// PEP-251 Access Hub gateway for databases, SSH/SFTP, S3 and mail. Same rules as the HTTP // gateway (connections.ts `callConnection`): the agent's session in a container, a grant of the // owner for the project and the agent, the owner's read / write mode for the operation, a rate // limit, the secret opened only here, every address checked right before connecting, one journal // row before the work and one after it (the operation, never the SQL text, the command, a file // or a letter). The agent gets the answer as data; the secret is masked in it. import { asIs, m as tr } from "@peppa/shared/i18n"; import { connectionGrants, connections, users, type Db } from "@peppa/db"; import { eq } from "drizzle-orm"; import { lookup } from "node:dns/promises"; 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 { ANSWER_MAX_BYTES, FILE_MAX_BYTES, formatRows, isBlockedAddress, isGatewayProtocol, isReadQuery, MAIL_BODY_MAX_BYTES, MAIL_LIST_MAX, mailFlags, mailFolder, mailRecipients, parseS3List, PROTOCOL_OPERATIONS, protocolHosts, s3Key, sftpPath, signS3, singleStatement, SQL_MAX_LENGTH, SQL_MAX_ROWS, SQL_TIMEOUT_MS, SSH_COMMAND_MAX, SSH_TIMEOUT_MS, type GatewayProtocol, type MailConfig, type S3Config, type SqlConfig, type SshConfig, } from "./connection-protocols.ts"; import { agentIsolated, allowPrivate, CONNECTION_RATE_PER_MIN, defaultConnectionFetch, findGranted, internalHosts, openConnectionSecret, recentCalls, Refused, sessionCtx, widest, type ConnectionCheckOptions, type ConnectionCheckResult, type ConnectionFetch, type ConnectionReason, type GrantMode, } from "./connections.ts"; import { deliverToUser } from "./notifications.ts"; import { connectionKeyForms, maskConnectionKey } from "./connection-mask.ts"; import { getSetting, setSetting } from "./settings.ts"; /** Resolves a host name to addresses (tests: a fixed map). */ export type GatewayResolve = (host: string) => Promise; const defaultResolve: GatewayResolve = async (host) => (await lookup(host, { all: true })).map((a) => a.address); export interface UseConnectionCall { sessionId: number | null | undefined; connection: string | number; operation: string; args?: Record; } 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 }; export interface GatewayOptions { drivers?: GatewayDrivers; fetch?: ConnectionFetch; resolve?: GatewayResolve; now?: Date; env?: NodeJS.ProcessEnv; } type Conn = typeof connections.$inferSelect; let defaults: GatewayOptions = {}; /** Tests and the dev stand: mock drivers / resolver / fetch for calls that pass none (MCP). */ export function setGatewayDefaults(o: GatewayOptions): void { defaults = o; } /** * The checked address to connect to: every address the name resolves to must be public, unless * the host is on the superadmin's list of FORGE's own servers. */ export async function resolveAddress(host: string, o: { internal: boolean; resolve?: GatewayResolve }): Promise { const list = isIP(host) ? [host] : await (o.resolve ?? defaultResolve)(host).catch(() => [] as string[]); if (!list.length) throw new DriverError("down"); if (!o.internal && list.some(isBlockedAddress)) throw new Refused("blocked_address"); return list[0]!; } const str = (v: unknown, max: number): string | null => (typeof v === "string" && v.length <= max ? v : typeof v === "number" ? String(v) : null); /** The agent's arguments → a driver request (or a refusal); also the path for the journal. */ type Prepared = | { kind: "sql"; text: string; readOnly: boolean; page: number; logPath: string } | { kind: "ssh"; req: SshRequest; logPath: string; relative?: (abs: string) => string } | { kind: "s3"; method: "GET" | "PUT" | "DELETE"; key: string | null; query?: Record; body?: Buffer; contentType?: string; list?: boolean; logPath: string } | { kind: "mail"; req: MailRequest; logPath: string }; function decodeContent(args: Record): Buffer | null { const content = typeof args.content === "string" ? args.content : null; if (content == null) return null; const b = args.base64 === true || args.base64 === "true" ? Buffer.from(content, "base64") : Buffer.from(content, "utf8"); return b.length > FILE_MAX_BYTES ? null : b; } function prepare(protocol: GatewayProtocol, cfg: Record, op: string, args: Record): Prepared | ConnectionReason { if (protocol === "postgres" || protocol === "mysql") { const text = str(args.sql, SQL_MAX_LENGTH)?.trim(); if (!text || !singleStatement(text)) return "bad_request"; if (op === "query" && !isReadQuery(text)) return "not_read_query"; const page = Number(args.page ?? 1); return { kind: "sql", text: text.replace(/;\s*$/, ""), readOnly: op === "query", page: Number.isFinite(page) ? page : 1, logPath: "/" }; } if (protocol === "ssh") { const c = cfg as unknown as SshConfig; const rel = (abs: string) => abs.slice(c.root === "/" ? 0 : c.root.length) || "/"; if (op === "exec") { const command = str(args.command, SSH_COMMAND_MAX)?.trim(); if (!command || command.includes("\u0000")) return "bad_request"; return { kind: "ssh", req: { op: "exec", command, timeoutMs: SSH_TIMEOUT_MS, maxBytes: ANSWER_MAX_BYTES }, logPath: "/" }; } const path = sftpPath(c.root, op === "sftp_list" ? (args.path ?? "") : args.path); if (!path || (op !== "sftp_list" && path === c.root)) return "outside_root"; if (op === "sftp_list") return { kind: "ssh", req: { op: "list", path }, logPath: rel(path) }; if (op === "sftp_read") return { kind: "ssh", req: { op: "read", path, maxBytes: FILE_MAX_BYTES }, logPath: rel(path) }; const data = decodeContent(args); if (!data) return "bad_request"; return { kind: "ssh", req: { op: "write", path, data }, logPath: rel(path) }; } if (protocol === "s3") { const c = cfg as unknown as S3Config; if (op === "list") { const prefix = s3Key(c, args.prefix, { allowEmpty: true }); if (prefix == null) return "bad_path"; return { kind: "s3", method: "GET", key: null, query: { "list-type": "2", prefix, "max-keys": "1000" }, list: true, logPath: `/${prefix.slice(c.prefix.length)}` }; } const key = s3Key(c, args.key); if (!key) return "bad_path"; const logPath = `/${key.slice(c.prefix.length)}`; if (op === "get") return { kind: "s3", method: "GET", key, logPath }; if (op === "delete") return { kind: "s3", method: "DELETE", key, logPath }; const body = decodeContent(args); const contentType = typeof args.content_type === "string" && /^[a-z]+\/[a-z0-9.+-]+(;\s*charset=[a-z0-9-]+)?$/i.test(args.content_type) ? args.content_type : "application/octet-stream"; if (!body) return "bad_request"; return { kind: "s3", method: "PUT", key, body, contentType, logPath }; } const c = cfg as unknown as MailConfig; const folder = mailFolder(args.folder); if (!folder) return "bad_request"; if (op === "read") { if (args.uid != null && args.uid !== "") { const uid = Number(args.uid); if (!Number.isInteger(uid) || uid < 1) return "bad_request"; return { kind: "mail", req: { op: "get", folder, uid, maxBytes: MAIL_BODY_MAX_BYTES }, logPath: `/${folder}/${uid}` }; } const limit = Math.min(Math.max(1, Number(args.limit ?? 20) || 20), MAIL_LIST_MAX); return { kind: "mail", req: { op: "list", folder, limit }, logPath: `/${folder}` }; } if (op === "change") { const uid = Number(args.uid); const add = mailFlags(args.add_flags); const remove = mailFlags(args.remove_flags); const moveTo = args.move_to == null || args.move_to === "" ? null : mailFolder(args.move_to); if (!Number.isInteger(uid) || uid < 1 || !add || !remove || moveTo === null && args.move_to != null && args.move_to !== "") return "bad_request"; if (!add.length && !remove.length && !moveTo) return "bad_request"; return { kind: "mail", req: { op: "change", folder, uid, add, remove, moveTo }, logPath: `/${folder}/${uid}` }; } const to = mailRecipients(args.to); const subject = str(args.subject, 300); const text = str(args.text, MAIL_BODY_MAX_BYTES); if (!to || subject == null || /[\r\n]/.test(subject) || text == null) return "bad_request"; return { kind: "mail", req: { op: "send", from: c.from, to, subject, text }, logPath: "/" }; } const DRIVER_REASON: Record = { auth: "auth_failed", down: "upstream_error", timeout: "timeout", host_key_changed: "host_key_changed", query: "query_error", not_found: "not_found", outside_root: "outside_root", too_large: "too_large", }; /** Runs a prepared request against the service; returns the agent's text. */ async function perform(db: Db, conn: Conn, secret: string, p: Prepared, o: GatewayOptions & { internal: string[] }): Promise<{ text: string; truncated: boolean }> { const drivers = o.drivers ?? defaultDrivers; const protocol = conn.protocol as GatewayProtocol; const cfg = (conn.config ?? {}) as Record; const internalOk = (h: string) => allowPrivate(o.env) || o.internal.includes(h); const addr = (h: string) => resolveAddress(h, { internal: internalOk(h), resolve: o.resolve }); if (p.kind === "sql") { const c = cfg as unknown as SqlConfig; const a = await drivers.sql({ protocol: protocol as "postgres" | "mysql", host: c.host, address: await addr(c.host), port: c.port, user: c.user, database: c.database, tls: c.tls, password: secret }, { text: p.text, readOnly: p.readOnly, timeoutMs: SQL_TIMEOUT_MS, maxRows: SQL_MAX_ROWS }); const f = formatRows(a, p.page); return { text: f.text, truncated: f.truncated }; } if (p.kind === "ssh") { const c = cfg as unknown as SshConfig; const a = await drivers.ssh({ host: c.host, address: await addr(c.host), port: c.port, user: c.user, secret, hostKey: c.hostKey ?? null, root: c.root }, p.req); await pinHostKey(db, conn, a.hostKey); if (p.req.op === "exec") return { text: `exit code: ${a.exitCode ?? "none"}${a.truncated ? " · output cut at 64 KB" : ""}\n${a.text ?? ""}`, truncated: !!a.truncated }; if (p.req.op === "list") return { text: (a.entries ?? []).map((e) => `${e.type}\t${e.size}\t${e.name}`).join("\n") || "(empty)", truncated: !!a.truncated }; if (p.req.op === "read") return { text: fileText(a.data ?? Buffer.alloc(0)), truncated: false }; return { text: a.text ?? "written", truncated: false }; } if (p.kind === "s3") { const c = cfg as unknown as S3Config; const host = new URL(c.endpoint).hostname; await addr(host); // refuse early; the request itself re-checks every address it connects to const req = signS3(c, secret, { method: p.method, key: p.key, query: p.query, body: p.body ?? null, contentType: p.contentType }, o.now); let res; try { res = await (o.fetch ?? defaultConnectionFetch)({ ...req, allowInternal: internalOk(host) }); } catch (e) { if (e instanceof Refused) throw e; throw new DriverError("down"); } if (res.status === 401 || res.status === 403) throw new DriverError("auth"); if (res.status === 404) throw new DriverError("not_found"); if (res.status >= 300) throw new DriverError(res.status >= 500 ? "down" : "query", `storage answered ${res.status}`); if (p.list) { const l = parseS3List(res.body.toString("utf8")); return { text: l.keys.map((k) => `${k.size}\t${k.modified}\t${k.key.slice(c.prefix.length)}`).join("\n") || "(empty)", truncated: l.truncated }; } if (p.method === "GET") return { text: fileText(res.body), truncated: res.truncated }; return { text: p.method === "PUT" ? `written ${p.body?.length ?? 0} bytes` : "deleted", truncated: false }; } const c = cfg as unknown as MailConfig; const target = { imap: { host: c.imapHost, address: p.req.op === "send" ? "" : await addr(c.imapHost), port: c.imapPort }, smtp: { host: c.smtpHost, address: p.req.op === "send" ? await addr(c.smtpHost) : "", port: c.smtpPort }, user: c.user, password: secret, }; const a = await drivers.mail(target, p.req); if (a.letters) return { text: a.letters.map((l) => `${l.uid}\t${l.date ?? ""}\t${l.flags.join(" ")}\t${l.from}\t${l.subject}`).join("\n") || "(no letters)", truncated: false }; return { text: a.text ?? a.done ?? "done", truncated: !!a.truncated }; } /** A file to the agent: text as is, anything else as base64. */ function fileText(b: Buffer): string { const text = b.toString("utf8"); const binary = b.includes(0) || text.includes("�"); return binary ? `base64:${b.toString("base64")}` : text; } /** The first contact pins the server's key (trust on first use, like ssh's known_hosts). */ async function pinHostKey(db: Db, conn: Conn, seen: string): Promise { const cfg = (conn.config ?? {}) as Record; if (cfg.hostKey || !seen) return; await db.update(connections).set({ config: { ...cfg, hostKey: seen } }).where(eq(connections.id, conn.id)); conn.config = { ...cfg, hostKey: seen }; } /** One message per new key: the server's key changed, calls are refused until the owner decides. */ export async function tellHostKeyChanged(db: Db, conn: Pick, seen: string): Promise { const key = `connection.hostkey.alert:${conn.id}`; if ((await getSetting(db, key)) === seen) return false; await setSetting(db, key, seen); const text = tr("Ключ сервера подключения «{name}» изменился. Агенты не смогут им пользоваться, пока вы не проверите сервер. Если сервер переустанавливали — нажмите «Принять новый ключ сервера» в разделе «Подключения».", { name: asIs(conn.name) }); await addMasterMessage(db, conn.ownerId, { kind: "event", important: true, text, dedupeKey: `master:${key}:${seen}`, url: `/connections#c${conn.id}` }).catch(() => null); const [u] = await db.select().from(users).where(eq(users.id, conn.ownerId)); if (u) { await deliverToUser(db, u, { event: "failures", dedupeKey: `${key}:${seen}:${u.telegramChatId}`, pushKey: `${key}:${seen}:u${u.id}`, telegram: { params: { text } }, push: { title: tr("FORGE"), body: text, url: "/connections", tag: key }, }).catch(() => null); } for (const g of await db.select({ projectId: connectionGrants.projectId }).from(connectionGrants).where(eq(connectionGrants.connectionId, conn.id))) { const { logEvent } = await import("./audit.ts"); await logEvent(db, { projectId: g.projectId, type: "connection_host_key_changed", payload: { connectionId: conn.id } }); } return true; } /** * 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 { const o = { ...defaults, ...opts }; const now = o.now ?? new Date(); const operation = String(call.operation ?? "").trim().toLowerCase(); const args = call.args && typeof call.args === "object" ? call.args : {}; const s = await sessionCtx(db, call.sessionId); 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 conn = found.matches[0]!.c; let logPath = "/"; const record = (decision: ConnectionJournalDecision, reason: ConnectionReason | null, extra: { kind?: "call" | "result"; parentId?: number; durationMs?: number } = {}) => appendJournal(db, { ownerId: conn.ownerId, kind: extra.kind ?? "call", parentId: extra.parentId ?? null, connectionId: conn.id, connectionName: conn.name, projectId: s.projectId, sessionId: s.id, agentId: s.agentId, agentName: s.agentName, method: operation.toUpperCase().slice(0, 10) || "?", path: logPath.slice(0, 300), decision, reason, statusCode: null, 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); return { ok: false, reason }; }; if (!agentIsolated(s, o.env)) return deny("not_isolated"); if (conn.status !== "active" || !conn.secretEnc) return deny("revoked"); const protocol = conn.protocol; if (!isGatewayProtocol(protocol)) return deny("wrong_protocol"); const mine = found.matches.filter((g) => g.agentId == null || g.agentId === s.agentId); if (!mine.length) return deny("no_grant"); const op = PROTOCOL_OPERATIONS[protocol][operation]; if (!op) return deny("bad_request"); const mode = mine.reduce((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"); const prepared = prepare(protocol, (conn.config ?? {}) as Record, 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"); let secret: string; try { secret = openConnectionSecret(conn)!; } catch { await record("failed", "upstream_error"); return { ok: false, reason: "upstream_error" }; } const callId = record("allowed", null); const started = Date.now(); const result = (decision: ConnectionJournalDecision, reason: ConnectionReason | null) => record(decision, reason, { kind: "result", parentId: callId, durationMs: Date.now() - started }); // PEP-258: every recognisable form of the secret (base64, URL, hex, JSON, each line of an SSH key). const forms = connectionKeyForms(secret); const mask = (t: string, truncated = false) => maskConnectionKey(t, forms, { truncated }); try { const out = await perform(db, conn, secret, prepared, { ...o, internal: await internalHosts(db) }); result("allowed", out.truncated ? "too_large" : null); await db.update(connections).set({ lastUsedAt: now }).where(eq(connections.id, conn.id)); return { ok: true, text: mask(out.text, out.truncated), truncated: out.truncated }; } catch (e) { if (e instanceof Refused) { result("denied", e.reason); return { ok: false, reason: e.reason }; } const err = e instanceof DriverError ? e : new DriverError("down"); const reason = DRIVER_REASON[err.code]; result(reason === "host_key_changed" ? "denied" : "failed", reason); if (err.code === "host_key_changed" && err.seenHostKey) await tellHostKeyChanged(db, conn, err.seenHostKey); return reason === "query_error" ? { ok: false, reason, message: mask(err.message).slice(0, 2000) } : { ok: false, reason }; } } /** «Проверить» and the daily check for a non-HTTP connection: one harmless read. */ export async function protocolCheck(db: Db, conn: Conn, opts: ConnectionCheckOptions & { resolve?: GatewayResolve; env?: NodeJS.ProcessEnv } = {}): Promise { const o = { ...defaults, ...opts }; const now = o.now ?? new Date(); const protocol = conn.protocol as GatewayProtocol; const probe: Record]> = { postgres: ["query", { sql: "SELECT 1" }], mysql: ["query", { sql: "SELECT 1" }], ssh: ["sftp_list", { path: "" }], s3: ["list", {}], mail: ["read", { limit: 1 }], }; const [op, args] = probe[protocol]; const p = prepare(protocol, (conn.config ?? {}) as Record, op, args); const entry = { ownerId: conn.ownerId, connectionId: conn.id, connectionName: conn.name, method: op.toUpperCase().slice(0, 10), path: "/", createdAt: now }; const callId = appendJournal(db, { ...entry, kind: "call", decision: "allowed", reason: "owner_check", statusCode: null }); const started = Date.now(); let status: ConnectionCheckResult["status"] = "down"; try { if (typeof p === "string") throw new DriverError("down"); const secret = openConnectionSecret(conn)!; await perform(db, conn, secret, p, { drivers: o.drivers, fetch: o.fetch, resolve: o.resolve, now, env: o.env, internal: await internalHosts(db) }); status = "ok"; } catch (e) { if (e instanceof DriverError && e.code === "auth") status = "bad_key"; else if (e instanceof DriverError && e.code === "host_key_changed") { status = "host_key"; if (e.seenHostKey) await tellHostKeyChanged(db, conn, e.seenHostKey); } else if (e instanceof DriverError && e.code === "not_found" && protocol === "s3") status = "down"; } const durationMs = Date.now() - started; appendJournal(db, { ...entry, kind: "result", parentId: callId, decision: status === "ok" ? "allowed" : "failed", reason: "owner_check", statusCode: null, durationMs, createdAt: new Date(now.getTime() + durationMs) }); const patch: Partial = { checkStatus: status, checkedAt: now }; if (status === "ok") patch.checkAlertedAt = null; await db.update(connections).set(patch).where(eq(connections.id, conn.id)); return { status, checkedAt: now }; }