// PEP-251 Access Hub beyond HTTP: databases (PostgreSQL, MySQL/MariaDB), SSH/SFTP, S3 and mail // (IMAP + SMTP). This module is pure — settings of a connection, the operations agents may ask // for (each one is «read» or «write» for the owner's modes, PEP-249), checks of addresses, SQL // and paths, the S3 signature and the answer format. Network work lives in connection-drivers.ts, // the gateway itself in connection-gateway.ts. See the change pep-251-access-hub-protocols. import { createHash, createHmac } from "node:crypto"; import { isIP } from "node:net"; import { posix } from "node:path"; import { m as tr } from "@peppa/shared/i18n"; export type ConnectionProtocol = "http" | "postgres" | "mysql" | "ssh" | "s3" | "mail"; export type GatewayProtocol = Exclude; export const GATEWAY_PROTOCOLS: GatewayProtocol[] = ["postgres", "mysql", "ssh", "s3", "mail"]; export const isGatewayProtocol = (p: unknown): p is GatewayProtocol => GATEWAY_PROTOCOLS.includes(p as GatewayProtocol); /** Rows a database answer keeps at most; the agent reads them page by page. */ export const SQL_MAX_ROWS = 1000; export const SQL_PAGE_ROWS = 100; export const SQL_TIMEOUT_MS = 10_000; export const SQL_MAX_LENGTH = 32 * 1024; export const CELL_MAX_CHARS = 1000; /** One answer to an agent (a page of rows, a file, command output). */ export const ANSWER_MAX_BYTES = 64 * 1024; export const SSH_TIMEOUT_MS = 30_000; export const SSH_COMMAND_MAX = 4096; /** A file read or written over SFTP / S3. */ export const FILE_MAX_BYTES = 256 * 1024; export const MAIL_LIST_MAX = 50; export const MAIL_BODY_MAX_BYTES = 64 * 1024; export const MAIL_RECIPIENTS_MAX = 10; export const PROTOCOL_SECRET_MAX_BYTES = 16 * 1024; // ---------- operations ---------- export interface ProtocolOperation { /** Read — looks at data only; write — changes, deletes or sends. Decides the owner's mode. */ kind: "read" | "write"; /** Argument names (for agents' help). */ args: string[]; /** For agents, English. */ help: string; } export const PROTOCOL_OPERATIONS: Record> = { postgres: { query: { kind: "read", args: ["sql", "page?"], help: "one read-only SQL statement (SELECT/WITH/SHOW/EXPLAIN), runs in a READ ONLY transaction, ≤ 1000 rows, 100 rows per page" }, execute: { kind: "write", args: ["sql"], help: "one SQL statement that changes data (INSERT/UPDATE/DELETE/DDL)" }, }, mysql: { query: { kind: "read", args: ["sql", "page?"], help: "one read-only SQL statement (SELECT/WITH/SHOW/EXPLAIN/DESCRIBE), runs in a READ ONLY transaction, ≤ 1000 rows, 100 rows per page" }, execute: { kind: "write", args: ["sql"], help: "one SQL statement that changes data (INSERT/UPDATE/DELETE/DDL)" }, }, ssh: { exec: { kind: "write", args: ["command"], help: "run one shell command on the server (30 s, output ≤ 64 KB); any command may change things, so it counts as writing" }, sftp_read: { kind: "read", args: ["path"], help: "read a file (≤ 256 KB) inside the allowed directory; path is relative to it" }, sftp_list: { kind: "read", args: ["path?"], help: "list a directory inside the allowed directory" }, sftp_write: { kind: "write", args: ["path", "content", "base64?"], help: "write a file (≤ 256 KB) inside the allowed directory" }, }, s3: { list: { kind: "read", args: ["prefix?"], help: "list objects under the allowed prefix (≤ 1000)" }, get: { kind: "read", args: ["key"], help: "read an object (≤ 256 KB); key is relative to the allowed prefix" }, put: { kind: "write", args: ["key", "content", "content_type?", "base64?"], help: "write an object (≤ 256 KB)" }, delete: { kind: "write", args: ["key"], help: "delete an object" }, }, mail: { read: { kind: "read", args: ["folder?", "uid?", "limit?"], help: "without uid: the latest letters of a folder (default INBOX, ≤ 50: uid, date, from, subject, flags); with uid: one letter's text (≤ 64 KB)" }, change: { kind: "write", args: ["uid", "folder?", "add_flags?", "remove_flags?", "move_to?"], help: "mark a letter (flags like \\Seen, \\Flagged) or move it to another folder" }, send: { kind: "write", args: ["to", "subject", "text"], help: "send a plain-text letter from the mailbox (≤ 10 recipients)" }, }, }; export function operationKind(protocol: GatewayProtocol, op: string): "read" | "write" | null { return PROTOCOL_OPERATIONS[protocol][op]?.kind ?? null; } // ---------- settings of a connection (never the secret) ---------- export interface SqlConfig { host: string; port: number; database: string; user: string; /** verify — encrypted with a checked certificate (default); encrypt — without the check; off. */ tls: "verify" | "encrypt" | "off"; } export interface SshConfig { host: string; port: number; user: string; /** SFTP paths stay inside it. */ root: string; /** «SHA256:…» — pinned server key; empty until the first contact. */ hostKey?: string | null; } export interface S3Config { endpoint: string; region: string; bucket: string; prefix: string; accessKeyId: string; } export interface MailConfig { imapHost: string; imapPort: number; smtpHost: string; smtpPort: number; user: string; from: string; } export type ProtocolConfig = SqlConfig | SshConfig | S3Config | MailConfig; export class ProtocolConfigError extends Error {} const HOST_RE = /^(?=.{1,253}$)([A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/; const USER_RE = /^[A-Za-z0-9._@+-]{1,128}$/; const DB_RE = /^[A-Za-z0-9_$.-]{1,128}$/; const BUCKET_RE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/; const REGION_RE = /^[a-z0-9-]{2,32}$/; const ACCESS_KEY_RE = /^[A-Za-z0-9._-]{4,128}$/; const FP_RE = /^SHA256:[A-Za-z0-9+/]{43}=?$/; const EMAIL_RE = /^[^\s@<>",;]{1,64}@[A-Za-z0-9.-]{1,253}$/; /** Loopback, private, link-local, CGNAT, ULA, multicast, unspecified, metadata: not reachable. */ export function isBlockedAddress(ip: string): boolean { const v = isIP(ip); if (v === 4) { const [a, b] = ip.split(".").map(Number) as [number, number]; return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224; } if (v === 6) { const s = ip.toLowerCase(); const mapped = s.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/); if (mapped) return isBlockedAddress(mapped[1]!); if (/^::ffff:/.test(s)) return true; // hex-mapped forms: refuse rather than decode return s === "::" || s === "::1" || /^f[cd]/.test(s) || /^fe[89ab]/.test(s) || /^ff/.test(s) || /^64:ff9b:/.test(s) || /^2001:db8:/.test(s); } return false; // a host name: checked after resolving } const LOCAL_NAME_RE = /^(localhost|.*\.localhost|.*\.local|.*\.internal|.*\.lan|.*\.home\.arpa)$/i; /** * A host of a connection: a public name or address. A private one only when it is on the * superadmin's list of the platform's own servers (`internal`) or in tests. */ export function checkHost(raw: unknown, o: { internal?: string[]; allowPrivate?: boolean } = {}): string { const host = String(raw ?? "").trim().toLowerCase().replace(/^\[|\]$/g, ""); if (!host || !(HOST_RE.test(host) || isIP(host))) throw new ProtocolConfigError(tr("Укажите адрес сервера, например db.example.com")); const allowed = o.allowPrivate || (o.internal ?? []).includes(host); if (!allowed && (isBlockedAddress(host) || LOCAL_NAME_RE.test(host) || !host.includes(".") && !isIP(host))) throw new ProtocolConfigError(tr("Этот адрес сервиса недоступен: укажите адрес в интернете")); return host; } function port(raw: unknown, def: number): number { if (raw == null || raw === "") return def; const n = Number(raw); if (!Number.isInteger(n) || n < 1 || n > 65535) throw new ProtocolConfigError(tr("Порт — число от 1 до 65535")); return n; } function field(raw: unknown, re: RegExp, message: string): string { const v = String(raw ?? "").trim(); if (!re.test(v)) throw new ProtocolConfigError(message); return v; } /** The SFTP directory agents stay in: absolute, normalized, no «..». */ export function checkRoot(raw: unknown, user: string): string { const v = String(raw ?? "").trim() || `/home/${user}`; if (!v.startsWith("/") || v.length > 512 || /[\u0000-\u001f\u007f]/.test(v) || v.split("/").includes("..")) throw new ProtocolConfigError(tr("Папка на сервере — полный путь, например /var/www")); return posix.normalize(v).replace(/(.)\/+$/, "$1"); } /** Owner's form → stored settings (validated). Throws ProtocolConfigError with words for people. */ export function normalizeProtocolConfig(protocol: GatewayProtocol, raw: Record, o: { internal?: string[]; allowPrivate?: boolean } = {}): ProtocolConfig { if (protocol === "postgres" || protocol === "mysql") { const user = field(raw.user, USER_RE, tr("Укажите пользователя базы данных")); return { host: checkHost(raw.host, o), port: port(raw.port, protocol === "postgres" ? 5432 : 3306), database: field(raw.database, DB_RE, tr("Укажите название базы данных")), user, tls: raw.tls === "off" || raw.tls === "encrypt" ? raw.tls : "verify", } satisfies SqlConfig; } if (protocol === "ssh") { const user = field(raw.user, USER_RE, tr("Укажите пользователя на сервере")); const hostKey = String(raw.hostKey ?? "").trim(); if (hostKey && !FP_RE.test(hostKey)) throw new ProtocolConfigError(tr("Отпечаток ключа сервера выглядит как SHA256:… — или оставьте поле пустым")); return { host: checkHost(raw.host, o), port: port(raw.port, 22), user, root: checkRoot(raw.root, user), hostKey: hostKey || null } satisfies SshConfig; } if (protocol === "s3") { let endpoint: URL; try { endpoint = new URL(String(raw.endpoint ?? "").trim()); } catch { throw new ProtocolConfigError(tr("Адрес хранилища должен начинаться с https://")); } if ((endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && o.allowPrivate)) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || (endpoint.pathname !== "/" && endpoint.pathname !== "")) throw new ProtocolConfigError(tr("Адрес хранилища должен начинаться с https:// и не содержать путь, логин и пароль")); checkHost(endpoint.hostname, o); const prefix = String(raw.prefix ?? "").trim().replace(/^\/+/, ""); if (prefix && (!s3KeyOk(prefix) || prefix.length > 512)) throw new ProtocolConfigError(tr("Папка в хранилище содержит недопустимые символы")); return { endpoint: endpoint.origin, region: field(raw.region || "us-east-1", REGION_RE, tr("Укажите регион хранилища, например eu-central-1")), bucket: field(raw.bucket, BUCKET_RE, tr("Укажите название бакета: строчные латинские буквы, цифры, точка и дефис")), prefix: prefix && !prefix.endsWith("/") ? `${prefix}/` : prefix, accessKeyId: field(raw.accessKeyId, ACCESS_KEY_RE, tr("Укажите идентификатор ключа доступа")), } satisfies S3Config; } const user = field(raw.user, /^[^\s]{1,254}$/, tr("Укажите логин почтового ящика")); const from = String(raw.from ?? "").trim() || user; if (!EMAIL_RE.test(from)) throw new ProtocolConfigError(tr("Адрес отправителя — почта, например shop@example.com")); return { imapHost: checkHost(raw.imapHost, o), imapPort: port(raw.imapPort, 993), smtpHost: checkHost(raw.smtpHost || raw.imapHost, o), smtpPort: port(raw.smtpPort, 465), user, from, } satisfies MailConfig; } /** Hosts a connection talks to (for the internal-address check at call time). */ export function protocolHosts(protocol: GatewayProtocol, c: ProtocolConfig): string[] { if (protocol === "s3") return [new URL((c as S3Config).endpoint).hostname]; if (protocol === "mail") return [(c as MailConfig).imapHost, (c as MailConfig).smtpHost]; return [(c as SqlConfig | SshConfig).host]; } /** What the owner sees instead of a service address. */ export function protocolAddress(protocol: GatewayProtocol, c: ProtocolConfig): string { if (protocol === "postgres" || protocol === "mysql") { const s = c as SqlConfig; return `${protocol}://${s.user}@${s.host}:${s.port}/${s.database}`; } if (protocol === "ssh") { const s = c as SshConfig; return `ssh://${s.user}@${s.host}:${s.port}${s.root}`; } if (protocol === "s3") { const s = c as S3Config; return `${s.endpoint}/${s.bucket}/${s.prefix}`; } const s = c as MailConfig; return `imap://${s.user}@${s.imapHost}:${s.imapPort} · smtp://${s.smtpHost}:${s.smtpPort}`; } /** Password / private key / secret access key: one value; an SSH key may span lines. */ export function protocolSecretError(protocol: GatewayProtocol, secret: string): string | null { if (!secret) return tr("Пароль или ключ пустой"); if (Buffer.byteLength(secret) > PROTOCOL_SECRET_MAX_BYTES) return tr("Пароль или ключ больше 16 КБ"); if (secret.includes("\u0000")) return tr("Пароль или ключ содержит недопустимые символы"); if (protocol !== "ssh" && /[\r\n]/.test(secret)) return tr("Пароль или ключ должен быть одной строкой"); return null; } // ---------- SQL ---------- /** The SQL without comments and string literals — for the checks below only. */ export function sqlSkeleton(sql: string): string { return sql .replace(/\/\*[\s\S]*?\*\//g, " ") .replace(/--[^\n]*/g, " ") .replace(/#[^\n]*/g, " ") .replace(/\$([A-Za-z_]*)\$[\s\S]*?\$\1\$/g, "''") .replace(/'(?:[^'\\]|\\.|'')*'/g, "''") .replace(/"(?:[^"\\]|\\.|"")*"/g, '""') .replace(/`[^`]*`/g, "``"); } /** One statement only: no «;» except a trailing one. */ export function singleStatement(sql: string): boolean { return !sqlSkeleton(sql).trim().replace(/;\s*$/, "").includes(";"); } const READ_START = new Set(["select", "with", "show", "explain", "describe", "desc", "values", "table"]); /** * Belt over braces: `query` also runs in a READ ONLY transaction, but MySQL commits implicitly * before DDL, so the statement must look like reading too. */ export function isReadQuery(sql: string): boolean { const s = sqlSkeleton(sql).trim().replace(/^\(+\s*/, "").toLowerCase(); const first = s.match(/^[a-z]+/)?.[0] ?? ""; if (!READ_START.has(first)) return false; if (/\binto\s+(outfile|dumpfile)\b/.test(s)) return false; if (/\bfor\s+(update|share)\b|\block\s+in\s+share\s+mode\b/.test(s)) return false; return true; } export interface SqlAnswer { columns: string[]; rows: unknown[][]; /** Rows affected (execute) or returned (query). */ rowCount: number | null; /** More than SQL_MAX_ROWS rows: the rest was dropped. */ truncated: boolean; } function cell(v: unknown): string { let s: string; if (v == null) s = "NULL"; else if (v instanceof Date) s = v.toISOString(); else if (Buffer.isBuffer(v)) s = `\\x${v.subarray(0, CELL_MAX_CHARS / 2).toString("hex")}`; else if (typeof v === "object") s = JSON.stringify(v); else s = String(v); s = s.replace(/[\t\r\n]+/g, " "); return s.length > CELL_MAX_CHARS ? `${s.slice(0, CELL_MAX_CHARS)}…` : s; } /** A page of rows as a tab-separated table; the page shrinks to fit ANSWER_MAX_BYTES. */ export function formatRows(a: SqlAnswer, page = 1): { text: string; page: number; pages: number; truncated: boolean } { const pages = Math.max(1, Math.ceil(a.rows.length / SQL_PAGE_ROWS)); const p = Math.min(Math.max(1, Math.floor(page) || 1), pages); if (!a.columns.length) return { text: `OK${a.rowCount != null ? `, rows affected: ${a.rowCount}` : ""}`, page: 1, pages: 1, truncated: false }; const lines = [a.columns.map(cell).join("\t")]; let size = Buffer.byteLength(lines[0]!); let cut = false; for (const r of a.rows.slice((p - 1) * SQL_PAGE_ROWS, p * SQL_PAGE_ROWS)) { const line = r.map(cell).join("\t"); size += Buffer.byteLength(line) + 1; if (size > ANSWER_MAX_BYTES) { cut = true; break; } lines.push(line); } const head = `rows: ${a.rows.length}${a.truncated ? `+ (only the first ${SQL_MAX_ROWS} kept)` : ""} · page ${p} of ${pages}${p < pages ? ` — ask page ${p + 1} for more` : ""}${cut ? " · this page was cut at 64 KB" : ""}`; return { text: `${head}\n${lines.join("\n")}`, page: p, pages, truncated: a.truncated || cut }; } // ---------- SFTP paths ---------- /** An agent's path → absolute path inside root, or null (escapes, odd characters). */ export function sftpPath(root: string, raw: unknown): string | null { const v = String(raw ?? "").trim(); if (v.length > 1024 || /[\u0000-\u001f\u007f\\]/.test(v)) return null; const rel = v.startsWith(root + "/") || v === root ? v.slice(root.length) : v; if (rel.split("/").includes("..")) return null; const abs = posix.normalize(posix.join(root, rel.replace(/^\/+/, ""))); return within(root, abs) ? abs.replace(/(.)\/+$/, "$1") : null; } export const within = (root: string, p: string) => root === "/" || p === root || p.startsWith(`${root}/`); // ---------- S3 ---------- export function s3KeyOk(key: string): boolean { return !!key && key.length <= 1024 && !/[\u0000-\u001f\u007f\\]/.test(key) && !key.split("/").some((s) => s === "." || s === "..") && !key.startsWith("/"); } /** An agent's key → full key under the connection's prefix, or null. */ export function s3Key(cfg: S3Config, raw: unknown, o: { allowEmpty?: boolean } = {}): string | null { const v = String(raw ?? "").trim().replace(/^\/+/, ""); if (!v) return o.allowEmpty ? cfg.prefix : null; if (!s3KeyOk(v)) return null; return cfg.prefix + v; } const enc = (s: string) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); const sha256 = (b: Buffer | string) => createHash("sha256").update(b).digest("hex"); const hmac = (k: Buffer | string, s: string) => createHmac("sha256", k).update(s).digest(); export interface S3Request { method: "GET" | "PUT" | "DELETE"; url: URL; headers: Record; body: Buffer | null; } /** * AWS Signature V4, path-style (`//`) — works with AWS, MinIO, Yandex * Object Storage, Cloudflare R2 and others. Signed on the gateway: the agent never sees the key. */ export function signS3(cfg: S3Config, secret: string, r: { method: "GET" | "PUT" | "DELETE"; key: string | null; query?: Record; body?: Buffer | null; contentType?: string | null }, now = new Date()): S3Request { const amzDate = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, ""); const day = amzDate.slice(0, 8); const host = new URL(cfg.endpoint).host; const path = `/${cfg.bucket}${r.key != null ? `/${r.key.split("/").map(enc).join("/")}` : ""}`; const query = Object.entries(r.query ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([k, v]) => `${enc(k)}=${enc(v)}`).join("&"); const body = r.body ?? null; const payloadHash = sha256(body ?? ""); const headers: Record = { host, "x-amz-content-sha256": payloadHash, "x-amz-date": amzDate }; if (body) headers["content-length"] = String(body.length); if (body && r.contentType) headers["content-type"] = r.contentType; const names = Object.keys(headers).sort(); const canonical = [r.method, path, query, names.map((n) => `${n}:${headers[n]!.trim()}\n`).join(""), names.join(";"), payloadHash].join("\n"); const scope = `${day}/${cfg.region}/s3/aws4_request`; const toSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256(canonical)].join("\n"); const key = hmac(hmac(hmac(hmac(`AWS4${secret}`, day), cfg.region), "s3"), "aws4_request"); headers.authorization = `AWS4-HMAC-SHA256 Credential=${cfg.accessKeyId}/${scope}, SignedHeaders=${names.join(";")}, Signature=${createHmac("sha256", key).update(toSign).digest("hex")}`; const { host: _h, ...sent } = headers; return { method: r.method, url: new URL(`${cfg.endpoint}${path}${query ? `?${query}` : ""}`), headers: { ...sent, "user-agent": "PeppaFactory-AccessHub/1" }, body }; } /** ListObjectsV2 XML → keys (sizes, dates), no XML library. */ export function parseS3List(xml: string): { keys: Array<{ key: string; size: number; modified: string }>; truncated: boolean } { const keys: Array<{ key: string; size: number; modified: string }> = []; const unxml = (s: string) => s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&"); for (const m of xml.matchAll(/([\s\S]*?)<\/Contents>/g)) { const body = m[1]!; const tag = (t: string) => unxml(body.match(new RegExp(`<${t}>([\\s\\S]*?)`))?.[1] ?? ""); keys.push({ key: tag("Key"), size: Number(tag("Size")) || 0, modified: tag("LastModified") }); } return { keys, truncated: /true<\/IsTruncated>/.test(xml) }; } // ---------- SSH ---------- /** «SHA256:» like `ssh-keygen -l`. */ export function hostKeyFingerprint(key: Buffer): string { return `SHA256:${createHash("sha256").update(key).digest("base64").replace(/=+$/, "")}`; } export const sameFingerprint = (a: string, b: string) => a.replace(/=+$/, "") === b.replace(/=+$/, ""); /** A letter's flags the agent may set: IMAP system flags or simple keywords. */ export function mailFlags(raw: unknown): string[] | null { if (raw == null || raw === "") return []; const list = (Array.isArray(raw) ? raw : String(raw).split(/[\s,]+/)).map((s) => String(s).trim()).filter(Boolean); if (list.length > 10 || list.some((f) => !/^\\?[A-Za-z][A-Za-z0-9_$-]{0,40}$/.test(f))) return null; return list; } export function mailFolder(raw: unknown): string | null { const v = String(raw ?? "").trim() || "INBOX"; return v.length <= 200 && !/[\u0000-\u001f\u007f*%]/.test(v) ? v : null; } export function mailRecipients(raw: unknown): string[] | null { const list = (Array.isArray(raw) ? raw : String(raw ?? "").split(/[,;\s]+/)).map((s) => String(s).trim()).filter(Boolean); if (!list.length || list.length > MAIL_RECIPIENTS_MAX || list.some((a) => !EMAIL_RE.test(a))) return null; return list; }