PEP-235: подтверждения в шлюзе — таблица, ожидание, выполнение один раз

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-30 11:08:42 +00:00
parent 1000e0413e
commit 218315432d
9 changed files with 6597 additions and 13 deletions

View File

@ -0,0 +1,501 @@
// PEP-235 Access Hub: the owner confirms a gateway call whose grant mode is «спрашивать меня» (ask).
// Until «Разрешить» nothing reaches the service. An approval is bound to the exact request
// (fingerprint), to the connection's owner, has a term (24 h), runs at most once (claim
// approved → running in one UPDATE) and survives restarts (rows in connection_approvals).
// The journal gets the usual gateway rows; the body and the answer are stored only encrypted,
// for get_call, and wiped after a week. See openspec change pep-235-owner-approvals.
import { asIs, m as tr } from "@peppa/shared/i18n";
import { connectionApprovals, connections, projects, sessions, tasks, users, type Db } from "@peppa/db";
import { and, asc, desc, eq, inArray, isNotNull, lt, lte, or, sql } from "drizzle-orm";
import { createHash, randomUUID } from "node:crypto";
import { decrypt, encrypt } from "./crypto.ts";
import { logEvent } from "./audit.ts";
import { addMasterMessage } from "./chats.ts";
import { deliverToUser } from "./notifications.ts";
import { PeppaError } from "./errors.ts";
import { formatTaskKey } from "@peppa/shared";
type Row = typeof connectionApprovals.$inferSelect;
export type ApprovalStatus = Row["status"];
/** The exact call that runs after «Разрешить». */
export type ApprovalRequest =
| { kind: "http"; method: string; path: string; body: string | null; contentType: string | null }
| { kind: "use"; operation: string; args: Record<string, unknown> };
export const APPROVAL_TTL_MS = () => Math.max(1, Number(process.env.PEPPA_APPROVAL_TTL_HOURS ?? 24)) * 3600_000;
/** How long the agent's call waits for the answer before «ждёт подтверждения, id …». */
export const APPROVAL_WAIT_MS = () => Math.max(0, Number(process.env.PEPPA_APPROVAL_WAIT_SEC ?? 240)) * 1000;
/** A call started and not finished for this long was cut by a restart: never repeated. */
export const APPROVAL_RUNNING_STALE_MS = 10 * 60_000;
/** The answer for get_call is kept this long. */
export const APPROVAL_RESULT_KEEP_MS = 7 * 24 * 3600_000;
const SUMMARY_BODY_MAX = 300;
// ---------- pure: fingerprint and the owner's card ----------
function canonical(v: unknown): unknown {
if (Array.isArray(v)) return v.map(canonical);
if (v && typeof v === "object") return Object.fromEntries(Object.keys(v as object).sort().map((k) => [k, canonical((v as Record<string, unknown>)[k])]));
return v;
}
/** Same connection, project and exact request → same fingerprint; any change of a parameter → another. */
export function approvalFingerprint(connectionId: number, projectId: number, req: ApprovalRequest): string {
const r = req.kind === "http" ? { k: "http", m: req.method.toUpperCase(), p: req.path, b: req.body ?? "", t: req.contentType ?? "" } : { k: "use", o: req.operation.toLowerCase(), a: canonical(req.args) };
return createHash("sha256").update(JSON.stringify([connectionId, projectId, r])).digest("hex");
}
const SECRET_NAME = /(pass(word)?|secret|token|api[_-]?key|apikey|auth(orization)?|private[_-]?key|credential|signature|cookie|session)/i;
const SECRET_VALUE = /\b(?:sk|pk|rk|whsec|ghp|gho|ghs|xox[abprs]|glpat|AKIA)[-_A-Za-z0-9]{6,}|\bBearer\s+\S+|\beyJ[\w-]{8,}\.[\w-]+\.[\w-]+|-----BEGIN [A-Z ]+-----[\s\S]*?(-----END [A-Z ]+-----|$)/g;
/** A long run of letters and digits mixed (a key, a token) — numbers, words and e-mails stay. */
const LONG_TOKEN = /(?<![\w@.])(?=[A-Za-z0-9_\-+/=]*\d)(?=[A-Za-z0-9_\-+/=]*[A-Za-z])[A-Za-z0-9_\-+/=]{24,}(?![\w@])/g;
const HIDDEN = "•••";
/** Values that look like keys are hidden: by the field name (JSON, form, query) and by their shape. */
export function maskKeyLike(text: string): string {
let t = text;
// "token": "…" / token=… / token: …
t = t.replace(/("([^"\\]*)"\s*:\s*)"((?:[^"\\]|\\.)*)"/g, (all, head: string, name: string) => (SECRET_NAME.test(name) ? `${head}"${HIDDEN}"` : all));
t = t.replace(/(^|[?&\s,{])([A-Za-z_][\w.-]*)(=|:\s*)([^&\s,}"]+)/g, (all, pre: string, name: string, sep: string) => (SECRET_NAME.test(name) ? `${pre}${name}${sep}${HIDDEN}` : all));
t = t.replace(SECRET_VALUE, HIDDEN).replace(LONG_TOKEN, HIDDEN);
return t;
}
function shorten(text: string, max = SUMMARY_BODY_MAX): string {
const one = text.replace(/\s+/g, " ").trim();
return one.length > max ? `${one.slice(0, max - 1)}…` : one;
}
/** The owner's card of the request: method and path (query hidden), the body shortened and masked. */
export function approvalSummary(req: ApprovalRequest): { method: string; logPath: string; summary: string } {
if (req.kind === "http") {
const [p, q] = req.path.split("?");
const logPath = (p || "/").slice(0, 300);
const lines = [`${req.method.toUpperCase()} ${logPath}${q ? `?${maskKeyLike(q).slice(0, 120)}` : ""}`];
if (req.body) lines.push(shorten(maskKeyLike(req.body)));
return { method: req.method.toUpperCase().slice(0, 10), logPath, summary: lines.join("\n") };
}
const args = JSON.stringify(canonical(req.args));
return { method: req.operation.toUpperCase().slice(0, 10), logPath: "/", summary: [req.operation, args === "{}" ? "" : shorten(maskKeyLike(args))].filter(Boolean).join("\n") };
}
// ---------- views ----------
export interface ApprovalView {
id: number;
ownerId: number;
connectionId: number;
connectionName: string;
projectId: number;
projectKey: string;
taskId: number | null;
taskKey: string | null;
taskTitle: string | null;
sessionId: number | null;
agentName: string | null;
kind: "http" | "use";
method: string;
logPath: string;
summary: string;
status: ApprovalStatus;
idemKey: string;
expiresAt: Date;
decidedAt: Date | null;
resultReason: string | null;
createdAt: Date;
}
async function views(db: Db, rows: Row[]): Promise<ApprovalView[]> {
if (!rows.length) return [];
const conns = new Map((await db.select({ id: connections.id, name: connections.name }).from(connections).where(inArray(connections.id, [...new Set(rows.map((r) => r.connectionId))]))).map((c) => [c.id, c.name]));
const projs = new Map((await db.select({ id: projects.id, key: projects.key }).from(projects).where(inArray(projects.id, [...new Set(rows.map((r) => r.projectId))]))).map((p) => [p.id, p.key]));
const taskIds = [...new Set(rows.map((r) => r.taskId).filter((x): x is number => x != null))];
const ts = new Map(taskIds.length ? (await db.select({ id: tasks.id, number: tasks.number, title: tasks.title }).from(tasks).where(inArray(tasks.id, taskIds))).map((t) => [t.id, t]) : []);
return rows.map((r) => {
const t = r.taskId != null ? ts.get(r.taskId) : undefined;
const key = projs.get(r.projectId) ?? "?";
return {
id: r.id,
ownerId: r.ownerId,
connectionId: r.connectionId,
connectionName: conns.get(r.connectionId) ?? "?",
projectId: r.projectId,
projectKey: key,
taskId: r.taskId,
taskKey: t ? formatTaskKey(key, t.number) : null,
taskTitle: t?.title ?? null,
sessionId: r.sessionId,
agentName: r.agentName,
kind: r.kind,
method: r.method,
logPath: r.logPath,
summary: r.summary,
status: r.status,
idemKey: r.idemKey,
expiresAt: r.expiresAt,
decidedAt: r.decidedAt,
resultReason: r.resultReason,
createdAt: r.createdAt,
};
});
}
export async function getApproval(db: Db, id: number): Promise<ApprovalView | null> {
const [r] = await db.select().from(connectionApprovals).where(eq(connectionApprovals.id, id));
return r ? ((await views(db, [r]))[0] ?? null) : null;
}
// ---------- the gateway's side ----------
export interface ApprovalCtx {
conn: { id: number; ownerId: number; name: string };
session: { id: number; projectId: number; agentId: number | null; agentName: string | null };
request: ApprovalRequest;
/** The agent's own repeat key (idempotency_key); none — one is made. */
idemKey?: string | null;
now: Date;
}
/** What the gateway tells the agent while the owner has not decided. */
export interface ApprovalPending {
id: number;
status: ApprovalStatus;
expiresAt: Date;
}
export type ApprovalLookup =
| { state: "new"; row: Row }
| { state: "open"; row: Row }
/** Already decided and finished within the term: the stored outcome, never run again. */
| { state: "finished"; row: Row }
| { state: "conflict" };
/**
* The approval of this request: an open or finished one with the same fingerprint (a repeat of the
* agent makes no second approval and never runs twice), otherwise a new one + a message to the owner.
* The same idempotency key with other parameters is a conflict.
*/
export async function findOrCreateApproval(db: Db, c: ApprovalCtx, o: { announce?: boolean } = {}): Promise<ApprovalLookup> {
const fp = approvalFingerprint(c.conn.id, c.session.projectId, c.request);
const idem = c.idemKey?.trim().slice(0, 100) || null;
const live = and(eq(connectionApprovals.projectId, c.session.projectId), sql`${connectionApprovals.expiresAt} > ${c.now.getTime()}`, inArray(connectionApprovals.status, ["pending", "approved", "running", "done", "failed", "denied"]));
if (idem) {
const [same] = await db.select().from(connectionApprovals).where(and(eq(connectionApprovals.projectId, c.session.projectId), eq(connectionApprovals.idemKey, idem))).orderBy(desc(connectionApprovals.id)).limit(1);
if (same && same.fingerprint !== fp) return { state: "conflict" };
if (same && same.expiresAt > c.now && same.status !== "expired") return { state: ["pending", "approved", "running"].includes(same.status) ? "open" : "finished", row: same };
} else {
const [same] = await db.select().from(connectionApprovals).where(and(live, eq(connectionApprovals.fingerprint, fp))).orderBy(desc(connectionApprovals.id)).limit(1);
if (same) return { state: ["pending", "approved", "running"].includes(same.status) ? "open" : "finished", row: same };
}
const [s] = await db.select({ taskId: sessions.taskId }).from(sessions).where(eq(sessions.id, c.session.id));
const card = approvalSummary(c.request);
const [row] = await db
.insert(connectionApprovals)
.values({
ownerId: c.conn.ownerId,
connectionId: c.conn.id,
projectId: c.session.projectId,
sessionId: c.session.id,
taskId: s?.taskId ?? null,
agentId: c.session.agentId,
agentName: c.session.agentName,
kind: c.request.kind,
method: card.method,
logPath: card.logPath,
summary: card.summary,
fingerprint: fp,
requestEnc: encrypt(JSON.stringify(c.request)),
idemKey: idem ?? randomUUID(),
expiresAt: new Date(c.now.getTime() + APPROVAL_TTL_MS()),
createdAt: c.now,
})
.returning();
await logEvent(db, { projectId: row!.projectId, taskId: row!.taskId, sessionId: row!.sessionId, type: "connection_approval_requested", payload: { approvalId: row!.id, connectionId: c.conn.id, method: card.method, path: card.logPath } });
if (o.announce !== false) await announceApproval(db, row!.id).catch(() => null);
return { state: "new", row: row! };
}
/** The stored outcome of a finished call (what the agent gets from get_call). */
export function approvalOutcome(row: Pick<Row, "status" | "resultEnc" | "resultReason">): Record<string, unknown> | null {
if (row.status === "denied") return { ok: false, reason: "approval_denied" };
if (row.status === "expired") return { ok: false, reason: "approval_expired" };
if (row.status !== "done" && row.status !== "failed") return null;
if (row.resultEnc) {
try {
return JSON.parse(decrypt(row.resultEnc)) as Record<string, unknown>;
} catch {}
}
return { ok: false, reason: row.resultReason ?? "upstream_error" };
}
export const approvalRequest = (row: Pick<Row, "requestEnc">): ApprovalRequest => JSON.parse(decrypt(row.requestEnc)) as ApprovalRequest;
/** Atomically take an approved call to run; null — someone else runs it, or the term is over. */
export async function claimApproval(db: Db, id: number, now: Date): Promise<Row | null> {
const [row] = await db
.update(connectionApprovals)
.set({ status: "running", startedAt: now })
.where(and(eq(connectionApprovals.id, id), eq(connectionApprovals.status, "approved"), sql`${connectionApprovals.expiresAt} > ${now.getTime()}`))
.returning();
return row ?? null;
}
export async function finishApproval(db: Db, id: number, result: { ok: boolean; reason?: string } & Record<string, unknown>, now: Date): Promise<void> {
await db
.update(connectionApprovals)
.set({ status: result.ok ? "done" : "failed", resultEnc: encrypt(JSON.stringify(result)), resultReason: result.ok ? null : String(result.reason ?? "upstream_error"), finishedAt: now })
.where(and(eq(connectionApprovals.id, id), eq(connectionApprovals.status, "running")));
}
export async function setApprovalWaiting(db: Db, id: number, until: Date | null): Promise<void> {
await db.update(connectionApprovals).set({ waitingUntil: until }).where(eq(connectionApprovals.id, id));
}
export async function markApprovalDelivered(db: Db, id: number, now = new Date()): Promise<void> {
await db.update(connectionApprovals).set({ deliveredAt: now }).where(eq(connectionApprovals.id, id));
}
export async function readApproval(db: Db, id: number): Promise<Row | null> {
const [r] = await db.select().from(connectionApprovals).where(eq(connectionApprovals.id, id));
return r ?? null;
}
/**
* Run an approved call through the same gateway (every check again; only «ask» is skipped).
* At most once: the claim decides who runs it. Returns the outcome, or null when not claimed.
*/
/** Mocks of the gateway (drivers, fetch, resolver) for the run of an approved call. */
export type ApprovalGateway = import("./connection-gateway.ts").GatewayOptions;
export async function runApproval(db: Db, id: number, o: { now?: Date; gateway?: ApprovalGateway } = {}): Promise<Record<string, unknown> | null> {
const now = o.now ?? new Date();
const row = await claimApproval(db, id, now);
if (!row) return null;
let result: { ok: boolean; reason?: string } & Record<string, unknown>;
try {
const req = approvalRequest(row);
if (req.kind === "http") {
const { callConnection } = await import("./connections.ts");
result = await callConnection(db, { sessionId: row.sessionId, connection: row.connectionId, method: req.method, path: req.path, body: req.body, contentType: req.contentType }, { ...o.gateway, now, approved: { id: row.id, idemKey: row.idemKey } });
} else {
const { useConnection } = await import("./connection-gateway.ts");
result = await useConnection(db, { sessionId: row.sessionId, connection: row.connectionId, operation: req.operation, args: req.args }, { ...o.gateway, now, approved: { id: row.id, idemKey: row.idemKey } });
}
} catch {
result = { ok: false, reason: "upstream_error" };
}
await finishApproval(db, row.id, result, new Date());
return result;
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/**
* The agent's call waits for the owner up to `waitMs` (the row says so — the one who presses
* «Разрешить» leaves the run to it). Approved → runs here; decided otherwise → the outcome.
* Null: no answer yet, the agent gets «ждёт подтверждения» and asks get_call later.
*/
export async function waitForApproval(db: Db, id: number, waitMs: number, o: { gateway?: ApprovalGateway; pollMs?: number } = {}): Promise<Record<string, unknown> | null> {
if (waitMs <= 0) return null;
const end = Date.now() + waitMs;
await setApprovalWaiting(db, id, new Date(end + 5_000));
const step = async (): Promise<Record<string, unknown> | null> => {
const row = await readApproval(db, id);
if (!row) return { ok: false, reason: "approval_expired" };
if (row.status === "approved") {
const out = await runApproval(db, id, { gateway: o.gateway });
if (out) return out;
return null;
}
return approvalOutcome(row);
};
try {
while (Date.now() < end) {
const out = await step();
if (out) return out;
await sleep(Math.min(o.pollMs ?? 1000, Math.max(0, end - Date.now())));
}
} finally {
await setApprovalWaiting(db, id, null);
}
// The answer may have come right at the end: one last look (the decider then saw us waiting).
const last = await step();
return last;
}
/**
* The gateway at «ask»: find or make the approval of this exact request, wait for the owner in the
* same call, then run it here, or tell the agent «ждёт подтверждения, id …». A finished one within
* its term gives its stored outcome (never run twice); the same repeat key with other parameters
* is refused.
*/
export async function approvalGate(db: Db, c: ApprovalCtx, recordAsk: () => unknown, o: { waitMs?: number; gateway?: ApprovalGateway } = {}): Promise<Record<string, unknown>> {
const found = await findOrCreateApproval(db, c);
if (found.state === "conflict") return { ok: false, reason: "bad_request" };
if (found.state === "finished") {
if (!found.row.deliveredAt) await markApprovalDelivered(db, found.row.id, c.now);
return { ...approvalOutcome(found.row)!, approval: pendingView(found.row) };
}
await recordAsk();
const out = await waitForApproval(db, found.row.id, o.waitMs ?? APPROVAL_WAIT_MS(), { gateway: o.gateway });
if (out) {
await markApprovalDelivered(db, found.row.id);
return { ...out, approval: pendingView((await readApproval(db, found.row.id)) ?? found.row) };
}
const row = (await readApproval(db, found.row.id)) ?? found.row;
return { ok: false, reason: "needs_approval", approval: pendingView(row) };
}
const pendingView = (r: Row): ApprovalPending => ({ id: r.id, status: r.status, expiresAt: r.expiresAt });
// ---------- the owner's side ----------
/** The approval for the connection's owner only — anyone else (a member, a superadmin) gets null. */
export async function approvalForUser(db: Db, userId: number, id: number): Promise<ApprovalView | null> {
const [r] = await db.select({ a: connectionApprovals, connOwner: connections.ownerId }).from(connectionApprovals).innerJoin(connections, eq(connections.id, connectionApprovals.connectionId)).where(eq(connectionApprovals.id, id));
if (!r || r.a.ownerId !== userId || r.connOwner !== userId) return null;
return (await views(db, [r.a]))[0] ?? null;
}
/** «Ждут подтверждения»: the user's pending approvals, oldest first. */
export async function ownerPendingApprovals(db: Db, userId: number, now = new Date()): Promise<ApprovalView[]> {
const rows = await db
.select({ a: connectionApprovals })
.from(connectionApprovals)
.innerJoin(connections, eq(connections.id, connectionApprovals.connectionId))
.where(and(eq(connectionApprovals.ownerId, userId), eq(connections.ownerId, userId), eq(connectionApprovals.status, "pending"), sql`${connectionApprovals.expiresAt} > ${now.getTime()}`))
.orderBy(asc(connectionApprovals.id));
return views(db, rows.map((r) => r.a));
}
/**
* «Разрешить» / «Отклонить» by the connection's owner, once, within the term. Returns the view
* and whether the agent's call still waits (then it runs the call itself).
*/
export async function decideApproval(db: Db, userId: number, id: number, allow: boolean, o: { now?: Date; via?: string } = {}): Promise<{ approval: ApprovalView; waiting: boolean }> {
const now = o.now ?? new Date();
const v = await approvalForUser(db, userId, id);
if (!v) throw new PeppaError(tr("Подтверждение не найдено"));
if (v.status !== "pending") throw new PeppaError(tr("По этому запросу уже есть решение"));
if (v.expiresAt <= now) {
await db.update(connectionApprovals).set({ status: "expired" }).where(and(eq(connectionApprovals.id, id), eq(connectionApprovals.status, "pending")));
throw new PeppaError(tr("Срок подтверждения истёк: агент спросит снова, если действие ещё нужно"));
}
const [row] = await db
.update(connectionApprovals)
.set({ status: allow ? "approved" : "denied", decidedBy: userId, decidedAt: now })
.where(and(eq(connectionApprovals.id, id), eq(connectionApprovals.status, "pending")))
.returning();
if (!row) throw new PeppaError(tr("По этому запросу уже есть решение"));
await logEvent(db, { projectId: row.projectId, taskId: row.taskId, sessionId: row.sessionId, type: "connection_approval_decided", payload: { approvalId: id, allow, via: o.via ?? null, connectionId: row.connectionId, method: row.method, path: row.logPath } });
return { approval: (await views(db, [row]))[0]!, waiting: !!row.waitingUntil && row.waitingUntil > now };
}
// ---------- the agent's side ----------
/** get_call: the state and, when finished, the outcome — for the session's project only. */
export async function agentCall(db: Db, sessionId: number | null | undefined, id: number, now = new Date()): Promise<{ id: number; status: ApprovalStatus; expiresAt: Date; result: Record<string, unknown> | null }> {
if (sessionId == null) throw new PeppaError("No FORGE session");
const [s] = await db.select({ projectId: sessions.projectId }).from(sessions).where(eq(sessions.id, sessionId));
const row = await readApproval(db, id);
if (!s || !row || row.projectId !== s.projectId) throw new PeppaError(`Call #${id} not found in this project`);
let status = row.status;
if (status === "pending" && row.expiresAt <= now) {
await db.update(connectionApprovals).set({ status: "expired" }).where(and(eq(connectionApprovals.id, id), eq(connectionApprovals.status, "pending")));
status = "expired";
}
const result = approvalOutcome({ ...row, status });
if (result && !row.deliveredAt) await markApprovalDelivered(db, id, now);
return { id, status, expiresAt: row.expiresAt, result };
}
// ---------- the watchdog ----------
/**
* Pending past the term → expired (never run). Running for too long → failed «interrupted»
* (cut by a restart: the service's outcome is unknown, so it is not repeated). Approved and no
* call waiting for it → run once. Old answers wiped. Returns the ids that finished now.
*/
export async function approvalTick(db: Db, o: { now?: Date; gateway?: ApprovalGateway } = {}): Promise<{ expired: number[]; interrupted: number[]; ran: number[] }> {
const now = o.now ?? new Date();
const expired = (await db.update(connectionApprovals).set({ status: "expired" }).where(and(inArray(connectionApprovals.status, ["pending", "approved"]), lte(connectionApprovals.expiresAt, now))).returning({ id: connectionApprovals.id })).map((r) => r.id);
const interrupted = (
await db
.update(connectionApprovals)
.set({ status: "failed", resultReason: "interrupted", finishedAt: now, resultEnc: encrypt(JSON.stringify({ ok: false, reason: "interrupted" })) })
.where(and(eq(connectionApprovals.status, "running"), lt(connectionApprovals.startedAt, new Date(now.getTime() - APPROVAL_RUNNING_STALE_MS))))
.returning({ id: connectionApprovals.id })
).map((r) => r.id);
const ready = await db
.select({ id: connectionApprovals.id })
.from(connectionApprovals)
.where(and(eq(connectionApprovals.status, "approved"), or(sql`${connectionApprovals.waitingUntil} IS NULL`, lte(connectionApprovals.waitingUntil, now))))
.orderBy(asc(connectionApprovals.id))
.limit(20);
const ran: number[] = [];
for (const r of ready) if (await runApproval(db, r.id, { now, gateway: o.gateway })) ran.push(r.id);
await db.update(connectionApprovals).set({ resultEnc: null }).where(and(isNotNull(connectionApprovals.resultEnc), lt(connectionApprovals.finishedAt, new Date(now.getTime() - APPROVAL_RESULT_KEEP_MS))));
return { expired, interrupted, ran };
}
/** Finished calls whose agent has not got the outcome yet (no waiting call, no get_call). */
export async function undeliveredApprovals(db: Db, now = new Date()): Promise<Row[]> {
return db
.select()
.from(connectionApprovals)
.where(and(inArray(connectionApprovals.status, ["done", "failed", "denied", "expired"]), sql`${connectionApprovals.deliveredAt} IS NULL`, isNotNull(connectionApprovals.sessionId), or(sql`${connectionApprovals.waitingUntil} IS NULL`, lte(connectionApprovals.waitingUntil, now)), sql`${connectionApprovals.createdAt} > ${now.getTime() - APPROVAL_RESULT_KEEP_MS}`))
.orderBy(asc(connectionApprovals.id))
.limit(50);
}
/** The line a live agent gets when its call is decided (English: agents' language). */
export function approvalAgentNote(row: Pick<Row, "id" | "status" | "method" | "logPath" | "resultReason">): string {
const what = `${row.method} ${row.logPath}`;
if (row.status === "done") return `Call #${row.id} (${what}) was approved by the owner and ran. Get the answer with get_call(${row.id}).`;
if (row.status === "denied") return `Call #${row.id} (${what}) was refused by the owner. Do not repeat it; continue without it or ask the owner in plain words why it is needed.`;
if (row.status === "expired") return `Call #${row.id} (${what}) got no answer from the owner in time and was not run. Repeat it only if it is still needed.`;
return `Call #${row.id} (${what}) was approved but failed (${row.resultReason ?? "error"}). See get_call(${row.id}); if the reason is «interrupted» check the service before repeating.`;
}
// ---------- the message to the owner ----------
export const approvalUrl = (id: number) => `/connections#approval-${id}`;
/** Telegram buttons under the card: `ap:<id>:y` (allow once) / `ap:<id>:n` (refuse). */
export function approvalKeyboard(id: number): Array<Array<{ text: string; callback_data: string }>> {
return [[{ text: tr("✅ Разрешить один раз"), callback_data: `ap:${id}:y` }, { text: tr("❌ Отклонить"), callback_data: `ap:${id}:n` }]];
}
export function parseApprovalCallback(data: string): { id: number; allow: boolean } | null {
const m = /^ap:(\d+):(y|n)$/.exec(data);
return m ? { id: Number(m[1]), allow: m[2] === "y" } : null;
}
/** Who, what, where: the card for the owner (values that look like keys are already hidden). */
export function approvalText(v: ApprovalView): string {
const who = v.agentName ? tr("Агент {name}", { name: asIs(v.agentName) }) : tr("Агент");
const lines = [tr("{who} просит разрешить действие через подключение «{name}»", { who, name: asIs(v.connectionName) })];
if (v.taskKey) lines.push(tr("Задача: {task}", { task: asIs(`${v.taskKey}${v.taskTitle ? ` «${v.taskTitle}»` : ""}`) }));
lines.push(tr("Что: {what}", { what: asIs(v.summary) }));
lines.push(tr("До вашего ответа действие не выполняется. Без ответа запрос отменится сам."));
return lines.join("\n");
}
export async function announceApproval(db: Db, id: number): Promise<void> {
const v = await getApproval(db, id);
if (!v) return;
const text = approvalText(v);
const url = approvalUrl(id);
await addMasterMessage(db, v.ownerId, { kind: "event", important: true, text, dedupeKey: `master:approval:${id}`, url }).catch(() => null);
const [u] = await db.select().from(users).where(eq(users.id, v.ownerId));
if (!u) return;
await deliverToUser(db, u, {
event: "questions",
projectId: v.projectId,
dedupeKey: `approval:${id}:${u.telegramChatId}`,
pushKey: `approval:${id}:u${u.id}`,
telegram: { params: { text, reply_markup: { inline_keyboard: approvalKeyboard(id) } } },
push: { title: tr("Агент просит подтверждение"), body: text, url, tag: `approval:${id}` },
});
}

View File

@ -12,6 +12,7 @@ import { isIP } from "node:net";
import { addMasterMessage } from "./chats.ts";
import { appendJournal, type ConnectionJournalDecision } from "./connection-journal.ts";
import { DriverError, defaultDrivers, type GatewayDrivers, type MailRequest, type SshRequest } from "./connection-drivers.ts";
import { approvalGate, type ApprovalPending } from "./connection-approvals.ts";
import {
ANSWER_MAX_BYTES,
FILE_MAX_BYTES,
@ -61,6 +62,7 @@ import {
type ConnectionFetch,
type ConnectionReason,
type GrantMode,
type ApprovalOptions,
} from "./connections.ts";
import { deliverToUser } from "./notifications.ts";
import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts";
@ -76,12 +78,14 @@ export interface UseConnectionCall {
connection: string | number;
operation: string;
args?: Record<string, unknown>;
/** PEP-235: the agent's repeat key. */
idempotencyKey?: string | null;
}
export type UseConnectionResult =
| { ok: true; text: string; truncated: boolean }
/** `message` — only the service's own error text for `query_error` (an SQL mistake, a refused letter). */
| { ok: false; reason: ConnectionReason; message?: string };
| { ok: false; reason: ConnectionReason; message?: string; approval?: ApprovalPending };
export interface GatewayOptions {
drivers?: GatewayDrivers;
@ -305,7 +309,7 @@ export async function tellHostKeyChanged(db: Db, conn: Pick<Conn, "id" | "ownerI
* The gateway for non-HTTP connections. Decides, opens the secret, connects to a checked address,
* writes the journal and returns the service's answer for the agent.
*/
export async function useConnection(db: Db, call: UseConnectionCall, opts: GatewayOptions = {}): Promise<UseConnectionResult> {
export async function useConnection(db: Db, call: UseConnectionCall, opts: GatewayOptions & ApprovalOptions = {}): Promise<UseConnectionResult> {
const o = { ...defaults, ...opts };
const now = o.now ?? new Date();
const operation = String(call.operation ?? "").trim().toLowerCase();
@ -352,12 +356,16 @@ export async function useConnection(db: Db, call: UseConnectionCall, opts: Gatew
const op = PROTOCOL_OPERATIONS[protocol][operation];
if (!op) return deny("bad_request");
const mode = mine.reduce<GrantMode>((acc, g) => widest(acc, op.kind === "read" ? g.readMode : g.writeMode), "off");
if (mode === "ask") return deny("needs_approval");
if (mode !== "auto") return deny(op.kind === "read" ? "read_denied" : "write_denied");
if (mode !== "auto" && mode !== "ask") return deny(op.kind === "read" ? "read_denied" : "write_denied");
const prepared = prepare(protocol, (conn.config ?? {}) as Record<string, unknown>, operation, args);
if (typeof prepared === "string") return deny(prepared);
logPath = prepared.logPath;
if ((await recentCalls(db, s.id, now)) >= CONNECTION_RATE_PER_MIN) return deny("rate_limited");
// PEP-235: «спрашивать меня» — nothing runs until the owner allows this exact operation once.
if (mode === "ask" && !o.approved) {
const { drivers, fetch, resolve, env } = o;
return (await approvalGate(db, { conn, session: s, request: { kind: "use", operation, args }, idemKey: call.idempotencyKey, now }, () => record("denied", "needs_approval"), { waitMs: o.approvalWaitMs, gateway: { drivers, fetch, resolve, env } })) as UseConnectionResult;
}
let secret: string;
try {

View File

@ -25,6 +25,7 @@ import { PeppaError } from "./errors.ts";
import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts";
import { projectForUser } from "./users.ts";
import { pausedProjectIds } from "./project-pause.ts";
import { approvalGate, type ApprovalPending, type ApprovalRequest } from "./connection-approvals.ts";
export { isBlockedAddress } from "./connection-protocols.ts";
@ -72,7 +73,11 @@ export type ConnectionReason =
| "not_found"
| "query_error"
// PEP-260
| "binary_response";
| "binary_response"
// PEP-235
| "approval_denied"
| "approval_expired"
| "interrupted";
export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
no_session: tr("запрос не от агента FORGE"),
@ -87,7 +92,7 @@ export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
operation_denied: tr("операция не разрешена"),
read_denied: tr("чтение не разрешено"),
write_denied: tr("запись не разрешена"),
needs_approval: tr("нужно подтверждение владельца, а подтверждения пока не поддерживаются"),
needs_approval: tr("ждёт подтверждения владельца"),
owner_check: tr("проверка ключа владельцем"),
bad_path: tr("недопустимый путь"),
bad_request: tr("недопустимый запрос"),
@ -105,6 +110,9 @@ export const CONNECTION_REASON_TEXT: Record<ConnectionReason, string> = {
not_found: tr("не найдено"),
query_error: tr("сервис вернул ошибку"),
binary_response: tr("сервис вернул не текст: двоичные и сжатые ответы агенту не передаются"),
approval_denied: tr("владелец отклонил действие"),
approval_expired: tr("владелец не ответил вовремя, действие не выполнено"),
interrupted: tr("выполнение прервал перезапуск, исход у сервиса неизвестен"),
};
export interface ConnectionView {
@ -836,7 +844,7 @@ export function grantDecision(catalogId: string | null, grants: Array<{ operatio
}
/** Target URL and headers of a request with the key in its place; null — the path escapes the base. */
function buildRequest(conn: typeof connections.$inferSelect, secret: string, clean: { path: string; query: string }, contentType: string | null, body: Buffer | null): { url: URL; headers: Record<string, string> } | null {
function buildRequest(conn: typeof connections.$inferSelect, secret: string, clean: { path: string; query: string }, contentType: string | null, body: Buffer | null, idemKey: string | null = null): { url: URL; headers: Record<string, string> } | null {
const card = catalogService(conn.catalogId);
const base = new URL(conn.baseUrl);
const basePath = base.pathname.replace(/\/$/, "");
@ -855,6 +863,8 @@ function buildRequest(conn: typeof connections.$inferSelect, secret: string, cle
for (const [k, v] of Object.entries(card?.headers ?? {})) headers[k.toLowerCase()] = v;
if (contentType) headers["content-type"] = contentType;
if (body) headers["content-length"] = String(body.length);
// PEP-235: services that take a repeat key (Stripe…) never run the same call twice.
if (card?.idempotency && idemKey && body) headers["idempotency-key"] = `forge-${idemKey}`;
if (conn.authKind === "header" && conn.authHeader) headers[conn.authHeader.toLowerCase()] = secret;
else if (conn.authKind === "basic") headers.authorization = `Basic ${Buffer.from(secret).toString("base64")}`;
else if (conn.authKind === "bearer" || conn.authKind === "oauth") headers.authorization = `Bearer ${secret}`;
@ -979,11 +989,21 @@ export interface ConnectionCall {
path: string;
body?: string | null;
contentType?: string | null;
/** PEP-235: the agent's repeat key — the same key never makes a second approval or a second run. */
idempotencyKey?: string | null;
}
export type ConnectionResult =
| { ok: true; status: number; contentType: string | null; body: string; truncated: boolean }
| { ok: false; reason: ConnectionReason; status?: number };
| { ok: false; reason: ConnectionReason; status?: number; approval?: ApprovalPending };
/** PEP-235: options of a gateway call about owner confirmations. */
export interface ApprovalOptions {
/** Run of an approved call (connection-approvals.ts runApproval): «ask» is skipped, nothing else. */
approved?: { id: number; idemKey: string };
/** How long the call waits for the owner; default PEPPA_APPROVAL_WAIT_SEC (240 s). */
approvalWaitMs?: number;
}
/** One outbound request, injectable in tests. */
export type ConnectionFetch = (o: { url: URL; method: string; headers: Record<string, string>; body: Buffer | null; allowInternal?: boolean }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean; contentEncoding?: string | null }>;
@ -1110,7 +1130,7 @@ export async function refusedCallService(db: Db, sessionId: number, connection:
* The gateway: decides, injects the key, calls the service, masks the key in the answer and
* writes one journal row (method, path without query, decision, reason — never a key or a body).
*/
export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: ConnectionFetch; now?: Date; env?: NodeJS.ProcessEnv } = {}): Promise<ConnectionResult> {
export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?: ConnectionFetch; now?: Date; env?: NodeJS.ProcessEnv } & ApprovalOptions = {}): Promise<ConnectionResult> {
const now = o.now ?? new Date();
const method = String(call.method ?? "").toUpperCase();
const rawPath = String(call.path ?? "");
@ -1163,12 +1183,17 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
const clean = cleanPath(rawPath);
if (!clean) return deny("bad_path");
const refusal = grantDecision(conn.catalogId, mine, method, clean.path);
if (refusal) return deny(refusal);
if (refusal && refusal !== "needs_approval") return deny(refusal);
const body = call.body == null || call.body === "" ? null : Buffer.from(String(call.body));
if (body && (body.length > CONNECTION_BODY_MAX_BYTES || method === "GET")) return deny("bad_request");
const contentType = call.contentType?.trim() || (body ? "application/json" : null);
if (contentType && !CONTENT_TYPE_RE.test(contentType)) return deny("bad_request");
if ((await recentCalls(db, s.id, now)) >= CONNECTION_RATE_PER_MIN) return deny("rate_limited");
// PEP-235: «спрашивать меня» — nothing runs until the owner allows this exact request once.
if (refusal === "needs_approval" && !o.approved) {
const request: ApprovalRequest = { kind: "http", method, path: rawPath, body: body ? String(call.body) : null, contentType: body ? contentType : null };
return (await approvalGate(db, { conn, session: s, request, idemKey: call.idempotencyKey, now }, () => record("denied", "needs_approval", null), { waitMs: o.approvalWaitMs, gateway: { fetch: o.fetch, env: o.env } })) as ConnectionResult;
}
// PEP-252: a sign-in token is refreshed here when it is about to expire.
let cred = await connectionCredential(db, conn, { now });
@ -1178,7 +1203,8 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
return { ok: false, reason: cred.reason };
}
// Target = base (+ key in the path) + path; the host and the base path must survive URL parsing unchanged.
let built = buildRequest(conn, cred.secret, clean, contentType, body);
const idemKey = o.approved?.idemKey ?? (call.idempotencyKey?.trim().slice(0, 100) || null);
let built = buildRequest(conn, cred.secret, clean, contentType, body, idemKey);
if (!built) return deny("bad_path");
// Written before the service is called: a crash in the middle leaves «started, no result».
@ -1198,7 +1224,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
return { ok: false, reason: again.reason };
}
cred = again;
built = buildRequest(conn, cred.secret, clean, contentType, body)!;
built = buildRequest(conn, cred.secret, clean, contentType, body, idemKey)!;
res = await (o.fetch ?? defaultConnectionFetch)({ url: built.url, method, headers: built.headers, body });
}
if (res.status >= 300 && res.status < 400 && res.location) {

View File

@ -121,6 +121,7 @@ export * from "./connection-catalog.ts";
export * from "./access-requests.ts";
export * from "./connection-protocols.ts";
export * from "./connection-gateway.ts";
export * from "./connection-approvals.ts";
export { DriverError, type GatewayDrivers, type SqlTarget, type SqlRequest, type SshTarget, type SshRequest, type SshAnswer, type MailTarget, type MailRequest, type MailAnswer, type TlsMode } from "./connection-drivers.ts";
export * from "./connection-mask.ts";
export * from "./connection-oauth.ts";

View File

@ -4,7 +4,7 @@
// step-by-step instructions and a "rotated" mark that restarts their age. Values never leave.
import { m as tr } from "@peppa/shared/i18n";
import { randomBytes } from "node:crypto";
import { connections, oauthClients, oauthTokens, projects, projectSecrets, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db";
import { connectionApprovals, connections, oauthClients, oauthTokens, projects, projectSecrets, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db";
import { and, eq, gt, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
import { logEvent } from "./audit.ts";
import { encrypt, decrypt, encryptedWith, rotatingSecret } from "./crypto.ts";
@ -234,6 +234,9 @@ function encryptedColumns(db: Db) {
// keys. Old rows not yet moved by `upgradeConnectionKeys` still hold the key itself.
{ table: "connections", column: "dek_enc", rows: () => db.select({ id: connections.id, enc: connections.dekEnc }).from(connections).where(isNotNull(connections.dekEnc)), set: (id: number, enc: string) => db.update(connections).set({ dekEnc: enc }).where(eq(connections.id, id)) },
{ table: "connections", column: "secret_enc", rows: () => db.select({ id: connections.id, enc: connections.secretEnc }).from(connections).where(and(isNotNull(connections.secretEnc), isNull(connections.dekEnc))), set: (id: number, enc: string) => db.update(connections).set({ secretEnc: enc }).where(and(eq(connections.id, id), isNull(connections.dekEnc))) },
// PEP-235: the exact call waiting for the owner and its answer for get_call.
{ table: "connection_approvals", column: "request_enc", rows: () => db.select({ id: connectionApprovals.id, enc: connectionApprovals.requestEnc }).from(connectionApprovals), set: (id: number, enc: string) => db.update(connectionApprovals).set({ requestEnc: enc }).where(eq(connectionApprovals.id, id)) },
{ table: "connection_approvals", column: "result_enc", rows: () => db.select({ id: connectionApprovals.id, enc: connectionApprovals.resultEnc }).from(connectionApprovals).where(isNotNull(connectionApprovals.resultEnc)), set: (id: number, enc: string) => db.update(connectionApprovals).set({ resultEnc: enc }).where(eq(connectionApprovals.id, id)) },
];
}

View File

@ -0,0 +1,39 @@
CREATE TABLE `connection_approvals` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`owner_id` integer NOT NULL,
`connection_id` integer NOT NULL,
`project_id` integer NOT NULL,
`session_id` integer,
`task_id` integer,
`agent_id` integer,
`agent_name` text,
`kind` text NOT NULL,
`method` text NOT NULL,
`log_path` text NOT NULL,
`summary` text NOT NULL,
`fingerprint` text NOT NULL,
`request_enc` text NOT NULL,
`idem_key` text NOT NULL,
`status` text DEFAULT 'pending' NOT NULL,
`decided_by` integer,
`decided_at` integer,
`expires_at` integer NOT NULL,
`waiting_until` integer,
`result_enc` text,
`result_reason` text,
`started_at` integer,
`finished_at` integer,
`delivered_at` integer,
`created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`connection_id`) REFERENCES `connections`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null,
FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null,
FOREIGN KEY (`agent_id`) REFERENCES `agents`(`id`) ON UPDATE no action ON DELETE set null,
FOREIGN KEY (`decided_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
);
--> statement-breakpoint
CREATE INDEX `connection_approvals_owner` ON `connection_approvals` (`owner_id`,`status`);--> statement-breakpoint
CREATE INDEX `connection_approvals_fp` ON `connection_approvals` (`project_id`,`fingerprint`);--> statement-breakpoint
CREATE INDEX `connection_approvals_status` ON `connection_approvals` (`status`);

File diff suppressed because it is too large Load Diff

View File

@ -253,6 +253,13 @@
"when": 1795722167324,
"tag": "0035_access_requests",
"breakpoints": true
},
{
"idx": 36,
"version": "6",
"when": 1796036638399,
"tag": "0036_connection_approvals",
"breakpoints": true
}
]
}

View File

@ -818,6 +818,49 @@ export const accessRequests = sqliteTable(
(t) => [index("access_requests_project_service").on(t.projectId, t.serviceKey, t.status), index("access_requests_owner").on(t.ownerId, t.status)],
);
/**
* PEP-235: a gateway call waiting for the owner's «Разрешить» (grant mode `ask`). Survives restarts;
* executed at most once (claim approved → running), bound to the exact request (`fingerprint`).
*/
export const connectionApprovals = sqliteTable(
"connection_approvals",
{
id: integer("id").primaryKey({ autoIncrement: true }),
// The connection's owner: only they decide.
ownerId: integer("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
connectionId: integer("connection_id").notNull().references(() => connections.id, { onDelete: "cascade" }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
agentId: integer("agent_id").references(() => agents.id, { onDelete: "set null" }),
agentName: text("agent_name"),
kind: text("kind").$type<"http" | "use">().notNull(),
// HTTP method or the operation of use_connection; the path without a query string.
method: text("method").notNull(),
logPath: text("log_path").notNull(),
// The owner's card: the body shortened, values that look like keys hidden.
summary: text("summary").notNull(),
fingerprint: text("fingerprint").notNull(),
// The exact call (encrypt): what runs after «Разрешить».
requestEnc: text("request_enc").notNull(),
idemKey: text("idem_key").notNull(),
status: text("status").$type<"pending" | "approved" | "running" | "done" | "failed" | "denied" | "expired">().notNull().default("pending"),
decidedBy: integer("decided_by").references(() => users.id, { onDelete: "set null" }),
decidedAt: integer("decided_at", { mode: "timestamp_ms" }),
expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
// The agent's call is still waiting for the answer (it gets the result itself).
waitingUntil: integer("waiting_until", { mode: "timestamp_ms" }),
// The answer for get_call (encrypt; wiped after a week) and the gateway's reason.
resultEnc: text("result_enc"),
resultReason: text("result_reason"),
startedAt: integer("started_at", { mode: "timestamp_ms" }),
finishedAt: integer("finished_at", { mode: "timestamp_ms" }),
deliveredAt: integer("delivered_at", { mode: "timestamp_ms" }),
createdAt: createdAt(),
},
(t) => [index("connection_approvals_owner").on(t.ownerId, t.status), index("connection_approvals_fp").on(t.projectId, t.fingerprint), index("connection_approvals_status").on(t.status)],
);
/** PEP-26: the reviewer agent of a project (no row = off). */
export const reviewSettings = sqliteTable("review_settings", {
projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }),