diff --git a/.env.example b/.env.example index e6347b5..4a1945b 100644 --- a/.env.example +++ b/.env.example @@ -14,6 +14,10 @@ REDIS_PORT=6379 # Postgres (matches docker-compose.yml). For a hosted DB (e.g. RDS): # DATABASE_URL=postgres://:@:5432/?sslmode=require DATABASE_URL=postgres://rootmail:rootmail@localhost:5432/rootmail +# Shared postgres.js pool. Unset uses the process default (API 5, worker 3). +# Idle connections close after 20s. A connection is recycled after 1800s. +# Must be a positive integer. Blank is the same as unset. +# DB_POOL_MAX=5 # Redis — queue, idempotency cache, rate limits (matches docker-compose.yml). # NOTE: ElastiCache (especially serverless) is VPC-only and is NOT reachable @@ -158,6 +162,9 @@ UPLOAD_MAX_BYTES=5242880 # Generate: openssl genpkey -algorithm ed25519 # Provide as a double-quoted multi-line value, or single line with \n escapes. # PROOF_SIGNING_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n" +# Optional retired public keys, checked after the current key when verifying. +# Comma-separated SPKI PEMs. Multi-line, or one line with \n escapes. Not private keys. +# PROOF_VERIFY_PUBLIC_KEYS="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n" # --- Secrets at rest ------------------------------------------------------ # Master key for encrypting stored secrets — currently every sub-tenant's DKIM diff --git a/DEPLOY.md b/DEPLOY.md index 1e10b6e..91bda31 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -87,7 +87,8 @@ signing keys) are loaded only into **api**/**worker**; the public-facing Next ap (or an instance role); `ROOTMAIL_DOMAIN`, `DKIM_SELECTOR`; `INBOUND_DOMAIN` for reply capture - `STRIPE_SECRET_KEY` + price ids + `STRIPE_WEBHOOK_SECRET` - `ANTHROPIC_API_KEY` -- `PROOF_SIGNING_KEY`, `LINK_SIGNING_SECRET`, `INTERNAL_API_SECRET` +- `PROOF_SIGNING_KEY`, `PROOF_VERIFY_PUBLIC_KEYS` (optional retired public keys), `LINK_SIGNING_SECRET`, `INTERNAL_API_SECRET` +- `DB_POOL_MAX` (optional positive integer; the API defaults to 5 and the worker to 3) - Asset storage: `ASSET_S3_BUCKET` (+ AWS creds) and `ASSET_PUBLIC_URL` - OAuth (dashboard `.env.local`): Google/GitHub/Apple creds; `DNS_VERIFY_MODE=live` diff --git a/apps/api/src/db-pool.test.ts b/apps/api/src/db-pool.test.ts new file mode 100644 index 0000000..e775df1 --- /dev/null +++ b/apps/api/src/db-pool.test.ts @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; + +const packageDir = fileURLToPath(new URL("..", import.meta.url)); + +function tsxImport(): string { + const require = createRequire(import.meta.url); + try { + return require.resolve("tsx"); + } catch { + return createRequire(fileURLToPath(new URL("../../../package.json", import.meta.url))).resolve("tsx"); + } +} + +function run(script: string, dbPoolMax: string): { status: number | null; output: string } { + const result = spawnSync(process.execPath, ["--import", tsxImport(), "--input-type=module", "-e", script], { + cwd: packageDir, + env: { ...process.env, DB_POOL_MAX: dbPoolMax }, + encoding: "utf8", + timeout: 60_000, + }); + return { status: result.status, output: `${result.stdout ?? ""}\n${result.stderr ?? ""}` }; +} + +const OPEN = `import { API_DB_POOL_DEFAULT } from "./src/db-pool.ts"; +import { closeDb, configuredDbPoolDefault, sql } from "@rootmail/db"; +console.log([API_DB_POOL_DEFAULT, configuredDbPoolDefault(), sql.options.max, sql.options.idle_timeout, sql.options.max_lifetime].join(",")); +await closeDb();`; + +describe("api database pool", () => { + it("passes a default of 5 into the shared client", () => { + const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8"); + const pool = readFileSync(new URL("./db-pool.ts", import.meta.url), "utf8"); + assert.match(source, /^import "\.\/db-pool";/); + assert.match(pool, /export const API_DB_POOL_DEFAULT = 5/); + assert.match(pool, /configureDbPool\(API_DB_POOL_DEFAULT\)/); + const result = run(OPEN, ""); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /5,5,5,20,1800/); + }); + + it("lets DB_POOL_MAX override the api default on the opened client", () => { + const result = run(OPEN, "4"); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /5,5,4,20,1800/); + }); +}); diff --git a/apps/api/src/db-pool.ts b/apps/api/src/db-pool.ts new file mode 100644 index 0000000..94d2e44 --- /dev/null +++ b/apps/api/src/db-pool.ts @@ -0,0 +1,5 @@ +import { configureDbPool } from "@rootmail/db/pool-default"; + +export const API_DB_POOL_DEFAULT = 5; + +configureDbPool(API_DB_POOL_DEFAULT); diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index e0af30b..19a1cc7 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -1,3 +1,4 @@ +import "./db-pool"; import { env } from "@rootmail/core"; import { closeDb, ensureBetaInviteAutomation, ensureInternalAccount } from "@rootmail/db"; import { betaInviteRequired } from "./lib/beta"; diff --git a/apps/api/src/routes/proof.ts b/apps/api/src/routes/proof.ts index 66cb695..38cb4e4 100644 --- a/apps/api/src/routes/proof.ts +++ b/apps/api/src/routes/proof.ts @@ -9,8 +9,8 @@ const verifyBody = z.object({ }); export async function proofRoutes(app: FastifyInstance): Promise { - // PUBLIC — anyone holding a bundle can verify it against rootmail's signing - // key (the bundle's own public_key is informational; verification uses ours). + // PUBLIC — anyone holding a bundle can verify it against the current signing + // key, then PROOF_VERIFY_PUBLIC_KEYS. The bundle's own public_key is ignored. app.post("/v1/proof/verify", async (req) => { const body = parse(verifyBody, req.body); return { object: "proof_verification", valid: verifyProof(body.bundle, body.signature) }; diff --git a/apps/worker/src/db-pool.test.ts b/apps/worker/src/db-pool.test.ts new file mode 100644 index 0000000..3fc93c9 --- /dev/null +++ b/apps/worker/src/db-pool.test.ts @@ -0,0 +1,54 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; + +const packageDir = fileURLToPath(new URL("..", import.meta.url)); + +function tsxImport(): string { + const require = createRequire(import.meta.url); + try { + return require.resolve("tsx"); + } catch { + return createRequire(fileURLToPath(new URL("../../../package.json", import.meta.url))).resolve("tsx"); + } +} + +function run(dbPoolMax: string): { status: number | null; output: string } { + const result = spawnSync( + process.execPath, + ["--import", tsxImport(), "--input-type=module", "-e", + `import { WORKER_DB_POOL_DEFAULT } from "./src/db-pool.ts"; + import { closeDb, configuredDbPoolDefault, sql } from "@rootmail/db"; + console.log([WORKER_DB_POOL_DEFAULT, configuredDbPoolDefault(), sql.options.max, sql.options.idle_timeout, sql.options.max_lifetime].join(",")); + await closeDb();`], + { + cwd: packageDir, + env: { ...process.env, DB_POOL_MAX: dbPoolMax }, + encoding: "utf8", + timeout: 60_000, + }, + ); + return { status: result.status, output: `${result.stdout ?? ""}\n${result.stderr ?? ""}` }; +} + +describe("worker database pool", () => { + it("passes a default of 3 into the shared client", () => { + const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8"); + const pool = readFileSync(new URL("./db-pool.ts", import.meta.url), "utf8"); + assert.match(source, /^import "\.\/db-pool";/); + assert.match(pool, /export const WORKER_DB_POOL_DEFAULT = 3/); + assert.match(pool, /configureDbPool\(WORKER_DB_POOL_DEFAULT\)/); + const result = run(""); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /3,3,3,20,1800/); + }); + + it("lets DB_POOL_MAX override the worker default on the opened client", () => { + const result = run("2"); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /3,3,2,20,1800/); + }); +}); diff --git a/apps/worker/src/db-pool.ts b/apps/worker/src/db-pool.ts new file mode 100644 index 0000000..d8ab988 --- /dev/null +++ b/apps/worker/src/db-pool.ts @@ -0,0 +1,5 @@ +import { configureDbPool } from "@rootmail/db/pool-default"; + +export const WORKER_DB_POOL_DEFAULT = 3; + +configureDbPool(WORKER_DB_POOL_DEFAULT); diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 762541c..d6aaebd 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -1,3 +1,4 @@ +import "./db-pool"; import { type ConnectionOptions, Worker } from "bullmq"; import { BULL_PREFIX, diff --git a/packages/core/src/db-pool.test.ts b/packages/core/src/db-pool.test.ts new file mode 100644 index 0000000..22cc7bf --- /dev/null +++ b/packages/core/src/db-pool.test.ts @@ -0,0 +1,75 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createRequire } from "node:module"; +import { describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; +import { parseDbPoolMax } from "./db-pool"; + +const packageDir = fileURLToPath(new URL("..", import.meta.url)); + +function tsxImport(): string { + const require = createRequire(import.meta.url); + try { + return require.resolve("tsx"); + } catch { + return createRequire(fileURLToPath(new URL("../../../package.json", import.meta.url))).resolve("tsx"); + } +} + +function importEnv(dbPoolMax: string | undefined): { status: number | null; output: string } { + const env = { ...process.env }; + if (dbPoolMax === undefined) delete env.DB_POOL_MAX; + else env.DB_POOL_MAX = dbPoolMax; + const result = spawnSync( + process.execPath, + ["--import", tsxImport(), "--input-type=module", "-e", "import { env } from './src/env.ts'; console.log('POOL_MAX=' + String(env.DB_POOL_MAX))"], + { cwd: packageDir, env, encoding: "utf8", timeout: 60_000 }, + ); + return { status: result.status, output: `${result.stdout ?? ""}\n${result.stderr ?? ""}` }; +} + +describe("parseDbPoolMax", () => { + it("accepts a positive integer and treats blank as unset", () => { + assert.equal(parseDbPoolMax(undefined), undefined); + assert.equal(parseDbPoolMax(""), undefined); + assert.equal(parseDbPoolMax(" "), undefined); + assert.equal(parseDbPoolMax("5"), 5); + assert.equal(parseDbPoolMax(" 12 "), 12); + }); + + it("rejects anything that is not a positive integer", () => { + for (const raw of ["0", "-1", "1.5", "10abc", "nope", "+5", "01", "1e2", "9007199254740993"]) { + assert.throws( + () => parseDbPoolMax(raw), + (err: Error) => { + assert.match(err.message, /DB_POOL_MAX must be a positive integer/); + assert.equal(err.message.includes(JSON.stringify(raw)), true); + return true; + }, + ); + } + }); +}); + +describe("DB_POOL_MAX at process startup", () => { + it("loads a valid value onto env", () => { + const result = importEnv("4"); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /POOL_MAX=4/); + }); + + it("treats a blank value as unset", () => { + const result = importEnv(""); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /POOL_MAX=undefined/); + }); + + it("crashes with a clear error on an invalid value", () => { + const result = importEnv("nope"); + assert.notEqual(result.status, 0); + assert.match(result.output, /DB_POOL_MAX must be a positive integer/); + assert.match(result.output, /nope/); + assert.equal(result.output.includes("BEGIN PRIVATE KEY"), false); + assert.equal(result.output.includes("BEGIN PUBLIC KEY"), false); + }); +}); diff --git a/packages/core/src/db-pool.ts b/packages/core/src/db-pool.ts new file mode 100644 index 0000000..3ff11b2 --- /dev/null +++ b/packages/core/src/db-pool.ts @@ -0,0 +1,15 @@ +const POSITIVE_INTEGER = /^[1-9]\d*$/; + +/** `undefined` means unset: the caller supplies its own default. */ +export function parseDbPoolMax(raw: string | undefined): number | undefined { + if (raw === undefined || raw.trim() === "") return undefined; + const trimmed = raw.trim(); + if (!POSITIVE_INTEGER.test(trimmed)) { + throw new Error(`DB_POOL_MAX must be a positive integer, got ${JSON.stringify(raw)}`); + } + const value = Number(trimmed); + if (!Number.isSafeInteger(value)) { + throw new Error(`DB_POOL_MAX must be a positive integer, got ${JSON.stringify(raw)}`); + } + return value; +} diff --git a/packages/core/src/env.ts b/packages/core/src/env.ts index 01da926..95a975a 100644 --- a/packages/core/src/env.ts +++ b/packages/core/src/env.ts @@ -2,6 +2,7 @@ import { existsSync } from "node:fs"; import { dirname, join } from "node:path"; import { config as loadDotenv } from "dotenv"; import { z } from "zod"; +import { parseDbPoolMax } from "./db-pool"; /** Walk up from `start` looking for a `.env` file (monorepo root lives above cwd). */ function findEnvFile(start: string): string | undefined { @@ -71,9 +72,15 @@ const EnvSchema = z.object({ // Ed25519 private key (PKCS8 PEM) for signing Layer-3 proof bundles. Unset → // a stable dev key in source (dev-only; in production the API refuses to start - // without a real Ed25519 key — see packages/core/src/proof.ts). Generate prod: + // without a real Ed25519 key — see packages/core/src/proof.ts). A multi-line + // PEM or a single line with literal \n escapes. Generate prod: // openssl genpkey -algorithm ed25519 PROOF_SIGNING_KEY: z.string().optional(), + // Retired Ed25519 public keys (SPKI PEM) still accepted when verifying proofs + // after PROOF_SIGNING_KEY rotates. Comma-separated. Each entry is a multi-line + // PEM or one line with literal \n escapes. Unset checks the current key only. + // Public keys only: openssl pkey -in old.pem -pubout + PROOF_VERIFY_PUBLIC_KEYS: z.string().optional(), // Master key for encrypting secrets at rest — today, every sub-tenant's DKIM // private key. Unset → a dev-only derived key, so local development needs no @@ -282,6 +289,8 @@ if (!parsed.success) { throw new Error("Invalid environment configuration"); } +const dbPoolMax = parseDbPoolMax(process.env.DB_POOL_MAX); + /* * Refuse to run without a real ENCRYPTION_KEY in production. * @@ -315,7 +324,10 @@ if (parsed.data.NODE_ENV === "production" && !parsed.data.ENCRYPTION_KEY) { ); } -export const env = parsed.data; +export const env = { + ...parsed.data, + DB_POOL_MAX: dbPoolMax, +}; export type Env = typeof env; /** The human inbox for replies to platform mail that says "just reply". */ diff --git a/packages/core/src/proof.test.ts b/packages/core/src/proof.test.ts index 46c0987..d21fac7 100644 --- a/packages/core/src/proof.test.ts +++ b/packages/core/src/proof.test.ts @@ -1,7 +1,18 @@ import assert from "node:assert/strict"; -import { generateKeyPairSync, sign, verify, createPublicKey } from "node:crypto"; -import { describe, it } from "node:test"; -import { DEV_PROOF_KEY, ProofKeyError, proofKeyFingerprint, resolveProofSigningKey } from "./proof"; +import { generateKeyPairSync, sign, verify, createPublicKey, createPrivateKey } from "node:crypto"; +import { after, describe, it } from "node:test"; +import { env } from "./env"; +import { + DEV_PROOF_KEY, + ProofKeyError, + assertProofSigningKey, + canonicalize, + proofKeyFingerprint, + proofVerifyPublicKeys, + resolveProofSigningKey, + signProof, + verifyProof, +} from "./proof"; // No key material is written in this file: the dev key is imported from // proof.ts and every other key is generated when the test runs. @@ -95,12 +106,121 @@ describe("proof signing key — dev and test behaviour is unchanged", () => { } }); - it("uses a configured key as given", () => { + it("uses a multi-line PEM and a single-line \\n PEM as the same key", () => { const pem = pkcs8("ed25519"); - assert.equal(proofKeyFingerprint(resolveProofSigningKey(pem, false)), proofKeyFingerprint(createPublicKey(pem))); + const expected = proofKeyFingerprint(createPublicKey(pem)); + assert.equal(proofKeyFingerprint(resolveProofSigningKey(pem, false)), expected); + assert.equal(proofKeyFingerprint(resolveProofSigningKey(pem.trim().replace(/\n/g, "\\n"), false)), expected); }); it("still allows the dev key itself", () => { assert.equal(proofKeyFingerprint(resolveProofSigningKey(DEV_PEM, false)), devFingerprint); }); }); + +function spki(privatePem: string): string { + const exported = createPublicKey(privatePem).export({ type: "spki", format: "pem" }); + return typeof exported === "string" ? exported : exported.toString("utf8"); +} + +function signBundle(bundle: object, privatePem: string): string { + return sign(null, Buffer.from(canonicalize(bundle)), createPrivateKey(privatePem)).toString("base64"); +} + +describe("proof verification — retired public keys", { concurrency: false }, () => { + const previous = { + nodeEnv: env.NODE_ENV, + key: env.PROOF_SIGNING_KEY, + extras: env.PROOF_VERIFY_PUBLIC_KEYS, + }; + + after(() => { + env.NODE_ENV = previous.nodeEnv; + env.PROOF_SIGNING_KEY = previous.key; + env.PROOF_VERIFY_PUBLIC_KEYS = previous.extras; + }); + + it("verifies a retired key when it is listed, in either PEM form, and rejects it when it is not", () => { + const currentPrivate = pkcs8("ed25519"); + const oldPrivate = pkcs8("ed25519"); + const otherPrivate = pkcs8("ed25519"); + const currentPublic = spki(currentPrivate); + const oldPublic = spki(oldPrivate); + const otherPublic = spki(otherPrivate); + const bundle = { hello: "rotation" }; + const oldSignature = signBundle(bundle, oldPrivate); + env.NODE_ENV = "test"; + env.PROOF_SIGNING_KEY = currentPrivate; + env.PROOF_VERIFY_PUBLIC_KEYS = undefined; + assertProofSigningKey(); + assert.equal(verifyProof(bundle, oldSignature), false); + + env.PROOF_VERIFY_PUBLIC_KEYS = oldPublic.trim().replace(/\n/g, "\\n"); + assert.equal(verifyProof(bundle, oldSignature), true); + env.PROOF_VERIFY_PUBLIC_KEYS = oldPublic; + assert.equal(verifyProof(bundle, oldSignature), true); + + const signed = signProof(bundle); + assert.equal(signed.algorithm, "ed25519"); + assert.equal(proofKeyFingerprint(createPublicKey(signed.public_key)), proofKeyFingerprint(createPublicKey(currentPublic))); + assert.notEqual(proofKeyFingerprint(createPublicKey(signed.public_key)), proofKeyFingerprint(createPublicKey(oldPublic))); + assert.equal(verifyProof(bundle, signed.signature), true); + + env.PROOF_VERIFY_PUBLIC_KEYS = otherPublic; + assert.equal(verifyProof(bundle, oldSignature), false); + assert.equal(verifyProof(bundle, signed.signature), true); + + const escaped = (pem: string) => pem.trim().replace(/\n/g, "\\n"); + env.PROOF_VERIFY_PUBLIC_KEYS = `${escaped(otherPublic)},${escaped(oldPublic)}`; + assert.equal(verifyProof(bundle, oldSignature), true); + assert.equal(proofVerifyPublicKeys(env.PROOF_VERIFY_PUBLIC_KEYS, false).length, 2); + + env.PROOF_VERIFY_PUBLIC_KEYS = `"${escaped(oldPublic)}"`; + assert.equal(verifyProof(bundle, oldSignature), true); + env.PROOF_VERIFY_PUBLIC_KEYS = oldPrivate; + assert.throws( + () => verifyProof(bundle, oldSignature), + (err: Error) => { + assert.match(err.message, /SPKI PEM public key/); + for (const line of secretLines(oldPrivate)) assert.equal(err.message.includes(line.slice(0, 16)), false); + return true; + }, + ); + }); + + it("rejects an unusable PROOF_VERIFY_PUBLIC_KEYS without echoing it", () => { + const junk = "not-a-key-supersecretvalue"; + env.NODE_ENV = "test"; + env.PROOF_SIGNING_KEY = pkcs8("ed25519"); + env.PROOF_VERIFY_PUBLIC_KEYS = junk; + assert.throws( + () => verifyProof({ hello: "x" }, "aaaa"), + (err: Error) => { + assert.match(err.message, /PROOF_VERIFY_PUBLIC_KEYS entry 1/); + assert.equal(err.message.includes(junk), false); + return true; + }, + ); + assert.throws(() => assertProofSigningKey(), (err: Error) => { + assert.match(err.message, /PROOF_VERIFY_PUBLIC_KEYS/); + assert.equal(err.message.includes(junk), false); + return true; + }); + }); + + it("refuses the committed dev public key in production", () => { + const devPublic = spki(DEV_PEM); + env.NODE_ENV = "production"; + env.PROOF_SIGNING_KEY = pkcs8("ed25519"); + env.PROOF_VERIFY_PUBLIC_KEYS = devPublic; + assert.throws( + () => assertProofSigningKey(), + (err: Error) => { + assert.match(err.message, /development key committed to this repository/); + for (const line of secretLines(devPublic)) assert.equal(err.message.includes(line.slice(0, 16)), false); + for (const line of secretLines(DEV_PEM)) assert.equal(err.message.includes(line.slice(0, 16)), false); + return true; + }, + ); + }); +}); diff --git a/packages/core/src/proof.ts b/packages/core/src/proof.ts index c94ad61..7b7b146 100644 --- a/packages/core/src/proof.ts +++ b/packages/core/src/proof.ts @@ -54,23 +54,31 @@ export class ProofKeyError extends Error { } } +function unwrapQuotes(raw: string): string { + const trimmed = raw.trim(); + if (trimmed.length >= 2 && (trimmed[0] === '"' || trimmed[0] === "'") && trimmed.at(-1) === trimmed[0]) { + return trimmed.slice(1, -1).trim(); + } + return trimmed; +} + /** * Decide which key signs proofs. * - * Outside production: unchanged — a value containing "PRIVATE KEY" is used as - * given, anything else falls back to the committed dev key. + * Outside production, a value containing "PRIVATE KEY" is used after the same + * PEM normalization as production; anything else falls back to the committed dev key. * * In production: fail closed. Missing, malformed, unparsable, not Ed25519, or * the committed dev key itself → ProofKeyError. Before this, every one of those * silently signed with a key anyone can read in this repository. */ export function resolveProofSigningKey(raw: string | undefined, production: boolean): KeyObject { + const pem = raw === undefined || raw.trim() === "" ? undefined : normalizePem(raw); if (!production) { - return createPrivateKey(raw?.includes("PRIVATE KEY") ? raw : DEV_PROOF_KEY); + return createPrivateKey(pem !== undefined && pem.includes("PRIVATE KEY") ? pem : DEV_PROOF_KEY); } - if (raw === undefined || raw.trim() === "") throw new ProofKeyError("is required in production and is not set."); - const pem = normalizePem(raw); + if (pem === undefined) throw new ProofKeyError("is required in production and is not set."); if (!pem.includes("-----BEGIN PRIVATE KEY-----") || !pem.includes("-----END PRIVATE KEY-----")) { throw new ProofKeyError("is set but is not a PKCS8 PEM private key."); } @@ -91,6 +99,41 @@ export function resolveProofSigningKey(raw: string | undefined, production: bool return key; } +/** SPKI public keys from `PROOF_VERIFY_PUBLIC_KEYS`. The value is never included in an error. */ +export function proofVerifyPublicKeys(raw: string | undefined, production: boolean): KeyObject[] { + if (raw === undefined || raw.trim() === "") return []; + const parts = unwrapQuotes(raw) + .split(",") + .map((part) => part.trim()) + .filter((part) => part !== ""); + return parts.map((part, index) => { + const pem = normalizePem(part); + const label = `entry ${index + 1}`; + if (!pem.includes("-----BEGIN PUBLIC KEY-----") || !pem.includes("-----END PUBLIC KEY-----")) { + throw new Error( + `PROOF_VERIFY_PUBLIC_KEYS ${label} must be an SPKI PEM public key (-----BEGIN PUBLIC KEY-----). The configured value is not shown.`, + ); + } + let key: KeyObject; + try { + key = createPublicKey(pem); + } catch { + throw new Error(`PROOF_VERIFY_PUBLIC_KEYS ${label} could not be parsed as a public key. The configured value is not shown.`); + } + if (key.asymmetricKeyType !== "ed25519") { + throw new Error( + `PROOF_VERIFY_PUBLIC_KEYS ${label} must be an Ed25519 key, but it is ${key.asymmetricKeyType ?? "an unknown type"}.`, + ); + } + if (production && proofKeyFingerprint(key) === DEV_PROOF_KEY_FINGERPRINT) { + throw new Error( + `PROOF_VERIFY_PUBLIC_KEYS ${label} is the development key committed to this repository, whose private half is public.`, + ); + } + return key; + }); +} + let privateKey: KeyObject | undefined; let publicKey: KeyObject | undefined; @@ -112,6 +155,7 @@ export function assertProofSigningKey(): { fingerprint: string; dev: boolean } { privateKey = undefined; publicKey = undefined; const { pub } = loadKeys(); + proofVerifyPublicKeys(env.PROOF_VERIFY_PUBLIC_KEYS, env.NODE_ENV === "production"); const fingerprint = proofKeyFingerprint(pub); return { fingerprint, dev: fingerprint === DEV_PROOF_KEY_FINGERPRINT }; } @@ -152,13 +196,24 @@ export function signProof(bundle: object): ProofSignature { return { signature, public_key: proofPublicKeyPem(), algorithm: "ed25519" }; } -/** Verify a bundle+signature against the SERVER's key (not the bundle's own - * public_key) — so a forged bundle signed with someone else's key fails. */ +/** Verify against the current public key, then each PROOF_VERIFY_PUBLIC_KEYS entry. + * The bundle's own public_key is ignored, so a forged key in the bundle cannot pass. */ export function verifyProof(bundle: object, signatureB64: string): boolean { + const keys = [loadKeys().pub, ...proofVerifyPublicKeys(env.PROOF_VERIFY_PUBLIC_KEYS, env.NODE_ENV === "production")]; + let data: Buffer; + let signature: Buffer; try { - const data = Buffer.from(canonicalize(bundle)); - return verify(null, data, loadKeys().pub, Buffer.from(signatureB64, "base64")); + data = Buffer.from(canonicalize(bundle)); + signature = Buffer.from(signatureB64, "base64"); } catch { return false; } + for (const key of keys) { + try { + if (verify(null, data, key, signature)) return true; + } catch { + continue; + } + } + return false; } diff --git a/packages/db/package.json b/packages/db/package.json index 530d084..1558239 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -5,7 +5,8 @@ "type": "module", "exports": { ".": "./src/index.ts", - "./schema": "./src/schema.ts" + "./schema": "./src/schema.ts", + "./pool-default": "./src/pool-default.ts" }, "scripts": { "generate": "drizzle-kit generate", diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index a4e2a78..678a763 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -2,8 +2,10 @@ import { drizzle } from "drizzle-orm/postgres-js"; import postgres from "postgres"; import { env } from "@rootmail/core"; import * as schema from "./schema"; +import { dbPoolOptions } from "./pool"; +import { sealDbPoolDefault } from "./pool-default"; -const client = postgres(env.DATABASE_URL, { max: 10 }); +const client = postgres(env.DATABASE_URL, dbPoolOptions(sealDbPoolDefault())); export const db = drizzle(client, { schema }); export const sql = client; diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index add1741..782c161 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -1,4 +1,6 @@ export * from "./client"; +export * from "./pool"; +export { configureDbPool, configuredDbPoolDefault, UNCONFIGURED_DB_POOL_MAX } from "./pool-default"; export * from "./schema"; export * from "./conversations"; export * from "./sequence-triggers"; diff --git a/packages/db/src/pool-default.ts b/packages/db/src/pool-default.ts new file mode 100644 index 0000000..c50c0db --- /dev/null +++ b/packages/db/src/pool-default.ts @@ -0,0 +1,24 @@ +export const UNCONFIGURED_DB_POOL_MAX = 10; + +let configuredDefault: number | undefined; +let sealed = false; + +export function configureDbPool(defaultMax: number): void { + if (!Number.isInteger(defaultMax) || defaultMax < 1) { + throw new Error("Database pool default must be a positive integer"); + } + if (configuredDefault === defaultMax) return; + if (sealed || configuredDefault !== undefined) { + throw new Error("Database pool default is already set"); + } + configuredDefault = defaultMax; +} + +export function configuredDbPoolDefault(): number | undefined { + return configuredDefault; +} + +export function sealDbPoolDefault(): number { + sealed = true; + return configuredDefault ?? UNCONFIGURED_DB_POOL_MAX; +} diff --git a/packages/db/src/pool.test.ts b/packages/db/src/pool.test.ts new file mode 100644 index 0000000..4ecbf09 --- /dev/null +++ b/packages/db/src/pool.test.ts @@ -0,0 +1,80 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createRequire } from "node:module"; +import { describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; +import { dbPoolConfig } from "./pool"; + +const packageDir = fileURLToPath(new URL("..", import.meta.url)); + +function tsxImport(): string { + const require = createRequire(import.meta.url); + try { + return require.resolve("tsx"); + } catch { + return createRequire(fileURLToPath(new URL("../../../package.json", import.meta.url))).resolve("tsx"); + } +} + +function run(script: string, dbPoolMax: string): { status: number | null; output: string } { + const env = { ...process.env, DB_POOL_MAX: dbPoolMax }; + const result = spawnSync(process.execPath, ["--import", tsxImport(), "--input-type=module", "-e", script], { + cwd: packageDir, + env, + encoding: "utf8", + timeout: 60_000, + }); + return { status: result.status, output: `${result.stdout ?? ""}\n${result.stderr ?? ""}` }; +} + +describe("database pool options", () => { + it("uses the caller's default unless DB_POOL_MAX is set", () => { + assert.deepEqual(dbPoolConfig(5, undefined), { max: 5, idle_timeout: 20, max_lifetime: 1800 }); + assert.deepEqual(dbPoolConfig(3, undefined), { max: 3, idle_timeout: 20, max_lifetime: 1800 }); + assert.equal(dbPoolConfig(5, 2).max, 2); + assert.equal(dbPoolConfig(3, 9).max, 9); + assert.equal(dbPoolConfig(10, undefined).max, 10); + assert.throws(() => dbPoolConfig(0, undefined), /Database pool default must be a positive integer/); + assert.throws(() => dbPoolConfig(5, 0), /DB_POOL_MAX must be a positive integer/); + }); + + it("opens an unconfigured client at max 10 with the idle and lifetime limits", () => { + const result = run( + `import { configuredDbPoolDefault } from "./src/pool-default.ts"; + const { closeDb, sql } = await import("./src/client.ts"); + console.log([String(configuredDbPoolDefault()), sql.options.max, sql.options.idle_timeout, sql.options.max_lifetime].join(",")); + await closeDb();`, + "", + ); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /undefined,10,20,1800/); + }); + + it("opens with DB_POOL_MAX instead of the default the caller passed", () => { + const result = run( + `import { configureDbPool } from "./src/pool-default.ts"; + configureDbPool(5); + const { closeDb, sql } = await import("./src/client.ts"); + console.log([sql.options.max, sql.options.idle_timeout, sql.options.max_lifetime].join(",")); + await closeDb();`, + "4", + ); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /4,20,1800/); + }); + + it("rejects a second default and a non-positive default before the pool opens", () => { + const result = run( + `import { configureDbPool } from "./src/pool-default.ts"; + configureDbPool(5); + configureDbPool(5); + let saw = ""; + try { configureDbPool(3); } catch (err) { saw += (err instanceof Error ? err.message : ""); } + try { configureDbPool(0); } catch (err) { saw += "|" + (err instanceof Error ? err.message : ""); } + console.log(saw);`, + "", + ); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /Database pool default is already set\|Database pool default must be a positive integer/); + }); +}); diff --git a/packages/db/src/pool.ts b/packages/db/src/pool.ts new file mode 100644 index 0000000..b2e00dc --- /dev/null +++ b/packages/db/src/pool.ts @@ -0,0 +1,30 @@ +import { env } from "@rootmail/core"; + +export const DB_POOL_IDLE_TIMEOUT_SECONDS = 20; +export const DB_POOL_MAX_LIFETIME_SECONDS = 1800; + +export interface DbPoolOptions { + max: number; + idle_timeout: number; + max_lifetime: number; +} + +export function dbPoolConfig(defaultMax: number, configuredMax: number | undefined): DbPoolOptions { + const max = configuredMax ?? defaultMax; + if (!Number.isInteger(max) || max < 1) { + throw new Error( + configuredMax === undefined + ? "Database pool default must be a positive integer" + : `DB_POOL_MAX must be a positive integer, got ${String(configuredMax)}`, + ); + } + return { + max, + idle_timeout: DB_POOL_IDLE_TIMEOUT_SECONDS, + max_lifetime: DB_POOL_MAX_LIFETIME_SECONDS, + }; +} + +export function dbPoolOptions(defaultMax: number): DbPoolOptions { + return dbPoolConfig(defaultMax, env.DB_POOL_MAX); +}