// PEP-234 Access Hub: a user's own external services («Подключения»). The key is stored // encrypted (crypto.ts, rotated with PEPPA_SECRET — secrets-audit encryptedColumns) and is // decrypted only here, in the server-side gateway `callConnection`, right before the request. // No function returns it: not to the owner, a superadmin, an agent, the journal or MCP. // Deny by default: an agent may call an operation only with an explicit grant of the owner for // the agent's project (and the agent, or any agent of the project). See the change // pep-234-access-hub (design.md — threat model). import { asIs, m as tr } from "@peppa/shared/i18n"; import { agents, connectionGrants, connectionLog, connections, projects, sessions, users, type Db } from "@peppa/db"; import { and, asc, count, desc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm"; import { lookup as dnsLookup, type LookupAddress } from "node:dns"; import { request as httpRequest, type IncomingMessage } from "node:http"; import { request as httpsRequest } from "node:https"; import { isIP } from "node:net"; import { getSetting, setSetting } from "./settings.ts"; import { isBlockedAddress, isGatewayProtocol, normalizeProtocolConfig, PROTOCOL_OPERATIONS, protocolAddress, protocolSecretError, ProtocolConfigError, type ConnectionProtocol, type GatewayProtocol } from "./connection-protocols.ts"; import { logEvent } from "./audit.ts"; import { catalogService, classifyRequest, type CatalogAuth, type CatalogCheck } from "./connection-catalog.ts"; import { addMasterMessage } from "./chats.ts"; import { appendJournal, type ConnectionJournalDecision } from "./connection-journal.ts"; import { decrypt, encrypt, newDataKey, openWithKey, sealWithKey } from "./crypto.ts"; import { deliverToUser } from "./notifications.ts"; import { PeppaError } from "./errors.ts"; import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts"; import { projectForUser } from "./users.ts"; export { isBlockedAddress } from "./connection-protocols.ts"; export const CONNECTION_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const; export type ConnectionMethod = (typeof CONNECTION_METHODS)[number]; export const CONNECTION_NAME_MAX = 60; export const CONNECTION_SECRET_MAX_BYTES = 8 * 1024; export const CONNECTION_BODY_MAX_BYTES = 64 * 1024; export const CONNECTION_RESPONSE_MAX_BYTES = 256 * 1024; export const CONNECTION_TIMEOUT_MS = 15_000; /** Gateway calls per session per minute. */ export const CONNECTION_RATE_PER_MIN = 60; export const CONNECTION_MAX_OPERATIONS = 20; /** Why a call was refused or failed — stored in the journal, words for people in REASON_TEXT. */ export type ConnectionReason = | "no_session" | "not_isolated" | "unknown_connection" | "ambiguous_connection" | "revoked" | "no_grant" | "operation_denied" | "read_denied" | "write_denied" | "needs_approval" | "owner_check" | "bad_path" | "bad_request" | "rate_limited" | "blocked_address" | "redirect" | "too_large" | "timeout" | "upstream_error" // PEP-251 | "wrong_protocol" | "auth_failed" | "host_key_changed" | "not_read_query" | "outside_root" | "not_found" | "query_error"; export const CONNECTION_REASON_TEXT: Record = { no_session: tr("запрос не от агента FORGE"), not_isolated: tr("агент работает без изоляции"), unknown_connection: tr("нет такого подключения"), ambiguous_connection: tr("несколько подключений с таким названием"), revoked: tr("подключение отозвано"), no_grant: tr("нет разрешения для проекта или агента"), operation_denied: tr("операция не разрешена"), read_denied: tr("чтение не разрешено"), write_denied: tr("запись не разрешена"), needs_approval: tr("нужно подтверждение владельца, а подтверждения пока не поддерживаются"), owner_check: tr("проверка ключа владельцем"), bad_path: tr("недопустимый путь"), bad_request: tr("недопустимый запрос"), rate_limited: tr("слишком много запросов"), blocked_address: tr("адрес сервиса недоступен"), redirect: tr("сервис перенаправил запрос"), too_large: tr("слишком большой ответ"), timeout: tr("сервис не ответил вовремя"), upstream_error: tr("сервис недоступен"), wrong_protocol: tr("у этого подключения другие операции"), auth_failed: tr("сервис не принял пароль или ключ"), host_key_changed: tr("ключ сервера изменился"), not_read_query: tr("запрос не только читает данные"), outside_root: tr("путь вне разрешённой папки"), not_found: tr("не найдено"), query_error: tr("сервис вернул ошибку"), }; export interface ConnectionView { id: number; name: string; baseUrl: string; authKind: CatalogAuth; authHeader: string | null; /** PEP-249: catalog card id, null = own service. */ catalogId: string | null; /** PEP-249: short name for agents (`stripe`). */ slug: string; /** PEP-251: http, or a database / server / storage / mailbox. */ protocol: ConnectionProtocol; /** PEP-251: host, port, user… of a non-HTTP connection (never the secret). */ config: Record | null; checkStatus: ConnectionCheckStatus | null; checkedAt: Date | null; status: "active" | "revoked"; hasKey: boolean; revokedAt: Date | null; lastUsedAt: Date | null; createdAt: Date; grants: ConnectionGrantView[]; } export interface ConnectionGrantView { id: number; projectId: number; projectKey: string; projectName: string; agentId: number | null; agentName: string | null; operations: string[]; readMode: GrantMode; writeMode: GrantMode; createdAt: Date; } export type GrantMode = "off" | "auto" | "ask"; export const GRANT_MODES: GrantMode[] = ["off", "auto", "ask"]; export type ConnectionCheckStatus = "ok" | "bad_key" | "down" | "host_key"; export const CONNECTION_CHECK_TEXT: Record = { ok: tr("ключ работает"), bad_key: tr("ключ не подходит"), down: tr("сервис не отвечает"), host_key: tr("ключ сервера изменился"), }; export interface ConnectionLogView { id: number; connectionId: number | null; connectionName: string | null; projectKey: string | null; agentName: string | null; sessionId: number | null; method: string; path: string; decision: "allowed" | "denied" | "failed"; reason: string | null; statusCode: number | null; /** PEP-254: how long the service took (from the result row). */ durationMs: number | null; /** done — a decision or a result is written; running — the call is in flight; unfinished — started, no result (a crash in the middle). */ state: "done" | "running" | "unfinished"; createdAt: Date; } export const allowPrivate = (env: NodeJS.ProcessEnv = process.env) => env.PEPPA_CONNECTIONS_ALLOW_PRIVATE === "1"; const allowUnisolated = (env: NodeJS.ProcessEnv = process.env) => env.PEPPA_CONNECTIONS_UNISOLATED === "on"; // ---------- addresses ---------- /** The service address of a connection: https, no login/password, no query or fragment. */ export function parseBaseUrl(raw: string, env: NodeJS.ProcessEnv = process.env): string { const bad = () => new PeppaError(tr("Адрес сервиса должен начинаться с https:// и не содержать логин, пароль, «?» и «#»")); let u: URL; try { u = new URL(raw.trim()); } catch { throw bad(); } if (u.protocol !== "https:" && !(u.protocol === "http:" && allowPrivate(env))) throw bad(); if (u.username || u.password || u.search || u.hash || raw.includes("?") || raw.includes("#")) throw bad(); if (!u.hostname) throw bad(); if (!allowPrivate(env) && (isBlockedAddress(u.hostname.replace(/^\[|\]$/g, "")) || /^(localhost|.*\.localhost|.*\.local|.*\.internal)$/i.test(u.hostname))) throw new PeppaError(tr("Этот адрес сервиса недоступен: укажите адрес в интернете")); return u.origin + u.pathname.replace(/\/+$/, ""); } /** * A path from an agent → the clean path (with its query) or null. Refuses everything that could * step out of the base address or confuse a server: dot segments, `//`, `\`, encoded dots and * slashes, control characters, a scheme or `@`. */ export function cleanPath(raw: string): { path: string; query: string } | null { if (typeof raw !== "string" || !raw.startsWith("/") || raw.length > 2048) return null; if (/[\u0000-\u001f\u007f\s\\#@]/.test(raw)) return null; const [path, ...rest] = raw.split("?"); const query = rest.join("?"); if (!path || path.includes("//") || /%(2e|2f|5c|25|00)/i.test(path)) return null; if (/:/.test(path)) return null; if (path.split("/").some((seg) => seg === "." || seg === "..")) return null; if (/[^A-Za-z0-9\-._~!$&'()*+,;=:@%/]/.test(path)) return null; if (/[^A-Za-z0-9\-._~!$&'()*+,;=:@%/?]/.test(query)) return null; return { path, query }; } /** "GET /items/" → {method, prefix}; null when malformed. */ export function parseOperation(op: string): { method: ConnectionMethod; prefix: string } | null { const m = op.trim().match(/^([A-Za-z]+)\s+(\/\S*)$/); if (!m) return null; const method = m[1]!.toUpperCase() as ConnectionMethod; if (!CONNECTION_METHODS.includes(method)) return null; const c = cleanPath(m[2]!); if (!c || c.query) return null; const prefix = c.path.length > 1 ? c.path.replace(/\/+$/, "") : "/"; return { method, prefix }; } /** Prefix match on a segment boundary: "/items" covers "/items" and "/items/5", not "/itemsX". */ export function operationAllows(ops: string[], method: string, path: string): boolean { return ops.some((o) => { const p = parseOperation(o); if (!p || p.method !== method.toUpperCase()) return false; return p.prefix === "/" || path === p.prefix || path.startsWith(`${p.prefix}/`); }); } export function normalizeOperations(raw: string[] | string, o: { allowEmpty?: boolean } = {}): string[] { const list = (Array.isArray(raw) ? raw : raw.split(/\r?\n|,/)).map((s) => s.trim()).filter(Boolean); if (!list.length && o.allowEmpty) return []; if (!list.length) throw new PeppaError(tr("Укажите хотя бы одну операцию, например «GET /items»")); if (list.length > CONNECTION_MAX_OPERATIONS) throw new PeppaError(tr("Не больше {n} операций в одном разрешении", { n: CONNECTION_MAX_OPERATIONS })); const out: string[] = []; for (const o of list) { const p = parseOperation(o); if (!p) throw new PeppaError(tr("Операция «{op}» не распознана: нужен метод (GET, POST, PUT, PATCH, DELETE) и путь с «/»", { op: o.slice(0, 80) })); out.push(`${p.method} ${p.prefix}`); } return [...new Set(out)]; } // ---------- owner's management ---------- async function ownConnection(db: Db, userId: number, connectionId: number) { const [c] = await db.select().from(connections).where(eq(connections.id, connectionId)); // No superadmin bypass: a connection is its owner's alone. if (!c || c.ownerId !== userId) throw new PeppaError(tr("Подключение не найдено")); return c; } function nameError(name: string): string | null { if (!name || name.length > CONNECTION_NAME_MAX) return tr("Название подключения: от 1 до {n} символов", { n: CONNECTION_NAME_MAX }); if (/[\u0000-\u001f\u007f]/.test(name)) return tr("Название подключения содержит недопустимые символы"); return null; } function secretError(secret: string): string | null { if (!secret) return tr("Ключ доступа пустой"); if (Buffer.byteLength(secret) > CONNECTION_SECRET_MAX_BYTES) return tr("Ключ доступа больше 8 КБ"); if (/[\r\n\u0000]/.test(secret)) return tr("Ключ доступа должен быть одной строкой"); return null; } const HEADER_RE = /^[A-Za-z][A-Za-z0-9-]{0,63}$/; const FORBIDDEN_HEADERS = new Set(["host", "content-length", "content-type", "transfer-encoding", "connection", "cookie", "accept-encoding"]); // ---------- PEP-254: one data key per connection (envelope) ---------- const SECRET_V2 = "v2."; const SECRET_AAD = "connection-secret"; /** * Encrypts a connection key with a fresh data key of its own; the data key goes under * PEPPA_SECRET. Decrypting one connection's data key opens nothing else. */ export function sealConnectionSecret(secret: string): { secretEnc: string; dekEnc: string } { const dek = newDataKey(); return { secretEnc: SECRET_V2 + sealWithKey(dek, secret, SECRET_AAD), dekEnc: encrypt(dek.toString("base64url")) }; } /** The key of a connection (gateway and check only — never returned anywhere else). */ export function openConnectionSecret(c: { secretEnc: string | null; dekEnc: string | null }): string | null { if (!c.secretEnc) return null; if (!c.dekEnc || !c.secretEnc.startsWith(SECRET_V2)) return decrypt(c.secretEnc); // an old row return openWithKey(Buffer.from(decrypt(c.dekEnc), "base64url"), c.secretEnc.slice(SECRET_V2.length), SECRET_AAD); } /** * Moves connections stored before PEP-254 (secret under PEPPA_SECRET) to their own data key. * The key is decrypted and re-encrypted inside this process only. Unreadable rows are skipped. */ export async function upgradeConnectionKeys(db: Db): Promise<{ upgraded: number; unreadable: number }> { const rows = await db.select({ id: connections.id, secretEnc: connections.secretEnc }).from(connections).where(and(isNotNull(connections.secretEnc), isNull(connections.dekEnc))); let upgraded = 0; let unreadable = 0; for (const r of rows) { let plain: string; try { plain = decrypt(r.secretEnc!); } catch { unreadable++; continue; } await db.update(connections).set(sealConnectionSecret(plain)).where(and(eq(connections.id, r.id), isNull(connections.dekEnc))); upgraded++; } return { upgraded, unreadable }; } export interface ConnectionInput { /** Default: the catalog card's name. */ name?: string; /** Required for an own service and for catalog cards with their own address (Gitea…). */ baseUrl?: string; secret: string; authKind?: CatalogAuth; authHeader?: string | null; /** PEP-249: a catalog card — address, key placement and rules come from it. */ catalogId?: string | null; /** PEP-251: a database, a server, a storage or a mailbox instead of an HTTP service. */ protocol?: ConnectionProtocol; /** PEP-251: the form fields of that protocol (host, port, user…). */ config?: Record; } const QUERY_PARAM_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/; const PATH_KEY_RE = /^[A-Za-z0-9:_.-]{4,512}$/; /** «Мой магазин» → «moi-magazin»; latin, digits and «-», ≤ 40. */ export function slugify(name: string): string { const map: Record = { а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "i", к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s", т: "t", у: "u", ф: "f", х: "h", ц: "c", ч: "ch", ш: "sh", щ: "sh", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya", ә: "a", ғ: "g", қ: "k", ң: "n", ө: "o", ұ: "u", ү: "u", һ: "h", і: "i" }; const latin = [...name.toLowerCase()].map((ch) => map[ch] ?? ch).join(""); return latin.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); } async function freeSlug(db: Db, userId: number, base: string, exceptId?: number): Promise { const root = base || "service"; const taken = new Set((await db.select({ id: connections.id, slug: connections.slug }).from(connections).where(eq(connections.ownerId, userId))).filter((r) => r.id !== exceptId).map((r) => r.slug)); if (!taken.has(root)) return root; for (let i = 2; ; i++) if (!taken.has(`${root}-${i}`)) return `${root}-${i}`; } function keyShapeError(authKind: CatalogAuth, secret: string): string | null { if (authKind === "basic" && !/^[^:]+:.+$/.test(secret)) return tr("Для этого сервиса вставьте ключ как «логин:пароль» через двоеточие"); if (authKind === "path" && !PATH_KEY_RE.test(secret)) return tr("Ключ доступа содержит недопустимые символы"); return null; } export async function createConnection(db: Db, userId: number, i: ConnectionInput): Promise { if (i.protocol && i.protocol !== "http") return createProtocolConnection(db, userId, i); const card = i.catalogId ? catalogService(i.catalogId) : null; if (i.catalogId && !card) throw new PeppaError(tr("Такого сервиса нет в каталоге")); const name = (i.name ?? "").trim() || card?.name || ""; const err = nameError(name) ?? secretError(i.secret); if (err) throw new PeppaError(err); let baseRaw = card && !card.baseEditable ? card.baseUrl : (i.baseUrl ?? "").trim(); if (!baseRaw) throw new PeppaError(tr("Укажите адрес сервиса")); if (card?.baseEditable && baseRaw === card.baseUrl) throw new PeppaError(tr("Укажите адрес своего сервиса вместо образца")); const baseUrl = parseBaseUrl(baseRaw); const authKind: CatalogAuth = card ? card.auth : (["header", "basic", "query"] as const).find((k) => k === i.authKind) ?? "bearer"; const authHeader = card ? (card.authParam ?? null) : authKind === "header" || authKind === "query" ? (i.authHeader ?? "").trim() : null; if (!card && authKind === "header" && (!HEADER_RE.test(authHeader!) || FORBIDDEN_HEADERS.has(authHeader!.toLowerCase()))) throw new PeppaError(tr("Имя заголовка для ключа: латинские буквы, цифры и дефис, например X-Api-Key")); if (!card && authKind === "query" && !QUERY_PARAM_RE.test(authHeader!)) throw new PeppaError(tr("Имя параметра для ключа: латинские буквы, цифры, дефис и подчёркивание, например key")); const shape = keyShapeError(authKind, i.secret); if (shape) throw new PeppaError(shape); const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name))); if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name })); const slug = await freeSlug(db, userId, card?.id ?? slugify(name)); const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind, authHeader, catalogId: card?.id ?? null, slug, ...sealConnectionSecret(i.secret) }).returning({ id: connections.id }); return (await listConnections(db, userId)).find((c) => c.id === row!.id)!; } // ---------- PEP-251: platform's own servers that may have internal addresses ---------- const INTERNAL_HOSTS_KEY = "connections.internal_hosts"; /** Host names / addresses a connection may reach although they resolve to internal addresses. */ export async function internalHosts(db: Db): Promise { return (await getSetting(db, INTERNAL_HOSTS_KEY)) ?? []; } /** Superadmin only: FORGE's own product servers. Everyone else gets internal addresses refused. */ export async function setInternalHosts(db: Db, actor: { id: number; login: string }, hosts: string[]): Promise { const { isSuperadmin } = await import("./monitor.ts"); if (!(await isSuperadmin(db, actor))) throw new PeppaError(tr("Это может только администратор FORGE")); return writeInternalHosts(db, hosts); } /** The CLI (an admin tool on the machine itself) writes the list without a web actor. */ export async function writeInternalHosts(db: Db, hosts: string[]): Promise { const list = [...new Set(hosts.map((h) => h.trim().toLowerCase().replace(/^\[|\]$/g, "")).filter(Boolean))]; if (list.length > 50 || list.some((h) => !/^[a-z0-9.:-]{1,253}$/.test(h))) throw new PeppaError(tr("Список адресов: имена серверов или IP-адреса, не больше 50")); await setSetting(db, INTERNAL_HOSTS_KEY, list); return list; } async function createProtocolConnection(db: Db, userId: number, i: ConnectionInput): Promise { const protocol = i.protocol as GatewayProtocol; if (!isGatewayProtocol(protocol)) throw new PeppaError(tr("Такого вида подключения нет")); const name = (i.name ?? "").trim(); const err = nameError(name) ?? protocolSecretError(protocol, i.secret); if (err) throw new PeppaError(err); let config: Record; try { config = { ...normalizeProtocolConfig(protocol, i.config ?? {}, { internal: await internalHosts(db), allowPrivate: allowPrivate() }) }; } catch (e) { if (e instanceof ProtocolConfigError) throw new PeppaError(e.message); throw e; } const [dup] = await db.select({ id: connections.id }).from(connections).where(and(eq(connections.ownerId, userId), eq(connections.name, name))); if (dup) throw new PeppaError(tr("Подключение «{name}» уже есть", { name })); const slug = await freeSlug(db, userId, slugify(name) || protocol); const baseUrl = protocolAddress(protocol, config as never); const [row] = await db.insert(connections).values({ ownerId: userId, name, baseUrl, authKind: "bearer", authHeader: null, catalogId: null, slug, protocol, config, ...sealConnectionSecret(i.secret) }).returning({ id: connections.id }); return (await listConnections(db, userId)).find((c) => c.id === row!.id)!; } /** * PEP-251: the server showed a new key and the owner confirms it is theirs — the next contact * pins whatever the server shows. */ export async function resetHostKey(db: Db, userId: number, connectionId: number): Promise { const c = await ownConnection(db, userId, connectionId); if (c.protocol !== "ssh") throw new PeppaError(tr("У этого подключения нет ключа сервера")); await db.update(connections).set({ config: { ...(c.config ?? {}), hostKey: null }, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, c.id)); for (const g of await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id))) await logEvent(db, { projectId: g.projectId, type: "connection_host_key_reset", payload: { connectionId: c.id } }); } /** Replaces the key; also brings a revoked connection back with its grants. */ export async function replaceConnectionSecret(db: Db, userId: number, connectionId: number, secret: string): Promise { const c = await ownConnection(db, userId, connectionId); const err = isGatewayProtocol(c.protocol) ? protocolSecretError(c.protocol, secret) : (secretError(secret) ?? keyShapeError(c.authKind, secret)); if (err) throw new PeppaError(err); // A new key: the old check result and the «key stopped working» message no longer apply. await db.update(connections).set({ ...sealConnectionSecret(secret), status: "active", revokedAt: null, checkStatus: null, checkedAt: null, checkAlertedAt: null }).where(eq(connections.id, connectionId)); } /** * Instant revoke: the stored key is wiped, so the very next gateway call is refused (`revoked`) * and even a copy of the database no longer holds it. Grants stay visible to the owner and * start working again only after a new key (`replaceConnectionSecret`). */ export async function revokeConnection(db: Db, userId: number, connectionId: number): Promise { const c = await ownConnection(db, userId, connectionId); await db.update(connections).set({ status: "revoked", secretEnc: null, dekEnc: null, revokedAt: new Date() }).where(eq(connections.id, c.id)); const grants = await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, c.id)); for (const projectId of new Set(grants.map((g) => g.projectId))) await logEvent(db, { projectId, type: "connection_revoked", payload: { connectionId: c.id } }); } export async function deleteConnection(db: Db, userId: number, connectionId: number): Promise { await revokeConnection(db, userId, connectionId); await db.delete(connectionGrants).where(eq(connectionGrants.connectionId, connectionId)); await db.delete(connections).where(eq(connections.id, connectionId)); } export interface GrantInput { projectId: number; agentId?: number | null; /** «Тонкая настройка»: «METHOD /prefix» lines; may be empty when a mode is on. */ operations?: string[] | string; /** PEP-249: reading / writing by the catalog's read rule. */ readMode?: GrantMode; writeMode?: GrantMode; } const mode = (m: unknown): GrantMode => (GRANT_MODES.includes(m as GrantMode) ? (m as GrantMode) : "off"); export async function grantConnection(db: Db, userId: number, connectionId: number, g: GrantInput): Promise { const c = await ownConnection(db, userId, connectionId); if (c.status !== "active") throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа")); await projectForUser(db, userId, g.projectId); // the owner gives access only to their projects const agentId = g.agentId ?? null; if (agentId != null) { const [a] = await db.select({ id: agents.id }).from(agents).where(eq(agents.id, agentId)); if (!a) throw new PeppaError(tr("Агент не найден")); } const readMode = mode(g.readMode); const writeMode = mode(g.writeMode); const anyMode = readMode !== "off" || writeMode !== "off"; const operations = normalizeOperations(g.operations ?? [], { allowEmpty: true }); if (!anyMode && !operations.length) throw new PeppaError(tr("Разрешите чтение, запись или хотя бы одну операцию")); const existing = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, c.id), eq(connectionGrants.projectId, g.projectId)))).find((x) => x.agentId === agentId); let id: number; if (existing) { await db.update(connectionGrants).set({ operations, readMode, writeMode, createdBy: userId }).where(eq(connectionGrants.id, existing.id)); id = existing.id; } else { const [row] = await db.insert(connectionGrants).values({ connectionId: c.id, projectId: g.projectId, agentId, operations, readMode, writeMode, createdBy: userId }).returning({ id: connectionGrants.id }); id = row!.id; } await logEvent(db, { projectId: g.projectId, type: "connection_granted", payload: { connectionId: c.id, agentId, operations, readMode, writeMode } }); return (await grantViews(db, [c.id])).find((x) => x.id === id)!; } export async function revokeGrant(db: Db, userId: number, grantId: number): Promise { const [g] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grantId)); if (!g) throw new PeppaError(tr("Разрешение не найдено")); await ownConnection(db, userId, g.connectionId); await db.delete(connectionGrants).where(eq(connectionGrants.id, grantId)); await logEvent(db, { projectId: g.projectId, type: "connection_grant_revoked", payload: { connectionId: g.connectionId, agentId: g.agentId } }); } async function grantViews(db: Db, connectionIds: number[]): Promise> { if (!connectionIds.length) return []; return db .select({ id: connectionGrants.id, connectionId: connectionGrants.connectionId, projectId: connectionGrants.projectId, projectKey: projects.key, projectName: projects.name, agentId: connectionGrants.agentId, agentName: agents.name, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode, createdAt: connectionGrants.createdAt, }) .from(connectionGrants) .innerJoin(projects, eq(projects.id, connectionGrants.projectId)) .leftJoin(agents, eq(agents.id, connectionGrants.agentId)) .where(inArray(connectionGrants.connectionId, connectionIds)) .orderBy(asc(projects.key), asc(connectionGrants.id)); } /** Short name for agents; connections made before PEP-249 get one from their name. */ export const connectionSlug = (r: { id: number; name: string; slug: string | null }) => r.slug || slugify(r.name) || `c${r.id}`; /** The user's own connections with grants; never the key. */ export async function listConnections(db: Db, userId: number): Promise { const rows = await db.select().from(connections).where(eq(connections.ownerId, userId)).orderBy(asc(connections.name)); const grants = await grantViews(db, rows.map((r) => r.id)); return rows.map((r) => ({ id: r.id, name: r.name, baseUrl: r.baseUrl, authKind: r.authKind, authHeader: r.authHeader, catalogId: r.catalogId, slug: connectionSlug(r), protocol: r.protocol, config: r.config ?? null, checkStatus: r.checkStatus, checkedAt: r.checkedAt, status: r.status, hasKey: !!r.secretEnc, revokedAt: r.revokedAt, lastUsedAt: r.lastUsedAt, createdAt: r.createdAt, grants: grants.filter((g) => g.connectionId === r.id).map(({ connectionId: _, ...g }) => g), })); } /** The owner's journal (all their connections, or one). */ export async function connectionJournal(db: Db, userId: number, o: { connectionId?: number; limit?: number; now?: Date } = {}): Promise { const calls = await db .select({ id: connectionLog.id, connectionId: connectionLog.connectionId, connectionName: connectionLog.connectionName, projectKey: sql`coalesce(${connectionLog.projectKey}, ${projects.key})`, agentName: connectionLog.agentName, sessionId: connectionLog.sessionId, method: connectionLog.method, path: connectionLog.path, decision: connectionLog.decision, reason: connectionLog.reason, statusCode: connectionLog.statusCode, durationMs: connectionLog.durationMs, createdAt: connectionLog.createdAt, }) .from(connectionLog) .leftJoin(projects, eq(projects.id, connectionLog.projectId)) .where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "call"), o.connectionId != null ? eq(connectionLog.connectionId, o.connectionId) : undefined)) .orderBy(desc(connectionLog.id)) .limit(Math.min(o.limit ?? 100, 500)); // PEP-254: an allowed call is written before the request; its result is a row of its own. const ids = calls.filter((c) => c.decision === "allowed" && c.statusCode == null).map((c) => c.id); const results = ids.length ? await db.select().from(connectionLog).where(and(eq(connectionLog.ownerId, userId), eq(connectionLog.kind, "result"), inArray(connectionLog.parentId, ids))) : []; const byParent = new Map(results.map((r) => [r.parentId!, r])); const now = (o.now ?? new Date()).getTime(); return calls.map((c) => { const r = byParent.get(c.id); if (r) return { ...c, decision: r.decision, reason: r.reason, statusCode: r.statusCode, durationMs: r.durationMs, state: "done" as const }; const open = c.decision === "allowed" && c.statusCode == null && ids.includes(c.id); if (!open) return { ...c, state: "done" as const }; return { ...c, state: now - c.createdAt.getTime() > CONNECTION_TIMEOUT_MS * 2 ? ("unfinished" as const) : ("running" as const) }; }); } /** Agents to choose from in a grant (the platform's team). */ export async function grantableAgents(db: Db): Promise> { return db.select({ id: agents.id, name: agents.name }).from(agents).orderBy(asc(agents.name)); } // ---------- agent side ---------- export interface SessionCtx { id: number; projectId: number; agentId: number | null; agentName: string | null; container: string | null; } export const agentIsolated = (s: SessionCtx, env: NodeJS.ProcessEnv = process.env) => !!s.container || allowUnisolated(env); /** false: the session's agent runs outside a container and the gateway refuses it. */ export async function sessionIsolated(db: Db, sessionId: number): Promise { const s = await sessionCtx(db, sessionId); return !!s && agentIsolated(s); } export async function sessionCtx(db: Db, sessionId: number | null | undefined): Promise { if (sessionId == null) return null; const [s] = await db .select({ id: sessions.id, projectId: sessions.projectId, agentId: sessions.agentId, agentName: agents.name, container: sessions.container }) .from(sessions) .leftJoin(agents, eq(agents.id, sessions.agentId)) .where(eq(sessions.id, sessionId)); return s ?? null; } export interface AgentConnection { id: number; name: string; /** Short name to call it by (`stripe`). */ slug: string; /** Catalog service name, null = own service. */ service: string | null; baseUrl: string; docsUrl: string | null; readMode: GrantMode; writeMode: GrantMode; operations: string[]; checkStatus: ConnectionCheckStatus | null; /** PEP-251: http — call_connection; others — use_connection with these operations. */ protocol: ConnectionProtocol; protocolOperations: Array<{ name: string; kind: "read" | "write"; args: string[]; help: string }>; } const RANK: Record = { off: 0, ask: 1, auto: 2 }; /** The widest of several grants: auto > ask > off. */ export const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a); /** What this session's agent may use: active connections granted to its project and agent. */ export async function agentConnections(db: Db, sessionId: number): Promise { const s = await sessionCtx(db, sessionId); // Like the gateway: an unisolated agent is refused, so it is shown nothing. if (!s || !agentIsolated(s)) return []; const rows = await db .select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode }) .from(connectionGrants) .innerJoin(connections, eq(connections.id, connectionGrants.connectionId)) .where(and(eq(connectionGrants.projectId, s.projectId), eq(connections.status, "active"))) .orderBy(asc(connections.name)); const by = new Map(); for (const r of rows) { if (r.agentId != null && r.agentId !== s.agentId) continue; const card = catalogService(r.c.catalogId); const proto = r.c.protocol; const protocolOperations = isGatewayProtocol(proto) ? Object.entries(PROTOCOL_OPERATIONS[proto]).map(([name, op]) => ({ name, ...op })) : []; const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.checkStatus, protocol: proto, protocolOperations }; c.operations = [...new Set([...c.operations, ...r.operations])]; c.readMode = widest(c.readMode, r.readMode); c.writeMode = widest(c.writeMode, r.writeMode); by.set(r.c.id, c); } return [...by.values()]; } /** * The gateway's decision for one agent request over its grants (PEP-249): a «Тонкая настройка» * line allows; otherwise the request is read or write by the catalog rule and the widest mode * decides — auto runs, ask waits for the owner (PEP-235; until then refused), off refuses. */ export function grantDecision(catalogId: string | null, grants: Array<{ operations: string[]; readMode: GrantMode; writeMode: GrantMode }>, method: string, path: string): ConnectionReason | null { if (operationAllows(grants.flatMap((g) => g.operations), method, path)) return null; const kind = classifyRequest(catalogId, method, path); const m = grants.reduce((acc, g) => widest(acc, kind === "read" ? g.readMode : g.writeMode), "off"); if (m === "auto") return null; if (m === "ask") return "needs_approval"; // No mode at all and only fine-grained lines: keep PEP-234's wording. if (grants.every((g) => g.readMode === "off" && g.writeMode === "off")) return "operation_denied"; return kind === "read" ? "read_denied" : "write_denied"; } /** 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 } | null { const card = catalogService(conn.catalogId); const base = new URL(conn.baseUrl); const basePath = base.pathname.replace(/\/$/, ""); // Only Telegram's catalog card uses it: the key goes right after the base as «/bot». const keyPath = conn.authKind === "path" ? `${basePath}/bot${secret}` : basePath; const params = new URLSearchParams(clean.query); if (conn.authKind === "query" && conn.authHeader) { params.delete(conn.authHeader); // the agent can't pass its own key params.set(conn.authHeader, secret); } const qs = params.toString(); const url = new URL(base.origin + keyPath + clean.path + (qs ? `?${qs}` : "")); if (url.origin !== base.origin || !(url.pathname === keyPath || url.pathname.startsWith(`${keyPath}/`))) return null; // Only these headers reach the service: the agent can't add or override any other. const headers: Record = { "user-agent": "PeppaFactory-AccessHub/1", accept: "*/*" }; 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); 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") headers.authorization = `Bearer ${secret}`; return { url, headers }; } export type GrantedRow = { c: typeof connections.$inferSelect; agentId: number | null; operations: string[]; readMode: GrantMode; writeMode: GrantMode }; /** The connection among those granted to this session's project (never by a bare id of someone else). */ export async function findGranted(db: Db, s: SessionCtx, connection: string | number): Promise<{ matches: GrantedRow[] } | { reason: "ambiguous_connection" | "unknown_connection" }> { const granted = await db .select({ c: connections, agentId: connectionGrants.agentId, operations: connectionGrants.operations, readMode: connectionGrants.readMode, writeMode: connectionGrants.writeMode }) .from(connectionGrants) .innerJoin(connections, eq(connections.id, connectionGrants.connectionId)) .where(eq(connectionGrants.projectId, s.projectId)); const want = String(connection).trim(); const byId = /^\d+$/.test(want) ? granted.filter((g) => g.c.id === Number(want)) : []; const byName = granted.filter((g) => g.c.name === want); const matches = byId.length ? byId : byName.length ? byName : granted.filter((g) => connectionSlug(g.c) === want.toLowerCase()); const ids = new Set(matches.map((g) => g.c.id)); if (ids.size > 1) return { reason: "ambiguous_connection" }; if (!ids.size) return { reason: "unknown_connection" }; return { matches }; } /** Calls of this session in the last minute (one budget for every kind of connection). */ export async function recentCalls(db: Db, sessionId: number, now: Date): Promise { const [{ n }] = (await db.select({ n: count() }).from(connectionLog).where(and(eq(connectionLog.sessionId, sessionId), eq(connectionLog.kind, "call"), gt(connectionLog.createdAt, new Date(now.getTime() - 60_000))))) as [{ n: number }]; return n; } export interface ConnectionCall { sessionId: number | null | undefined; /** Connection id or its name (when only one granted connection has it). */ connection: string | number; method: string; path: string; body?: string | null; contentType?: string | null; } export type ConnectionResult = | { ok: true; status: number; contentType: string | null; body: string; truncated: boolean } | { ok: false; reason: ConnectionReason; status?: number }; /** One outbound request, injectable in tests. */ export type ConnectionFetch = (o: { url: URL; method: string; headers: Record; body: Buffer | null; allowInternal?: boolean }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean }>; export class Refused extends Error { reason: ConnectionReason; constructor(reason: ConnectionReason) { super(reason); this.reason = reason; } } /** * Real request: a fresh socket per call (no keep-alive reuse past the address check), no redirects, every address the host resolves to at connect time is checked * (so DNS rebinding can't swap a public name for 127.0.0.1), size and time limits. */ export const defaultConnectionFetch: ConnectionFetch = ({ url, method, headers, body, allowInternal }) => new Promise((resolve, reject) => { const guardedLookup = (host: string, opts: object, cb: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void) => { dnsLookup(host, { ...opts, all: true }, (err, addrs) => { if (err) return cb(err, "", 4); const list = addrs as LookupAddress[]; if (!list.length || (!allowPrivate() && !allowInternal && list.some((a) => isBlockedAddress(a.address)))) return cb(Object.assign(new Error("blocked address"), { code: "PEPPA_BLOCKED" }), "", 4); if ((opts as { all?: boolean }).all) return cb(null, list); cb(null, list[0]!.address, list[0]!.family); }); }; const literal = url.hostname.replace(/^\[|\]$/g, ""); if (isIP(literal) && !allowPrivate() && !allowInternal && isBlockedAddress(literal)) return reject(new Refused("blocked_address")); const req = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, { method, headers, lookup: guardedLookup as never, timeout: CONNECTION_TIMEOUT_MS, agent: false }, (res: IncomingMessage) => { const chunks: Buffer[] = []; let size = 0; let truncated = false; res.on("data", (c: Buffer) => { if (truncated) return; size += c.length; if (size > CONNECTION_RESPONSE_MAX_BYTES) { truncated = true; chunks.push(c.subarray(0, c.length - (size - CONNECTION_RESPONSE_MAX_BYTES))); res.destroy(); return; } chunks.push(c); }); const done = () => resolve({ status: res.statusCode ?? 0, contentType: (res.headers["content-type"] as string | undefined) ?? null, body: Buffer.concat(chunks), truncated, location: !!res.headers.location }); res.on("end", done); res.on("close", done); res.on("error", () => (truncated ? done() : reject(new Refused("upstream_error")))); }); req.on("timeout", () => req.destroy(new Refused("timeout"))); req.on("error", (e: NodeJS.ErrnoException) => reject(e instanceof Refused ? e : new Refused(e.code === "PEPPA_BLOCKED" ? "blocked_address" : "upstream_error"))); if (body) req.write(body); req.end(); }); const CONTENT_TYPE_RE = /^[a-z]+\/[a-z0-9.+-]+(;\s*charset=[a-z0-9-]+)?$/i; /** * 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 { const now = o.now ?? new Date(); const method = String(call.method ?? "").toUpperCase(); const rawPath = String(call.path ?? ""); const logPath = (rawPath.split("?")[0] ?? "").slice(0, 300) || "/"; const s = await sessionCtx(db, call.sessionId); let conn: typeof connections.$inferSelect | null = null; // PEP-254: every row goes into the owner's hash chain; an allowed call is written BEFORE the request. const record = async (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null, extra: { kind?: "call" | "result"; parentId?: number; durationMs?: number } = {}): Promise => { if (!conn) return null; // nothing to attribute: an unknown connection is not someone's journal return appendJournal(db, { ownerId: conn.ownerId, kind: extra.kind ?? "call", parentId: extra.parentId ?? null, connectionId: conn.id, connectionName: conn.name, projectId: s?.projectId ?? null, sessionId: s?.id ?? null, agentId: s?.agentId ?? null, agentName: s?.agentName ?? null, method: method.slice(0, 10) || "?", path: logPath, decision, reason, statusCode, durationMs: extra.durationMs ?? null, createdAt: extra.kind === "result" ? new Date(now.getTime() + (extra.durationMs ?? 0)) : now, }); }; const deny = async (reason: ConnectionReason): Promise => { await record("denied", reason, null); return { ok: false, reason }; }; if (!s) return { ok: false, reason: "no_session" }; const found = await findGranted(db, s, call.connection); if ("reason" in found) return { ok: false, reason: found.reason }; const matches = found.matches; conn = matches[0]!.c; if (!agentIsolated(s, o.env)) return deny("not_isolated"); if (conn.status !== "active" || !conn.secretEnc) return deny("revoked"); if (conn.protocol !== "http") return deny("wrong_protocol"); const mine = matches.filter((g) => g.agentId == null || g.agentId === s.agentId); if (!mine.length) return deny("no_grant"); if (!CONNECTION_METHODS.includes(method as ConnectionMethod)) return deny("bad_request"); const clean = cleanPath(rawPath); if (!clean) return deny("bad_path"); const refusal = grantDecision(conn.catalogId, mine, method, clean.path); if (refusal) 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"); let secret: string; try { secret = openConnectionSecret(conn)!; } catch { await record("failed", "upstream_error", null); return { ok: false, reason: "upstream_error" }; } // Target = base (+ key in the path) + path; the host and the base path must survive URL parsing unchanged. const built = buildRequest(conn, secret, clean, contentType, body); if (!built) return deny("bad_path"); const { url, headers } = built; // Written before the service is called: a crash in the middle leaves «started, no result». const callId = (await record("allowed", null, null))!; const started = Date.now(); const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, statusCode: number | null) => record(decision, reason, statusCode, { kind: "result", parentId: callId, durationMs: Date.now() - started }); try { const res = await (o.fetch ?? defaultConnectionFetch)({ url, method, headers, body }); if (res.status >= 300 && res.status < 400 && res.location) { await result("failed", "redirect", res.status); return { ok: false, reason: "redirect", status: res.status }; } await result("allowed", res.truncated ? "too_large" : null, res.status); await db.update(connections).set({ lastUsedAt: now }).where(eq(connections.id, conn.id)); // The answer goes to the agent only: nothing of it is stored or sent anywhere (PEP-254). // PEP-258: every recognisable form of the key (base64, URL, hex, JSON, wrapped, cut at the limit). const forms = connectionKeyForms(secret, conn.authKind); const text = maskConnectionKey(res.body.toString("utf8"), forms, { truncated: res.truncated }); const contentType = res.contentType == null ? null : maskConnectionKey(res.contentType, forms); return { ok: true, status: res.status, contentType, body: text, truncated: res.truncated }; } catch (e) { const reason = e instanceof Refused ? e.reason : "upstream_error"; await result(reason === "blocked_address" ? "denied" : "failed", reason, null); return { ok: false, reason }; } } // ---------- PEP-249: checking a connection ---------- export const CONNECTION_CHECK_EVERY_MS = 24 * 3600_000; const CHECK_BATCH = 10; export interface ConnectionCheckResult { status: ConnectionCheckStatus; /** Own service without a check call: it answered, the key will show itself on the first request. */ reachableOnly?: boolean; httpStatus?: number; checkedAt: Date; } /** What a check answer means (pure — tested per catalog card). */ export function judgeCheck(check: CatalogCheck | null, res: { status: number; body: string } | null): { status: ConnectionCheckStatus; reachableOnly?: boolean } { if (!res) return { status: "down" }; if (!check) { if (res.status === 401 || res.status === 403) return { status: "bad_key" }; return res.status > 0 && res.status < 500 ? { status: "ok", reachableOnly: true } : { status: "down" }; } const badKey = check.badKey ?? [401, 403]; if (badKey.includes(res.status)) return { status: "bad_key" }; const ok = check.ok ? check.ok.includes(res.status) : res.status >= 200 && res.status < 300; if (ok) return check.bodyIncludes && !res.body.replace(/\s+/g, "").includes(check.bodyIncludes) ? { status: "bad_key" } : { status: "ok" }; return { status: "down" }; } export interface ConnectionCheckOptions { fetch?: ConnectionFetch; now?: Date; /** PEP-251: database / SSH / mail drivers (tests: mocks). */ drivers?: import("./connection-drivers.ts").GatewayDrivers; } async function runCheck(db: Db, conn: typeof connections.$inferSelect, o: ConnectionCheckOptions): Promise { if (conn.protocol !== "http") return (await import("./connection-gateway.ts")).protocolCheck(db, conn, o); const now = o.now ?? new Date(); const check = catalogService(conn.catalogId)?.check ?? null; const method = check?.method ?? "GET"; const raw = check?.path ?? "/"; const clean = cleanPath(raw) ?? { path: "/", query: "" }; let res: { status: number; body: string } | null = null; // PEP-254: the check is journaled like a gateway call — the call first, its result after. const entry = { ownerId: conn.ownerId, connectionId: conn.id, connectionName: conn.name, method, path: clean.path.slice(0, 300), createdAt: now }; const callId = appendJournal(db, { ...entry, kind: "call", decision: "allowed", reason: "owner_check", statusCode: null }); const started = Date.now(); try { const secret = openConnectionSecret(conn)!; const built = buildRequest(conn, secret, clean, null, null); if (built) { // Own service: the check is the base address itself (no trailing «/» added). if (!check) built.url.pathname = built.url.pathname.replace(/\/$/, "") || "/"; const r = await (o.fetch ?? defaultConnectionFetch)({ url: built.url, method, headers: built.headers, body: null }); res = r.status >= 300 && r.status < 400 && r.location ? null : { status: r.status, body: r.body.toString("utf8") }; } } catch { res = null; } const verdict = judgeCheck(check, res); const durationMs = Date.now() - started; appendJournal(db, { ...entry, kind: "result", parentId: callId, decision: verdict.status === "ok" ? "allowed" : "failed", reason: "owner_check", statusCode: res?.status ?? null, durationMs, createdAt: new Date(now.getTime() + durationMs) }); const patch: Partial = { checkStatus: verdict.status, checkedAt: now }; if (verdict.status === "ok") patch.checkAlertedAt = null; await db.update(connections).set(patch).where(eq(connections.id, conn.id)); return { ...verdict, httpStatus: res?.status, checkedAt: now }; } /** «Проверить»: the catalog's check call through the same address guards, owner only. */ export async function checkConnection(db: Db, userId: number, connectionId: number, o: ConnectionCheckOptions = {}): Promise { const c = await ownConnection(db, userId, connectionId); if (c.status !== "active" || !c.secretEnc) throw new PeppaError(tr("Подключение отозвано: сначала задайте новый ключ доступа")); return runCheck(db, c, o); } /** * Daily check (watchdog): active connections with a key not checked for a day. A key that * stopped working sends its owner ONE message (`check_alerted_at`); a working check or a new key * clears the mark. */ export async function connectionCheckTick(db: Db, o: ConnectionCheckOptions & { notify?: (db: Db, conn: { id: number; ownerId: number; name: string }) => Promise } = {}): Promise { if (process.env.PEPPA_CONNECTION_CHECK === "off") return 0; const now = o.now ?? new Date(); const due = (await db.select().from(connections).where(eq(connections.status, "active")).orderBy(asc(connections.checkedAt))) .filter((c) => c.secretEnc && (!c.checkedAt || now.getTime() - c.checkedAt.getTime() >= CONNECTION_CHECK_EVERY_MS)) .slice(0, CHECK_BATCH); for (const c of due) { const r = await runCheck(db, c, { fetch: o.fetch, drivers: o.drivers, now }); if (r.status === "bad_key" && c.checkStatus === "ok" && !c.checkAlertedAt) { await db.update(connections).set({ checkAlertedAt: now }).where(eq(connections.id, c.id)); await (o.notify ?? tellKeyStopped)(db, { id: c.id, ownerId: c.ownerId, name: c.name }); } } return due.length; } /** One message to the owner: the key of a connection stopped working. */ export async function tellKeyStopped(db: Db, c: { id: number; ownerId: number; name: string }): Promise { const text = tr("Ключ доступа подключения «{name}» перестал работать: агенты не смогут им пользоваться. Замените ключ в разделе «Подключения».", { name: asIs(c.name) }); const key = `connection-key:${c.id}`; await addMasterMessage(db, c.ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}:${Date.now()}`, url: `/connections#c${c.id}` }).catch(() => null); const [u] = await db.select().from(users).where(eq(users.id, c.ownerId)); if (!u) return; await deliverToUser(db, u, { event: "failures", dedupeKey: `${key}:${Date.now()}:${u.telegramChatId}`, pushKey: `${key}:${Date.now()}:u${u.id}`, telegram: { params: { text } }, push: { title: tr("FORGE"), body: text, url: "/connections", tag: key }, }).catch(() => null); }