502 lines
27 KiB
TypeScript
502 lines
27 KiB
TypeScript
// 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}` },
|
|
});
|
|
}
|