Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ REDIS_PORT=6379
# Postgres (matches docker-compose.yml). For a hosted DB (e.g. RDS):
# DATABASE_URL=postgres://<user>:<password>@<endpoint>:5432/<db>?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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion DEPLOY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
51 changes: 51 additions & 0 deletions apps/api/src/db-pool.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});
5 changes: 5 additions & 0 deletions apps/api/src/db-pool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { configureDbPool } from "@rootmail/db/pool-default";

export const API_DB_POOL_DEFAULT = 5;

configureDbPool(API_DB_POOL_DEFAULT);
1 change: 1 addition & 0 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import "./db-pool";
import { env } from "@rootmail/core";
import { closeDb, ensureBetaInviteAutomation, ensureInternalAccount } from "@rootmail/db";
import { betaInviteRequired } from "./lib/beta";
Expand Down
4 changes: 2 additions & 2 deletions apps/api/src/routes/proof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const verifyBody = z.object({
});

export async function proofRoutes(app: FastifyInstance): Promise<void> {
// 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) };
Expand Down
54 changes: 54 additions & 0 deletions apps/worker/src/db-pool.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});
5 changes: 5 additions & 0 deletions apps/worker/src/db-pool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { configureDbPool } from "@rootmail/db/pool-default";

export const WORKER_DB_POOL_DEFAULT = 3;

configureDbPool(WORKER_DB_POOL_DEFAULT);
1 change: 1 addition & 0 deletions apps/worker/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import "./db-pool";
import { type ConnectionOptions, Worker } from "bullmq";
import {
BULL_PREFIX,
Expand Down
75 changes: 75 additions & 0 deletions packages/core/src/db-pool.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
15 changes: 15 additions & 0 deletions packages/core/src/db-pool.ts
Original file line number Diff line number Diff line change
@@ -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;
}
16 changes: 14 additions & 2 deletions packages/core/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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". */
Expand Down
Loading
Loading