peppa/packages/core/src/connection-drivers.ts

369 lines
16 KiB
TypeScript

// PEP-251: network drivers of the Access Hub gateway. Each driver gets a target whose address
// the gateway has already resolved and checked (`address`), so a DNS answer can't swap a public
// name for an internal one between the check and the connection; the name (`host`) is used only
// to verify the TLS certificate. Libraries are loaded on first use: nothing heavy at startup.
// Tests replace the whole `GatewayDrivers` object with mocks (packages/testkit/src/mock-access.ts).
import { connect as netConnect } from "node:net";
import { posix } from "node:path";
import { hostKeyFingerprint, sameFingerprint, within, type SqlAnswer } from "./connection-protocols.ts";
export type TlsMode = "verify" | "encrypt" | "off";
export type DriverErrorCode = "auth" | "down" | "timeout" | "host_key_changed" | "query" | "not_found" | "outside_root" | "too_large";
/** A driver failure the gateway turns into a reason; `message` reaches the agent only for `query`. */
export class DriverError extends Error {
code: DriverErrorCode;
/** host_key_changed: the key the server showed. */
seenHostKey?: string;
constructor(code: DriverErrorCode, message: string = code, seenHostKey?: string) {
super(message);
this.code = code;
this.seenHostKey = seenHostKey;
}
}
export interface SqlTarget {
protocol: "postgres" | "mysql";
host: string;
address: string;
port: number;
user: string;
database: string;
tls: TlsMode;
password: string;
}
export interface SqlRequest {
text: string;
readOnly: boolean;
timeoutMs: number;
maxRows: number;
}
export interface SshTarget {
host: string;
address: string;
port: number;
user: string;
/** Password or a private key (PEM / OpenSSH). */
secret: string;
/** Pinned key; null — the first contact pins what the server shows. */
hostKey: string | null;
root: string;
}
export type SshRequest =
| { op: "exec"; command: string; timeoutMs: number; maxBytes: number }
| { op: "read"; path: string; maxBytes: number }
| { op: "list"; path: string }
| { op: "write"; path: string; data: Buffer }
| { op: "probe" };
export interface SshAnswer {
/** The key the server showed (the gateway pins it on first contact). */
hostKey: string;
text?: string;
data?: Buffer;
exitCode?: number | null;
entries?: Array<{ name: string; type: "file" | "dir" | "link" | "other"; size: number }>;
truncated?: boolean;
}
export interface MailTarget {
imap: { host: string; address: string; port: number };
smtp: { host: string; address: string; port: number };
user: string;
password: string;
}
export type MailRequest =
| { op: "list"; folder: string; limit: number }
| { op: "get"; folder: string; uid: number; maxBytes: number }
| { op: "change"; folder: string; uid: number; add: string[]; remove: string[]; moveTo: string | null }
| { op: "send"; from: string; to: string[]; subject: string; text: string };
export interface MailAnswer {
letters?: Array<{ uid: number; date: string | null; from: string; subject: string; flags: string[] }>;
text?: string;
truncated?: boolean;
done?: string;
}
export interface GatewayDrivers {
sql(t: SqlTarget, r: SqlRequest): Promise<SqlAnswer>;
ssh(t: SshTarget, r: SshRequest): Promise<SshAnswer>;
mail(t: MailTarget, r: MailRequest): Promise<MailAnswer>;
}
const CONNECT_TIMEOUT_MS = 10_000;
const tlsOptions = (mode: TlsMode, host: string) => (mode === "off" ? undefined : { servername: host, rejectUnauthorized: mode === "verify" });
function networkError(e: unknown): DriverError {
if (e instanceof DriverError) return e;
const err = e as { code?: string; message?: string };
if (err?.code === "ETIMEDOUT" || /timeout|timed out/i.test(err?.message ?? "")) return new DriverError("timeout");
return new DriverError("down");
}
// ---------- SQL ----------
async function postgres(t: SqlTarget, r: SqlRequest): Promise<SqlAnswer> {
const { default: pg } = await import("pg");
// host = the checked address; pg keeps our servername because the host is an IP literal.
const client = new pg.Client({ host: t.address, port: t.port, user: t.user, password: t.password, database: t.database, ssl: tlsOptions(t.tls, t.host) ?? false, connectionTimeoutMillis: CONNECT_TIMEOUT_MS, query_timeout: r.timeoutMs + 2000, application_name: "forge-access-hub" });
client.on("error", () => {});
try {
await client.connect();
} catch (e) {
const code = (e as { code?: string }).code;
if (code === "28P01" || code === "28000") throw new DriverError("auth");
if (code === "3D000") throw new DriverError("query", "database does not exist");
throw networkError(e);
}
try {
if (r.readOnly) await client.query("BEGIN TRANSACTION READ ONLY");
await client.query(`SET ${r.readOnly ? "LOCAL " : ""}statement_timeout = ${Math.floor(r.timeoutMs)}`);
// Extended protocol: exactly one statement — «…; COMMIT; DROP …» can't ride along.
const res = (await client.query({ text: r.text, rowMode: "array", queryMode: "extended" } as never)) as unknown as { rows?: unknown[][]; fields?: Array<{ name: string }>; rowCount?: number | null };
if (r.readOnly) await client.query("ROLLBACK");
const rows = (res.rows ?? []) as unknown[][];
return { columns: (res.fields ?? []).map((f: { name: string }) => f.name), rows: rows.slice(0, r.maxRows), rowCount: res.rowCount ?? null, truncated: rows.length > r.maxRows };
} catch (e) {
const err = e as { code?: string; message?: string };
if (err.code === "57014") throw new DriverError("timeout");
if (err.code) throw new DriverError("query", err.message ?? "query failed");
throw networkError(e);
} finally {
await client.end().catch(() => {});
}
}
async function mysql(t: SqlTarget, r: SqlRequest): Promise<SqlAnswer> {
const lib = await import("mysql2/promise");
let conn: Awaited<ReturnType<typeof lib.createConnection>>;
try {
conn = await lib.createConnection({
// The name stays for the certificate check; the socket goes to the checked address.
host: t.host,
stream: () => netConnect(t.port, t.address),
port: t.port,
user: t.user,
password: t.password,
database: t.database,
ssl: tlsOptions(t.tls, t.host),
connectTimeout: CONNECT_TIMEOUT_MS,
multipleStatements: false,
dateStrings: true,
supportBigNumbers: true,
bigNumberStrings: true,
} as never);
} catch (e) {
const code = (e as { code?: string }).code;
if (code === "ER_ACCESS_DENIED_ERROR" || code === "ER_DBACCESS_DENIED_ERROR") throw new DriverError("auth");
if (code === "ER_BAD_DB_ERROR") throw new DriverError("query", "database does not exist");
throw networkError(e);
}
conn.on("error", () => {});
try {
if (r.readOnly) {
await conn.query(`SET SESSION MAX_EXECUTION_TIME = ${Math.floor(r.timeoutMs)}`).catch(() => {}); // MariaDB: no such variable
await conn.query("START TRANSACTION READ ONLY");
}
const [rows, fields] = await conn.query({ sql: r.text, rowsAsArray: true, timeout: r.timeoutMs });
if (r.readOnly) await conn.query("ROLLBACK");
if (!Array.isArray(rows)) return { columns: [], rows: [], rowCount: (rows as { affectedRows?: number }).affectedRows ?? null, truncated: false };
const list = rows as unknown as unknown[][];
return { columns: (fields ?? []).map((f) => f.name), rows: list.slice(0, r.maxRows), rowCount: list.length, truncated: list.length > r.maxRows };
} catch (e) {
const err = e as { code?: string; message?: string; sqlState?: string };
if (err.code === "PROTOCOL_SEQUENCE_TIMEOUT" || err.code === "ER_QUERY_TIMEOUT") throw new DriverError("timeout");
if (err.sqlState || err.code?.startsWith("ER_")) throw new DriverError("query", err.message ?? "query failed");
throw networkError(e);
} finally {
await conn.end().catch(() => {});
}
}
// ---------- SSH / SFTP ----------
async function ssh(t: SshTarget, r: SshRequest): Promise<SshAnswer> {
const { Client } = await import("ssh2");
const client = new Client();
let seen = "";
let mismatch = false;
const auth = /^-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(t.secret.trim()) ? { privateKey: t.secret.trim() } : { password: t.secret };
await new Promise<void>((resolve, reject) => {
client.on("ready", () => resolve());
client.on("error", (e: Error & { level?: string }) => {
if (mismatch) return reject(new DriverError("host_key_changed", "host key changed", seen));
if (e.level === "client-authentication") return reject(new DriverError("auth"));
reject(networkError(e));
});
client.connect({
host: t.address,
port: t.port,
username: t.user,
...auth,
readyTimeout: CONNECT_TIMEOUT_MS,
hostVerifier: (key: Buffer) => {
seen = hostKeyFingerprint(key);
mismatch = !!t.hostKey && !sameFingerprint(t.hostKey, seen);
return !mismatch;
},
});
});
try {
if (r.op === "probe") return { hostKey: seen };
if (r.op === "exec") return { hostKey: seen, ...(await sshExec(client, r)) };
const sftp = await new Promise<import("ssh2").SFTPWrapper>((res, rej) => client.sftp((e, s) => (e ? rej(networkError(e)) : res(s))));
const call = <T,>(fn: (cb: (e: Error | null | undefined, v: T) => void) => void) =>
new Promise<T>((res, rej) => fn((e, v) => (e ? rej((e as { code?: number }).code === 2 ? new DriverError("not_found") : new DriverError("query", e.message)) : res(v))));
// Symlinks inside the root must not lead out of it: the real path is checked.
const real = async (p: string) => {
const rp = await call<string>((cb) => sftp.realpath(p, cb));
const rootReal = await call<string>((cb) => sftp.realpath(t.root, cb)).catch(() => t.root);
if (!within(rootReal, rp)) throw new DriverError("outside_root");
return rp;
};
if (r.op === "list") {
const dir = await real(r.path);
const list = await call<import("ssh2").FileEntryWithStats[]>((cb) => sftp.readdir(dir, cb));
return {
hostKey: seen,
entries: list.slice(0, 1000).map((f) => ({ name: f.filename, type: f.attrs.isDirectory() ? "dir" : f.attrs.isFile() ? "file" : f.attrs.isSymbolicLink() ? "link" : "other", size: f.attrs.size })),
truncated: list.length > 1000,
};
}
if (r.op === "read") {
const file = await real(r.path);
const st = await call<import("ssh2").Stats>((cb) => sftp.stat(file, cb));
if (st.size > r.maxBytes) throw new DriverError("too_large");
const data = await call<Buffer>((cb) => sftp.readFile(file, cb as never));
return { hostKey: seen, data };
}
// write: an existing file by its real path, a new one by its directory's.
const existing = await call<string>((cb) => sftp.realpath(r.path, cb)).catch(() => null);
if (existing) await real(r.path);
else await real(posix.dirname(r.path));
await call<void>((cb) => sftp.writeFile(r.path, r.data, cb as never));
return { hostKey: seen, text: `written ${r.data.length} bytes` };
} finally {
client.end();
}
}
function sshExec(client: import("ssh2").Client, r: { command: string; timeoutMs: number; maxBytes: number }): Promise<{ text: string; exitCode: number | null; truncated: boolean }> {
return new Promise((resolve, reject) => {
client.exec(r.command, (err, stream) => {
if (err) return reject(networkError(err));
const chunks: Buffer[] = [];
let size = 0;
let truncated = false;
const take = (c: Buffer) => {
if (truncated) return;
size += c.length;
if (size > r.maxBytes) {
truncated = true;
chunks.push(c.subarray(0, c.length - (size - r.maxBytes)));
return;
}
chunks.push(c);
};
const timer = setTimeout(() => {
truncated = true;
stream.close();
reject(new DriverError("timeout"));
}, r.timeoutMs);
stream.on("data", take);
stream.stderr.on("data", take);
stream.on("close", (code: number | null) => {
clearTimeout(timer);
resolve({ text: Buffer.concat(chunks).toString("utf8"), exitCode: code ?? null, truncated });
});
});
});
}
// ---------- mail ----------
type BodyNode = { part?: string; type?: string; childNodes?: BodyNode[] };
function textPart(n: BodyNode | undefined): string | null {
if (!n) return null;
if (n.type === "text/plain") return n.part ?? "1";
for (const c of n.childNodes ?? []) {
const p = textPart(c);
if (p) return p;
}
return null;
}
async function mail(t: MailTarget, r: MailRequest): Promise<MailAnswer> {
if (r.op === "send") {
const { default: nodemailer } = await import("nodemailer");
const transport = nodemailer.createTransport({ host: t.smtp.address, port: t.smtp.port, secure: t.smtp.port === 465, requireTLS: t.smtp.port !== 465, auth: { user: t.user, pass: t.password }, tls: { servername: t.smtp.host }, name: "forge-access-hub", connectionTimeout: CONNECT_TIMEOUT_MS, greetingTimeout: CONNECT_TIMEOUT_MS, socketTimeout: 30_000 });
try {
const info = await transport.sendMail({ from: r.from, to: r.to, subject: r.subject, text: r.text });
return { done: `sent to ${info.accepted.length} of ${r.to.length} recipients` };
} catch (e) {
const err = e as { code?: string; responseCode?: number };
if (err.code === "EAUTH" || err.responseCode === 535) throw new DriverError("auth");
if (err.code === "EENVELOPE" || err.code === "EMESSAGE") throw new DriverError("query", "the server refused the letter");
throw networkError(e);
} finally {
transport.close();
}
}
const { ImapFlow } = await import("imapflow");
const client = new ImapFlow({ host: t.imap.address, servername: t.imap.host, port: t.imap.port, secure: t.imap.port !== 143, doSTARTTLS: t.imap.port === 143 ? true : undefined, auth: { user: t.user, pass: t.password }, logger: false, connectionTimeout: CONNECT_TIMEOUT_MS, greetingTimeout: CONNECT_TIMEOUT_MS, socketTimeout: 30_000 } as never);
client.on("error", () => {});
try {
await client.connect();
} catch (e) {
if ((e as { authenticationFailed?: boolean }).authenticationFailed) throw new DriverError("auth");
throw networkError(e);
}
try {
const opened = await client.mailboxOpen(r.folder, { readOnly: r.op !== "change" }).catch(() => {
throw new DriverError("not_found", "no such folder");
});
if (r.op === "list") {
const letters: NonNullable<MailAnswer["letters"]> = [];
if (opened.exists > 0) {
const from = Math.max(1, opened.exists - r.limit + 1);
for await (const m of client.fetch(`${from}:*`, { uid: true, envelope: true, flags: true, internalDate: true })) {
const a = m.envelope?.from?.[0];
letters.push({ uid: m.uid, date: m.internalDate ? new Date(m.internalDate).toISOString() : null, from: a ? `${a.name ? `${a.name} ` : ""}<${a.address ?? ""}>` : "", subject: m.envelope?.subject ?? "", flags: [...(m.flags ?? [])] });
}
}
return { letters: letters.reverse() };
}
if (r.op === "get") {
const m = await client.fetchOne(String(r.uid), { uid: true, envelope: true, bodyStructure: true }, { uid: true });
if (!m) throw new DriverError("not_found", "no such letter");
const part = textPart(m.bodyStructure as BodyNode) ?? "TEXT";
const dl = await client.download(String(r.uid), part, { uid: true, maxBytes: r.maxBytes });
const chunks: Buffer[] = [];
for await (const c of dl.content ?? []) chunks.push(c as Buffer);
const body = Buffer.concat(chunks);
const a = m.envelope?.from?.[0];
return { text: [`From: ${a?.address ?? ""}`, `Subject: ${m.envelope?.subject ?? ""}`, `Date: ${m.envelope?.date ? new Date(m.envelope.date).toISOString() : ""}`, "", body.subarray(0, r.maxBytes).toString("utf8")].join("\n"), truncated: body.length >= r.maxBytes };
}
const uid = String(r.uid);
if (r.add.length) await client.messageFlagsAdd(uid, r.add, { uid: true });
if (r.remove.length) await client.messageFlagsRemove(uid, r.remove, { uid: true });
if (r.moveTo) {
const moved = await client.messageMove(uid, r.moveTo, { uid: true });
if (!moved) throw new DriverError("not_found", "could not move the letter");
}
return { done: "changed" };
} catch (e) {
if (e instanceof DriverError) throw e;
throw new DriverError("query", (e as Error).message ?? "mail server refused");
} finally {
await client.logout().catch(() => client.close());
}
}
export const defaultDrivers: GatewayDrivers = {
sql: (t, r) => (t.protocol === "postgres" ? postgres(t, r) : mysql(t, r)),
ssh,
mail,
};