From 3ec5c015c9252be561da2c0aa0be7ea8649a0d1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 19 Nov 2026 01:56:20 +0000 Subject: [PATCH 01/19] feat(selfhost): celld build and deploy core, plaintext mode (L22b, WIP before L22a merges) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 20 +- apps/api/src/selfhost/build.ts | 23 + .../selfhost-create-account.test.ts | 256 +++++++++++ .../selfhost/presign-vars-resolver.test.ts | 54 +++ .../unit/selfhost/selfhost-build.test.ts | 51 +++ .../selfhost/selfhost-only-modules.test.ts | 66 +++ package.json | 4 + scripts/deploy/generate-keys.ts | 22 +- scripts/selfhost/account-sql.ts | 150 ++++++ scripts/selfhost/box-settings.test.ts | 205 +++++++++ scripts/selfhost/box-settings.ts | 287 ++++++++++++ scripts/selfhost/celld-adopt.test.ts | 232 ++++++++++ scripts/selfhost/celld-adopt.ts | 184 ++++++++ scripts/selfhost/celld-binary.ts | 100 ++++ scripts/selfhost/celld-config.test.ts | 259 +++++++++++ scripts/selfhost/celld-config.ts | 429 ++++++++++++++++++ scripts/selfhost/celld-project.test.ts | 152 +++++++ scripts/selfhost/celld-project.ts | 159 +++++++ scripts/selfhost/create-account.test.ts | 187 ++++++++ scripts/selfhost/create-account.ts | 157 +++++++ scripts/selfhost/deploy-harness.ts | 56 +++ scripts/selfhost/deploy-health.test.ts | 68 +++ scripts/selfhost/deploy-plaintext.test.ts | 118 +++++ scripts/selfhost/deploy-steps.ts | 148 ++++++ scripts/selfhost/deploy.ts | 354 +++++++++++++++ .../selfhost/inbound-mail-settings.test.ts | 36 ++ scripts/selfhost/inbound-mail-settings.ts | 32 ++ scripts/selfhost/mail-settings.test.ts | 229 ++++++++++ scripts/selfhost/mail-settings.ts | 230 ++++++++++ scripts/selfhost/platform-keys.ts | 142 ++++++ scripts/selfhost/secret-files.test.ts | 164 +++++++ scripts/selfhost/secret-files.ts | 168 +++++++ scripts/selfhost/tsconfig.json | 6 + scripts/selfhost/upgrade-lib.ts | 251 ++++++++++ scripts/selfhost/upgrade.test.ts | 207 +++++++++ scripts/selfhost/upgrade.ts | 40 ++ scripts/selfhost/versions.test.ts | 17 + scripts/selfhost/versions.ts | 17 + scripts/selfhost/vitest.config.ts | 9 + scripts/selfhost/vm-agent-artifacts.test.ts | 113 +++++ scripts/selfhost/vm-agent-artifacts.ts | 274 +++++++++++ 41 files changed, 5665 insertions(+), 11 deletions(-) create mode 100644 apps/api/src/selfhost/build.ts create mode 100644 apps/api/tests/integration/selfhost-create-account.test.ts create mode 100644 apps/api/tests/unit/selfhost/presign-vars-resolver.test.ts create mode 100644 apps/api/tests/unit/selfhost/selfhost-build.test.ts create mode 100644 apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts create mode 100644 scripts/selfhost/account-sql.ts create mode 100644 scripts/selfhost/box-settings.test.ts create mode 100644 scripts/selfhost/box-settings.ts create mode 100644 scripts/selfhost/celld-adopt.test.ts create mode 100644 scripts/selfhost/celld-adopt.ts create mode 100644 scripts/selfhost/celld-binary.ts create mode 100644 scripts/selfhost/celld-config.test.ts create mode 100644 scripts/selfhost/celld-config.ts create mode 100644 scripts/selfhost/celld-project.test.ts create mode 100644 scripts/selfhost/celld-project.ts create mode 100644 scripts/selfhost/create-account.test.ts create mode 100644 scripts/selfhost/create-account.ts create mode 100644 scripts/selfhost/deploy-harness.ts create mode 100644 scripts/selfhost/deploy-health.test.ts create mode 100644 scripts/selfhost/deploy-plaintext.test.ts create mode 100644 scripts/selfhost/deploy-steps.ts create mode 100644 scripts/selfhost/deploy.ts create mode 100644 scripts/selfhost/inbound-mail-settings.test.ts create mode 100644 scripts/selfhost/inbound-mail-settings.ts create mode 100644 scripts/selfhost/mail-settings.test.ts create mode 100644 scripts/selfhost/mail-settings.ts create mode 100644 scripts/selfhost/platform-keys.ts create mode 100644 scripts/selfhost/secret-files.test.ts create mode 100644 scripts/selfhost/secret-files.ts create mode 100644 scripts/selfhost/tsconfig.json create mode 100644 scripts/selfhost/upgrade-lib.ts create mode 100644 scripts/selfhost/upgrade.test.ts create mode 100644 scripts/selfhost/upgrade.ts create mode 100644 scripts/selfhost/versions.test.ts create mode 100644 scripts/selfhost/versions.ts create mode 100644 scripts/selfhost/vitest.config.ts create mode 100644 scripts/selfhost/vm-agent-artifacts.test.ts create mode 100644 scripts/selfhost/vm-agent-artifacts.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 576d292c70..81468f3315 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,9 +133,8 @@ jobs: - 'scripts/deploy/deploy-signing-keys.ts' - 'scripts/deploy/types.ts' - 'scripts/deploy/vapid-keys.ts' - - 'scripts/selfhost/observability-migrations.ts' - - 'scripts/selfhost/reverse-tunnel-migrations.ts' - - 'scripts/selfhost/selfhost-migrations.ts' + # Self-host build tests import the celld generator, presign vars and account SQL. + - 'scripts/selfhost/**' # selfhost-inbound-email.test.ts builds this receiver (Self-host Email job only). - 'deploy/selfhost/sam-mx/**' - 'scripts/quality/node-pool-boundary.ts' @@ -235,6 +234,12 @@ jobs: - 'apps/api/scripts/**' - 'apps/api/container-entrypoints/**' - 'scripts/deploy/**' + # Self-hosted (celld) packaging: config generator, deploy, upgrade, create-account. + - 'scripts/selfhost/**' + # ...and what its tests read outside it: the self-host migration projection and the + # SMTP settings parser. + - 'apps/api/src/selfhost/**' + - 'packages/agent-email/src/smtp-config.ts' # The generated Worker config is built from wrangler.toml, so its text-binding # guard and effective-config tests must run when only wrangler.toml changes. - 'apps/api/wrangler.toml' @@ -853,7 +858,9 @@ jobs: run: pnpm quality:file-sizes - name: Type check deployment scripts - run: npx tsc --project scripts/deploy/tsconfig.json --noEmit + run: | + npx tsc --project scripts/deploy/tsconfig.json --noEmit + npx tsc --project scripts/selfhost/tsconfig.json --noEmit - name: Validate script syntax run: | @@ -867,6 +874,11 @@ jobs: - name: Run deploy and quality script tests run: pnpm quality:scripts:test + # celld wrangler.json generator, plaintext deploy (--init/--dry-run), upgrade, root-only + # secret files, pinned versions. No Docker, celld or frp: those run on a box. + - name: Run self-host packaging tests + run: pnpm selfhost:test + - name: Verify installer engine, runtime integrity and bounded proof contracts run: | pnpm exec vitest run --config scripts/deploy/installer-engine.vitest.config.ts diff --git a/apps/api/src/selfhost/build.ts b/apps/api/src/selfhost/build.ts new file mode 100644 index 0000000000..bd9f7c045e --- /dev/null +++ b/apps/api/src/selfhost/build.ts @@ -0,0 +1,23 @@ +/** + * What the self-host (celld) build adds to the shared Worker entry, applied once by the generated + * celld entry (`scripts/selfhost/celld-project.ts`) before any request. `apps/api/src/index.ts` + * never imports this module, so the Cloudflare bundle carries none of it + * (tests/unit/selfhost/reverse-tunnel-placement.test.ts). + * + * - speech-to-text and read-aloud through admin-configured endpoints (`speech/`, L14); + * - product analytics in OBSERVABILITY_DATABASE when ANALYTICS_SINK="d1" (`analytics/`, L20), + * with its `analytics.d1.*` retention settings; + * - the reverse-tunnel transport, gateway routes and lease sweep (`reverse-tunnel/entry.ts`, + * L17b), with the shared cloud-init generator as the frpc boot renderer. + */ +import { generateCloudInit } from '@simple-agent-manager/cloud-init'; + +import { installAnalyticsD1Sink } from './analytics'; +import { type SharedWorkerEntry, withReverseTunnel } from './reverse-tunnel/entry'; +import { installSpeechEndpoints } from './speech'; + +export function withSelfHostBuild(worker: T): T { + installSpeechEndpoints(); + installAnalyticsD1Sink(); + return withReverseTunnel(worker, generateCloudInit); +} diff --git a/apps/api/tests/integration/selfhost-create-account.test.ts b/apps/api/tests/integration/selfhost-create-account.test.ts new file mode 100644 index 0000000000..519387970f --- /dev/null +++ b/apps/api/tests/integration/selfhost-create-account.test.ts @@ -0,0 +1,256 @@ +/** + * `pnpm selfhost:create-account` (scripts/selfhost/account-sql.ts), end to end: its SQL runs on a + * real SQL engine with the full schema and the migration-seeded sentinel user, then the account + * signs in through the production `/api/auth` routes with a code delivered over SMTP. Proves the + * command writes the rows BetterAuth's email sign-in reads, and the sentinel rules. + */ +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + createAccountSql, + generateAccountId, + normalizeAccountEmail, +} from '../../../../scripts/selfhost/account-sql'; +import * as schema from '../../src/db/schema'; +import type { Env } from '../../src/env'; +import { handleAppError } from '../../src/middleware/app-error-handler'; +import { authRoutes } from '../../src/routes/auth'; +import { __resetPlatformConfigCacheForTest } from '../../src/services/platform-config'; +import { type FakeSmtpServer, startFakeSmtpServer } from '../helpers/fake-smtp-server'; +import { createAllSchemaTables, createMemoryKv, createSqliteD1 } from '../helpers/sqlite-d1'; + +const API_ORIGIN = 'https://api.example.com'; +const APP_ORIGIN = 'https://app.example.com'; + +interface Row { + id: string; + email: string; + role: string; + status: string; + emailVerified: number; + activeSuperadmins: number; +} + +describe('selfhost create-account SQL', () => { + let sqlite: Database.Database; + let smtp: FakeSmtpServer; + let env: Env; + const app = new Hono<{ Bindings: Env }>(); + app.onError(handleAppError); + app.route('/api/auth', authRoutes); + + /** Runs the command's batch the way `celld d1 execute` does; returns the report rows. */ + function runCommand(email: string, superadmin = false): Row[] { + const sql = createAccountSql({ + email: normalizeAccountEmail(email), + superadmin, + id: generateAccountId(), + nowMs: Date.now(), + }); + let rows: Row[] = []; + for (const statement of sql.split(';\n')) { + const prepared = sqlite.prepare(statement.replace(/;$/, '')); + if (prepared.reader) rows = prepared.all() as Row[]; + else prepared.run(); + } + return rows; + } + + function realUsers() { + return sqlite + .prepare(`SELECT email, role, status FROM users WHERE status != 'system' ORDER BY email`) + .all(); + } + + beforeEach(async () => { + sqlite = new Database(':memory:'); + createAllSchemaTables(sqlite, schema); + sqlite + .prepare( + `INSERT INTO users (id, email, email_verified, name, role, status, created_at, updated_at) + VALUES ('system_anonymous_trials', 'system@internal', 0, 'System', 'superadmin', 'system', 0, 0)` + ) + .run(); + smtp = await startFakeSmtpServer({ mode: 'plain' }); + env = { + DATABASE: createSqliteD1(sqlite), + KV: createMemoryKv(), + BASE_DOMAIN: 'example.com', + ENCRYPTION_KEY: 'test-encryption-key', + SMTP_HOST: '127.0.0.1', + SMTP_PORT: String(smtp.port), + SMTP_TLS: 'none', + SMTP_FROM: 'sign-in@example.com', + } as Env; + __resetPlatformConfigCacheForTest(); + }); + + afterEach(async () => { + sqlite.close(); + await smtp.close(); + }); + + async function signInByEmail(email: string): Promise | null> { + const background: Promise[] = []; + const executionCtx = { + waitUntil: (promise: Promise) => background.push(promise), + passThroughOnException: () => undefined, + props: {}, + } as unknown as ExecutionContext; + await app.request( + `${API_ORIGIN}/api/auth/email-otp/send-verification-otp`, + { + method: 'POST', + headers: { 'content-type': 'application/json', origin: APP_ORIGIN }, + body: JSON.stringify({ email, type: 'sign-in' }), + }, + env, + executionCtx + ); + await Promise.all(background); + const message = smtp.messages.findLast((sent) => sent.to.includes(email)); + if (!message) return null; + const body = message.data.split('\r\n\r\n').slice(1).join('\n'); + const otp = /\b(\d{6})\b/.exec(body)?.[1] ?? ''; + const signIn = await app.request( + `${API_ORIGIN}/api/auth/sign-in/email-otp`, + { + method: 'POST', + headers: { 'content-type': 'application/json', origin: APP_ORIGIN }, + body: JSON.stringify({ email, otp }), + }, + env + ); + const cookie = signIn.headers + .getSetCookie() + .map((value) => value.split(';', 1)[0]) + .join('; '); + const me = await app.request(`${API_ORIGIN}/api/auth/me`, { headers: { cookie } }, env); + return me.ok ? ((await me.json()) as Record) : null; + } + + it('creates an account that signs in by email and wins the sole-user administrator election', async () => { + // Control: without the account, no code is sent and nothing is created. + expect(await signInByEmail('teammate@example.com')).toBeNull(); + expect(realUsers()).toEqual([]); + + const [row] = runCommand('Teammate@Example.com'); + expect(row).toMatchObject({ email: 'teammate@example.com', role: 'user', status: 'active' }); + expect(row?.id).toMatch(/^[A-Za-z0-9]{32}$/); + expect(await signInByEmail('teammate@example.com')).toMatchObject({ + id: row?.id, + email: 'teammate@example.com', + // Main's durable first-user election runs at sign-in, after the CLI wrote a plain user. + role: 'superadmin', + status: 'active', + }); + }); + + it('is idempotent and promotes only when asked', () => { + const [first] = runCommand('teammate@example.com'); + const [again] = runCommand('teammate@example.com'); + expect(again?.id).toBe(first?.id); + expect(again?.role).toBe('user'); + const [promoted] = runCommand('teammate@example.com', true); + expect(promoted).toMatchObject({ id: first?.id, role: 'superadmin', status: 'active' }); + expect(realUsers()).toHaveLength(1); + }); + + it('keeps an existing account as it is unless asked to promote it', () => { + sqlite + .prepare( + `INSERT INTO users (id, email, email_verified, name, role, status, created_at, updated_at) + VALUES ('github-user', 'dev@example.com', 1, 'Dev', 'user', 'suspended', 1, 1)` + ) + .run(); + expect(runCommand('dev@example.com')[0]).toMatchObject({ + id: 'github-user', + status: 'suspended', + }); + expect(runCommand('dev@example.com', true)[0]).toMatchObject({ + id: 'github-user', + role: 'superadmin', + // Promotion never lifts a suspension. + status: 'suspended', + }); + }); + + it('approves a pending account when promoting it', () => { + sqlite + .prepare( + `INSERT INTO users (id, email, email_verified, name, role, status, created_at, updated_at) + VALUES ('waiting', 'waiting@example.com', 1, 'Waiting', 'user', 'pending', 1, 1)` + ) + .run(); + expect(runCommand('waiting@example.com')[0]).toMatchObject({ status: 'pending' }); + expect(runCommand('waiting@example.com', true)[0]).toMatchObject({ + role: 'superadmin', + status: 'active', + }); + }); + + describe('with an installer owner (BOOTSTRAP_OWNER_EMAIL)', () => { + const OWNER = 'owner@example.com'; + beforeEach(() => { + env = { ...env, BOOTSTRAP_OWNER_EMAIL: OWNER } as Env; + }); + + it('admits a created teammate only once the owner exists, as the command warns', async () => { + runCommand('teammate@example.com'); + // The owner has not signed in: SAM admits no one else yet. + expect(await signInByEmail('teammate@example.com')).toBeNull(); + + // Owner path: creating the owner as superadmin establishes them... + runCommand(OWNER, true); + expect(await signInByEmail(OWNER)).toMatchObject({ email: OWNER, role: 'superadmin' }); + // ...and the teammate is admitted from then on. + expect(await signInByEmail('teammate@example.com')).toMatchObject({ + email: 'teammate@example.com', + role: 'user', + }); + }); + + it('lets the owner, created as a plain account, sign in and become the administrator', async () => { + runCommand(OWNER); + expect(await signInByEmail(OWNER)).toMatchObject({ + email: OWNER, + role: 'superadmin', + status: 'active', + }); + }); + }); + + it('never counts or touches the sentinel user', () => { + // The sentinel is seeded as a 'superadmin' here on purpose: only status excludes it. + expect(runCommand('first@example.com')[0]?.activeSuperadmins).toBe(0); + expect(runCommand('first@example.com', true)[0]?.activeSuperadmins).toBe(1); + expect( + sqlite.prepare(`SELECT status, role FROM users WHERE id = 'system_anonymous_trials'`).get() + ).toEqual({ status: 'system', role: 'superadmin' }); + }); + + it("reports no row for the real sentinel's address and writes nothing", () => { + sqlite + .prepare( + `INSERT INTO users (id, email, email_verified, name, role, status, created_at, updated_at) + VALUES ('sentinel-2', 'anonymous-trials@simple-agent-manager.internal', 0, 'S', 'user', 'system', 0, 0)` + ) + .run(); + // The address passes the pattern (migration 0043's sentinel), so only the SQL protects it. + expect(runCommand('anonymous-trials@simple-agent-manager.internal', true)).toEqual([]); + expect( + sqlite + .prepare(`SELECT id, role, status FROM users WHERE email LIKE 'anonymous-trials@%'`) + .all() + ).toEqual([{ id: 'sentinel-2', role: 'user', status: 'system' }]); + }); + + it.each(["x'@example.com", 'a@b', 'a b@example.com', 'system@internal', 'é@example.com'])( + 'refuses %s before building any SQL', + (email) => { + expect(() => normalizeAccountEmail(email)).toThrow('not an email address'); + } + ); +}); diff --git a/apps/api/tests/unit/selfhost/presign-vars-resolver.test.ts b/apps/api/tests/unit/selfhost/presign-vars-resolver.test.ts new file mode 100644 index 0000000000..59f0323263 --- /dev/null +++ b/apps/api/tests/unit/selfhost/presign-vars-resolver.test.ts @@ -0,0 +1,54 @@ +/** + * The self-host deploy writes the operator-store presign vars (scripts/selfhost/box-settings.ts + * `presignVars`); the Worker reads them through main's `resolveR2PresignConfig` (L20), which + * refuses an operator store without a signing region. Run the real producer into the real + * consumer so a box cannot deploy vars its own Worker turns into "presigning off". + */ +import { describe, expect, it } from 'vitest'; + +import { presignVars } from '../../../../../scripts/selfhost/box-settings'; +import { resolveR2PresignConfig } from '../../../src/services/r2-presign-config'; + +const credentials = { + R2_ACCESS_KEY_ID: 'scoped-key-id', + R2_SECRET_ACCESS_KEY: 'scoped-key-secret', +}; +type PresignEnv = Parameters[0]; + +describe('presignVars → resolveR2PresignConfig', () => { + it('yields an operator store the Worker accepts for a gs:// box', () => { + const vars = presignVars( + { CELLD_BUCKET: 'gs://my-bucket/celld/', R2_S3_ENDPOINT: 'https://storage.googleapis.com' }, + 'assets' + ); + expect(resolveR2PresignConfig({ ...vars, ...credentials } as PresignEnv)).toMatchObject({ + endpoint: 'https://storage.googleapis.com', + bucket: 'my-bucket', + keyPrefix: 'celld/r2/assets/', + region: 'auto', + }); + }); + + it('passes an s3:// store region through to the Worker', () => { + const vars = presignVars( + { + CELLD_BUCKET: 's3://celld-fleet', + R2_S3_ENDPOINT: 'https://s3.example.com', + R2_S3_REGION: 'us-east-1', + }, + 'assets' + ); + expect(resolveR2PresignConfig({ ...vars, ...credentials } as PresignEnv)?.region).toBe( + 'us-east-1' + ); + }); + + it('control: the same vars without the region leave presigning off in the Worker', () => { + const vars: Record = presignVars( + { CELLD_BUCKET: 'gs://my-bucket/celld/', R2_S3_ENDPOINT: 'https://storage.googleapis.com' }, + 'assets' + ); + delete vars.R2_S3_REGION; + expect(resolveR2PresignConfig({ ...vars, ...credentials } as PresignEnv)).toBeNull(); + }); +}); diff --git a/apps/api/tests/unit/selfhost/selfhost-build.test.ts b/apps/api/tests/unit/selfhost/selfhost-build.test.ts new file mode 100644 index 0000000000..04d027a55d --- /dev/null +++ b/apps/api/tests/unit/selfhost/selfhost-build.test.ts @@ -0,0 +1,51 @@ +/** + * The celld entry applies `withSelfHostBuild` (scripts/selfhost/celld-project.ts). It must install + * the L20 D1 analytics sink and its `analytics.d1.*` settings, or a box loses product analytics + * and their retention bound. Enters through the real build function, not the sink's own installer. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { withSelfHostBuild } from '../../../src/selfhost/build'; +import { + findAdminSetting, + resetInstalledAdminSettingDefinitionsForTests, +} from '../../../src/services/admin-settings-registry'; +import { + activeLocalAnalyticsSink, + resetLocalAnalyticsSinkExtensionForTests, +} from '../../../src/services/analytics-sink'; +import { resolvePlatformCapabilities } from '../../../src/services/platform-capabilities'; + +const shared = { fetch: vi.fn(), scheduled: vi.fn() }; +const boxEnv = { ANALYTICS_SINK: 'd1', OBSERVABILITY_DATABASE: {} } as unknown as Env; + +afterEach(() => { + resetLocalAnalyticsSinkExtensionForTests(); + resetInstalledAdminSettingDefinitionsForTests(); +}); + +describe('withSelfHostBuild', () => { + it('installs the D1 analytics sink and its retention settings', () => { + // Control: nothing is installed before the build runs, so a box would have no analytics. + expect(activeLocalAnalyticsSink(boxEnv)).toBeUndefined(); + expect(findAdminSetting('analytics.d1.retentionDays')).toBeUndefined(); + + withSelfHostBuild(shared); + + expect(activeLocalAnalyticsSink(boxEnv)?.table).toBe('analytics_events'); + expect(resolvePlatformCapabilities(boxEnv).analyticsQuery).toBe(true); + expect(findAdminSetting('analytics.d1.retentionDays')).toBeDefined(); + expect(findAdminSetting('analytics.d1.maxRows')).toBeDefined(); + // The branch's pre-L20 names are gone from every registry. + expect(findAdminSetting('operations.analyticsD1RetentionDays')).toBeUndefined(); + expect(findAdminSetting('operations.analyticsD1MaxRows')).toBeUndefined(); + }); + + it('leaves the sink inactive on an installation that does not switch it on', () => { + withSelfHostBuild(shared); + expect(activeLocalAnalyticsSink({ OBSERVABILITY_DATABASE: {} } as unknown as Env)).toBe( + undefined + ); + }); +}); diff --git a/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts new file mode 100644 index 0000000000..f426f64582 --- /dev/null +++ b/apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts @@ -0,0 +1,66 @@ +/** + * The Cloudflare build must not contain code only the self-host build needs (owner decision, + * November 14, 2026: two builds rather than dormant code in production). It runs with the API unit + * tests so any change under apps/api triggers it: an import added to any shared module could pull + * the self-host-only code back into the Cloudflare bundle. + * + * - The shared entry `apps/api/src/index.ts` (wrangler.toml's `main`) must not reach + * `SELFHOST_ONLY_PATHS`, `apps/api/src/selfhost/build.ts` included. + * - The generated celld entry (scripts/selfhost/celld-project.ts `renderCelldMain`) is what reaches + * them: it imports `selfhost/build.ts`, whose graph the walker must see, so this guard cannot + * pass because the walker went blind. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import * as TOML from '@iarna/toml'; +import { describe, expect, it } from 'vitest'; + +import type { WranglerToml } from '../../../../../scripts/deploy/types'; +import { renderCelldMain, SOURCE_LINK } from '../../../../../scripts/selfhost/celld-project'; +import { + API_SRC, + collectImportGraph, + REPO_ROOT, + selfhostOnlyFindings, +} from '../../helpers/selfhost-only-modules'; + +const SELFHOST_BUILD = 'apps/api/src/selfhost/build.ts'; + +/** The apps/api/src modules the generated celld entry imports, as absolute paths. */ +function celldEntryImports(): string[] { + const prefix = `./${SOURCE_LINK}/`; + return [...renderCelldMain().matchAll(/from '([^']+)'/g)] + .map((match) => match[1]!) + .filter((specifier) => specifier.startsWith(prefix)) + .map((specifier) => resolve(API_SRC, specifier.slice(prefix.length))); +} + +describe('self-host-only code stays out of the Cloudflare Worker', () => { + it('the shared entry reaches no self-host-only module or package', () => { + const toml = TOML.parse( + readFileSync(resolve(REPO_ROOT, 'apps/api/wrangler.toml'), 'utf8') + ) as unknown as WranglerToml; + expect(toml.main).toBe('src/index.ts'); + const graph = collectImportGraph(resolve(API_SRC, 'index.ts')); + // A walker that resolved nothing would pass the assertion below; the entry reaches well + // over a thousand files. + expect(graph.files.length).toBeGreaterThan(1000); + expect(graph.files).not.toContain(SELFHOST_BUILD); + expect(selfhostOnlyFindings(graph)).toEqual([]); + }); + + it('positive control: the celld entry reaches the self-host build and its modules', () => { + const imports = celldEntryImports(); + expect(imports).toContain(resolve(REPO_ROOT, SELFHOST_BUILD)); + const findings = imports.flatMap((entry) => selfhostOnlyFindings(collectImportGraph(entry))); + expect(findings).toEqual( + expect.arrayContaining([ + SELFHOST_BUILD, + 'apps/api/src/selfhost/analytics/index.ts', + 'apps/api/src/selfhost/speech/index.ts', + 'apps/api/src/selfhost/reverse-tunnel/entry.ts', + ]) + ); + }); +}); diff --git a/package.json b/package.json index 084c067118..97ad0ee0f9 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,10 @@ "db:migrate:local": "tsx scripts/deploy/run-migrations.ts --local", "setup:github": "tsx scripts/deploy/setup-github.ts", "setup:local": "tsx scripts/deploy/setup-local-dev.ts", + "selfhost:deploy": "tsx scripts/selfhost/deploy.ts", + "selfhost:create-account": "tsx scripts/selfhost/create-account.ts", + "selfhost:test": "vitest run --config scripts/selfhost/vitest.config.ts", + "selfhost:upgrade": "tsx scripts/selfhost/upgrade.ts", "quality:preflight": "tsx scripts/quality/check-preflight-evidence.ts", "test:acp-c2-remote-service": "node tests/fixtures/acp-c2-remote-service.test.mjs", "quality:wrangler-bindings": "tsx scripts/quality/check-wrangler-bindings.ts", diff --git a/scripts/deploy/generate-keys.ts b/scripts/deploy/generate-keys.ts index 0eb4b2ac10..c4b275d5db 100644 --- a/scripts/deploy/generate-keys.ts +++ b/scripts/deploy/generate-keys.ts @@ -15,15 +15,18 @@ */ import * as crypto from 'node:crypto'; +import { fileURLToPath } from 'node:url'; import { generateDeploySigningKeyPair } from './deploy-signing-keys'; import { deriveVapidKeyPairFromPem } from './vapid-keys'; -function generateEncryptionKey(): string { +/** 32 random bytes, base64. Same shape as the Pulumi-managed `encryption-key`. */ +export function generateEncryptionKey(): string { return crypto.randomBytes(32).toString('base64'); } -function generateKeyPair(): { publicKey: string; privateKey: string } { +/** RSA-2048 PEM pair for JWT signing. Same shape as the Pulumi-managed `jwt-signing-key`. */ +export function generateKeyPair(): { publicKey: string; privateKey: string } { const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, @@ -33,7 +36,8 @@ function generateKeyPair(): { publicKey: string; privateKey: string } { return { publicKey, privateKey }; } -function generateVapidKeyPair(): { publicKey: string; privateKey: string } { +/** Raw base64url P-256 VAPID pair, derived the same way the deploy pipeline derives it. */ +export function generateVapidKeyPair(): { publicKey: string; privateKey: string } { const { privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); return deriveVapidKeyPairFromPem(privateKey.export({ format: 'pem', type: 'pkcs8' }).toString()); } @@ -75,7 +79,11 @@ async function main(): Promise { console.log('---'); } -main().catch((error) => { - console.error('❌ Error:', error instanceof Error ? error.message : error); - process.exit(1); -}); +// Run only as a CLI, so other scripts (scripts/selfhost/platform-keys.ts) can import the +// generators without printing keys. +if (process.argv[1] === fileURLToPath(import.meta.url)) { + main().catch((error) => { + console.error('❌ Error:', error instanceof Error ? error.message : error); + process.exit(1); + }); +} diff --git a/scripts/selfhost/account-sql.ts b/scripts/selfhost/account-sql.ts new file mode 100644 index 0000000000..5c9defbd63 --- /dev/null +++ b/scripts/selfhost/account-sql.ts @@ -0,0 +1,150 @@ +/** + * SQL for `pnpm selfhost:create-account` (create-account.ts): an account in the `users` table, + * the table BetterAuth reads, so email sign-in (emailOTP) then works for the address. BetterAuth + * needs no `accounts` row for it: its email-code sign-in looks the user up by email + * (`findUserByEmail`) and creates a session. + * + * `celld d1 execute` takes SQL text, not bound parameters, so every value written here is + * generated or checked first: the email against a strict pattern with no quote characters, the id + * from a fixed alphabet. Nothing else from the operator reaches the SQL. + * + * Rules: + * - Idempotent: an existing account is never duplicated or overwritten. `--superadmin` promotes + * it to superadmin and approves it if it was pending, but never lifts a suspension: that stays + * an explicit admin decision in the app. + * - The operator vouches for the address, so a new row is `email_verified = 1` and `active`, + * whatever the signup approval mode says. + * - Internal sentinel rows (`status = 'system'`, e.g. `system_anonymous_trials`) are never + * matched, promoted or counted as an administrator (apps/api/.claude/rules/40). Their addresses + * can pass the email pattern: asking for one inserts nothing (the INSERT sees the row) and + * reports nothing (the report excludes it), so `parseAccountReport` finds no row and the + * command fails. The INSERT deliberately does not exclude them, which would duplicate the + * address. + */ +import { randomInt } from 'node:crypto'; + +/** Lower-case ASCII, no quotes or spaces, a dot in the domain. */ +const ACCOUNT_EMAIL = + /^[a-z0-9.!#$%&*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/; +const MAX_EMAIL_LENGTH = 254; +const ID_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; +/** BetterAuth's generated ids are 32 characters from the same alphabet. */ +const ID_LENGTH = 32; + +export function normalizeAccountEmail(raw: string): string { + const email = raw.trim().toLowerCase(); + if (email.length > MAX_EMAIL_LENGTH || !ACCOUNT_EMAIL.test(email)) { + throw new Error( + `"${raw}" is not an email address this command accepts (plain ASCII, no quotes)` + ); + } + return email; +} + +export function generateAccountId(): string { + let id = ''; + for (let i = 0; i < ID_LENGTH; i += 1) id += ID_ALPHABET[randomInt(ID_ALPHABET.length)]; + return id; +} + +export interface AccountPlan { + email: string; + superadmin: boolean; + id: string; + nowMs: number; + /** + * The installer's owner email (BOOTSTRAP_OWNER_EMAIL), when the box has one. Until that owner + * is established, SAM promotes them on their first sign-in only if no other superadmin exists + * (`bootstrapSessionAllowed` in apps/api/src/services/bootstrap-owner.ts) and admits no one + * else. So a superadmin for any other address, written first, would lock everyone out. + */ + bootstrapOwnerEmail?: string; +} + +/** `platform_settings` key apps/api/src/services/bootstrap-owner.ts writes once the owner exists. */ +export const OWNER_ESTABLISHED_SETTING = 'setup.bootstrapOwnerEstablished'; + +function assertSafe(plan: AccountPlan): void { + normalizeAccountEmail(plan.email); + if (plan.bootstrapOwnerEmail !== undefined) normalizeAccountEmail(plan.bootstrapOwnerEmail); + if (!new RegExp(`^[${ID_ALPHABET}]{${ID_LENGTH}}$`).test(plan.id)) + throw new Error('bad account id'); + if (!Number.isSafeInteger(plan.nowMs) || plan.nowMs <= 0) throw new Error('bad timestamp'); +} + +const MATCH = (email: string) => `lower(trim(email)) = '${email}' AND status != 'system'`; + +/** + * The statements, in order: create when absent, promote when asked, then report the account and + * whether the install has an administrator. Run as one batch. + */ +/** + * True when `--superadmin` for this address must wait for the bootstrap owner: there is an owner + * email, this is another address, and the owner is not established yet. + */ +export function superadminWaitsForOwner(plan: AccountPlan): boolean { + return Boolean( + plan.superadmin && plan.bootstrapOwnerEmail && plan.bootstrapOwnerEmail !== plan.email + ); +} + +/** + * SQL condition: the bootstrap owner is established, by the same two proofs + * `bootstrapOwnerEstablished` accepts (its marker, or the owner as a verified active superadmin). + */ +function ownerEstablishedSql(owner: string): string { + return `(EXISTS (SELECT 1 FROM platform_settings WHERE key = '${OWNER_ESTABLISHED_SETTING}') + OR EXISTS (SELECT 1 FROM users WHERE lower(trim(email)) = '${owner}' AND email_verified = 1 + AND role = 'superadmin' AND status = 'active'))`; +} + +export function createAccountSql(plan: AccountPlan): string { + assertSafe(plan); + const { email, id, nowMs } = plan; + const name = email.split('@')[0] ?? email; + const role = plan.superadmin ? 'superadmin' : 'user'; + // Checked in the same statements that write, so a concurrent sign-in cannot slip between a + // separate check and the write. When it fails nothing is written and the report shows it. + const ownerGuard = superadminWaitsForOwner(plan) + ? ` AND ${ownerEstablishedSql(plan.bootstrapOwnerEmail ?? '')}` + : ''; + const statements = [ + `INSERT INTO users (id, email, email_verified, name, role, status, created_at, updated_at) + SELECT '${id}', '${email}', 1, '${name}', '${role}', 'active', ${nowMs}, ${nowMs} + WHERE NOT EXISTS (SELECT 1 FROM users WHERE lower(trim(email)) = '${email}')${ownerGuard}`, + ...(plan.superadmin + ? [ + `UPDATE users SET role = 'superadmin', + status = CASE WHEN status = 'pending' THEN 'active' ELSE status END, + updated_at = ${nowMs} + WHERE ${MATCH(email)}${ownerGuard}`, + ] + : []), + `SELECT id, email, role, status, email_verified AS emailVerified, + (SELECT count(*) FROM users WHERE role = 'superadmin' AND status = 'active') AS activeSuperadmins + FROM users WHERE ${MATCH(email)}`, + ]; + return statements.map((statement) => `${statement.replace(/\s+/g, ' ').trim()};`).join('\n'); +} + +export interface AccountReport { + id: string; + role: string; + status: string; +} + +/** + * The account row from `celld d1 execute`'s table output: the line that starts with a generated + * id followed by exactly this address. Null when the report has no such row (nothing usable was + * written). Matching the whole row, not the address anywhere in the output, keeps an echoed SQL + * statement from passing for a result. + */ +export function parseAccountReport(output: string, email: string): AccountReport | null { + for (const line of output.split('\n')) { + const [id = '', address, role = '', status = ''] = line.trim().split(/\s+/); + if (/^[A-Za-z0-9]{1,64}$/.test(id) && address === email && role && status) { + return { id, role, status }; + } + } + return null; +} diff --git a/scripts/selfhost/box-settings.test.ts b/scripts/selfhost/box-settings.test.ts new file mode 100644 index 0000000000..0925b1f0a2 --- /dev/null +++ b/scripts/selfhost/box-settings.test.ts @@ -0,0 +1,205 @@ +import { describe, expect, it } from 'vitest'; + +import { + BOX_RESERVED_PORTS, + celldChildEnv, + gatewayEnvAction, + presignVars, + redactSecrets, + renderGatewayEnv, + resolveTunnelPortRange, + resolveTunnelSettings, + tunnelWorkerVars, +} from './box-settings.js'; +import { parseDotenv } from './secret-files.js'; + +const SECRET = 'ab'.repeat(32); + +describe('tunnel port range', () => { + it('defaults, and gives the Worker and frps the same values', () => { + const settings = resolveTunnelSettings({}); + expect(settings).toEqual({ + range: { start: 20000, end: 29999 }, + heartbeatTimeoutSeconds: 90, + portReuseMinAgeSeconds: null, + }); + const frps = parseDotenv(renderGatewayEnv(SECRET, settings), 'gateway.env'); + const worker = tunnelWorkerVars(settings); + for (const name of [ + 'REVERSE_TUNNEL_PORT_RANGE_START', + 'REVERSE_TUNNEL_PORT_RANGE_END', + 'REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS', + ]) { + expect(frps[name], name).toBeDefined(); + expect(frps[name], name).toBe(worker[name]); + } + expect(frps.REVERSE_TUNNEL_GATEWAY_SECRET).toBe(SECRET); + expect(worker.REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS).toBeUndefined(); + }); + + it('takes the box override and rejects bad ranges', () => { + const box = { + REVERSE_TUNNEL_PORT_RANGE_START: '30000', + REVERSE_TUNNEL_PORT_RANGE_END: '30099', + }; + expect(resolveTunnelPortRange(box)).toEqual({ start: 30000, end: 30099 }); + expect(() => resolveTunnelPortRange({ REVERSE_TUNNEL_PORT_RANGE_START: '80' })).toThrow(/1024/); + expect(() => + resolveTunnelPortRange({ + REVERSE_TUNNEL_PORT_RANGE_START: '25000', + REVERSE_TUNNEL_PORT_RANGE_END: '24000', + }) + ).toThrow(/above/); + }); + + it('enforces the same size cap as the Worker', () => { + const at = { REVERSE_TUNNEL_PORT_RANGE_START: '10000', REVERSE_TUNNEL_PORT_RANGE_END: '29999' }; + expect(resolveTunnelPortRange(at)).toEqual({ start: 10000, end: 29999 }); + expect(() => + resolveTunnelPortRange({ ...at, REVERSE_TUNNEL_PORT_RANGE_START: '9999' }) + ).toThrow(/at most 20000 ports/); + }); + + // Each box listener at its compose default, then moved into an otherwise valid range. + it.each(Object.entries(BOX_RESERVED_PORTS))( + 'fails the deploy when the range contains %s', + (name, fallback) => { + if (fallback >= 1024) { + expect(() => + resolveTunnelPortRange({ + REVERSE_TUNNEL_PORT_RANGE_START: String(fallback), + REVERSE_TUNNEL_PORT_RANGE_END: String(fallback), + }) + ).toThrow(new RegExp(`contains ${name} \\(${fallback}\\)`)); + } + expect(() => resolveTunnelPortRange({ [name]: '20500' })).toThrow( + new RegExp(`contains ${name} \\(20500\\)`) + ); + // Control: the same listener moved just outside the range is accepted. + expect(resolveTunnelPortRange({ [name]: '30000' })).toEqual({ start: 20000, end: 29999 }); + } + ); + + it('derives the reuse age floor from the heartbeat timeout frps gets', () => { + expect( + resolveTunnelSettings({ REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS: '120' }) + ).toMatchObject({ heartbeatTimeoutSeconds: 120, portReuseMinAgeSeconds: null }); + expect(() => resolveTunnelSettings({ REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS: '30' })).toThrow( + /between 60 and 3600/ + ); + const longer = resolveTunnelSettings({ REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS: '600' }); + expect(tunnelWorkerVars(longer).REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS).toBe('600'); + expect(() => + resolveTunnelSettings({ + REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS: '120', + REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS: '200', + }) + ).toThrow(/between 240 and/); + }); + + it('refuses a gateway secret that is not 32 bytes of hex', () => { + expect(() => renderGatewayEnv('short', resolveTunnelSettings({}))).toThrow(/32 bytes/); + }); +}); + +describe('celldChildEnv', () => { + it('passes only allowlisted host vars plus storage settings', () => { + const env = celldChildEnv( + { PATH: '/bin', HOME: '/h', GITHUB_TOKEN: 'leak', AWS_ACCESS_KEY_ID: 'host-key' }, + { CELLD_BUCKET: 's3://b', AWS_ACCESS_KEY_ID: 'box-key', SAM_DOMAIN: 'x.example' }, + '/esbuild' + ); + expect(env).toEqual({ + CELLD_ESBUILD: '/esbuild', + PATH: '/bin', + HOME: '/h', + CELLD_BUCKET: 's3://b', + AWS_ACCESS_KEY_ID: 'box-key', + }); + }); + + it('does not inherit host storage credentials the box did not set (gs:// uses ADC)', () => { + const env = celldChildEnv({ AWS_SECRET_ACCESS_KEY: 'host' }, { CELLD_BUCKET: 'gs://b' }, '/e'); + expect(env.AWS_SECRET_ACCESS_KEY).toBeUndefined(); + }); +}); + +describe('redactSecrets', () => { + it('removes secret values, including each line of a PEM, but not short flags', () => { + const pem = + '-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\n-----END PRIVATE KEY-----'; + const out = redactSecrets(`key=${SECRET} pem=${pem} flag=true`, [SECRET, pem, 'true']); + expect(out).not.toContain(SECRET); + expect(out).not.toContain('MIIEvQIBADANBgkqhkiG9w0BAQEFAASC'); + expect(out).toContain('flag=true'); + }); +}); + +describe('presignVars', () => { + it('derives the fleet bucket and the R2 key prefix celld uses', () => { + expect(presignVars({ CELLD_BUCKET: 's3://celld-fleet' }, 'assets')).toEqual({ + R2_S3_BUCKET: 'celld-fleet', + R2_S3_KEY_PREFIX: 'r2/assets/', + }); + expect( + presignVars( + { CELLD_BUCKET: 'gs://my-bucket/celld/', R2_S3_ENDPOINT: 'https://storage.googleapis.com' }, + 'assets' + ) + ).toEqual({ + R2_S3_BUCKET: 'my-bucket', + R2_S3_KEY_PREFIX: 'celld/r2/assets/', + R2_S3_ENDPOINT: 'https://storage.googleapis.com', + // The Worker refuses an operator store without a region; GCS signs with "auto". + R2_S3_REGION: 'auto', + }); + }); + + // The Worker side (main's resolveR2PresignConfig) is exercised against these vars in + // apps/api/tests/unit/selfhost/presign-vars-resolver.test.ts; importing the Worker's env types + // here would pull the whole API into this package's typecheck. + it('passes an explicit region through and requires one for an s3:// store', () => { + expect( + presignVars( + { + CELLD_BUCKET: 's3://celld-fleet', + R2_S3_ENDPOINT: 'https://s3.example.com', + R2_S3_REGION: 'us-east-1', + }, + 'assets' + ).R2_S3_REGION + ).toBe('us-east-1'); + expect(() => + presignVars( + { CELLD_BUCKET: 's3://celld-fleet', R2_S3_ENDPOINT: 'https://s3.example.com' }, + 'assets' + ) + ).toThrow(/R2_S3_REGION is required/); + }); + + it('gives Azure buckets no presign vars', () => { + expect(presignVars({ CELLD_BUCKET: 'az://container' }, 'assets')).toEqual({}); + }); +}); + +describe('gatewayEnvAction', () => { + const settings = resolveTunnelSettings({}); + const current = renderGatewayEnv(SECRET, settings); + const longer = renderGatewayEnv( + SECRET, + resolveTunnelSettings({ REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS: '120' }) + ); + + it('writes on --init and on a first run, without stopping', () => { + expect(gatewayEnvAction(null, current, false)).toBe('write'); + expect(gatewayEnvAction(current, longer, true)).toBe('write'); + }); + + it('stops a normal deploy when frps would still run the old values', () => { + expect(gatewayEnvAction(current, longer, false)).toBe('write-then-restart'); + }); + + it('control: an unchanged file lets the deploy continue', () => { + expect(gatewayEnvAction(current, current, false)).toBe('unchanged'); + }); +}); diff --git a/scripts/selfhost/box-settings.ts b/scripts/selfhost/box-settings.ts new file mode 100644 index 0000000000..43c13b0377 --- /dev/null +++ b/scripts/selfhost/box-settings.ts @@ -0,0 +1,287 @@ +/** + * Settings shared by more than one process on a celld box, resolved once by the deploy script + * so the Worker, frps and Caddy cannot disagree. + */ + +import { + DEFAULT_MAIL_COLLECTOR_SMTP_PORT, + DEFAULT_MAIL_COLLECTOR_UI_PORT, +} from './mail-settings.js'; + +/** + * Loopback ports frps may bind for node tunnels. The deploy script always passes the resolved + * range to BOTH the Worker (vars) and frps (gateway.env), so neither side's own default is ever + * relied on. Overridable per box with REVERSE_TUNNEL_PORT_RANGE_START/END in the compose .env. + */ +export const DEFAULT_REVERSE_TUNNEL_PORT_RANGE_START = 20000; +export const DEFAULT_REVERSE_TUNNEL_PORT_RANGE_END = 29999; +/** Same cap the Worker enforces (MAX_REVERSE_TUNNEL_PORT_RANGE_SIZE); a bigger range fails here. */ +export const MAX_REVERSE_TUNNEL_PORT_RANGE_SIZE = 20000; +/** frps heartbeatTimeout; same default and bounds as the Worker (apps/api/src/selfhost/reverse-tunnel/config.ts). */ +export const DEFAULT_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = 90; +export const MIN_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = 60; +export const MAX_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS = 3600; +/** A released port is not reissued before this many heartbeat timeouts (Worker floor too). */ +export const REVERSE_TUNNEL_PORT_REUSE_HEARTBEAT_MULTIPLE = 2; + +/** + * Every other loopback/host listener on the box, with the default docker-compose.yml uses. A + * leased port that equals one of them would let a node's frpc bind (or the Worker and Caddy + * proxy to) celld's API, celld's UNAUTHENTICATED operator listener, frps itself, the bundled + * object store or Caddy. frps' allowPorts is the only fence, so the range must exclude them. + */ +export const BOX_RESERVED_PORTS: Readonly> = { + CELLD_PORT: 8080, + CELLD_INTERNAL_PORT: 7001, + FRPS_BIND_PORT: 7000, + OBJECTSTORE_PORT: 9000, + OBJECTSTORE_CONSOLE_PORT: 9001, + HTTP_PORT: 80, + HTTPS_PORT: 443, + // Reserved even with the collector off: a node holding its port would receive sign-in codes. + MAIL_COLLECTOR_SMTP_PORT: DEFAULT_MAIL_COLLECTOR_SMTP_PORT, + MAIL_COLLECTOR_UI_PORT: DEFAULT_MAIL_COLLECTOR_UI_PORT, +}; + +export interface PortRange { + start: number; + end: number; +} + +export interface TunnelSettings { + range: PortRange; + heartbeatTimeoutSeconds: number; + /** Only when the box overrides it; otherwise the Worker uses its default (2 x heartbeat). */ + portReuseMinAgeSeconds: number | null; +} + +function integer( + raw: string | undefined, + fallback: number, + name: string, + bounds: { min: number; max: number } +): number { + if (raw === undefined || raw === '') return fallback; + const value = Number(raw); + if (!/^\d+$/.test(raw) || value < bounds.min || value > bounds.max) { + throw new Error(`${name} must be an integer between ${bounds.min} and ${bounds.max}`); + } + return value; +} + +const PORT = { min: 1024, max: 65535 }; + +export function resolveTunnelPortRange(box: Readonly>): PortRange { + const start = integer( + box.REVERSE_TUNNEL_PORT_RANGE_START, + DEFAULT_REVERSE_TUNNEL_PORT_RANGE_START, + 'REVERSE_TUNNEL_PORT_RANGE_START', + PORT + ); + const end = integer( + box.REVERSE_TUNNEL_PORT_RANGE_END, + DEFAULT_REVERSE_TUNNEL_PORT_RANGE_END, + 'REVERSE_TUNNEL_PORT_RANGE_END', + PORT + ); + if (start > end) throw new Error('REVERSE_TUNNEL_PORT_RANGE_START is above _END'); + if (end - start + 1 > MAX_REVERSE_TUNNEL_PORT_RANGE_SIZE) { + throw new Error( + `REVERSE_TUNNEL_PORT_RANGE_START.._END may hold at most ${MAX_REVERSE_TUNNEL_PORT_RANGE_SIZE} ports (the Worker refuses larger ranges)` + ); + } + for (const [name, fallback] of Object.entries(BOX_RESERVED_PORTS)) { + const port = integer(box[name], fallback, name, { min: 1, max: 65535 }); + if (port >= start && port <= end) { + throw new Error( + `REVERSE_TUNNEL_PORT_RANGE ${start}-${end} contains ${name} (${port}); a node could bind it` + ); + } + } + return { start, end }; +} + +/** The range plus the heartbeat timeout frps enforces and the port-reuse age derived from it. */ +export function resolveTunnelSettings(box: Readonly>): TunnelSettings { + const heartbeatTimeoutSeconds = integer( + box.REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, + DEFAULT_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, + 'REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS', + { + min: MIN_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, + max: MAX_REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS, + } + ); + const floor = REVERSE_TUNNEL_PORT_REUSE_HEARTBEAT_MULTIPLE * heartbeatTimeoutSeconds; + const reuse = box.REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS; + const portReuseMinAgeSeconds = + reuse === undefined || reuse === '' + ? null + : integer(reuse, floor, 'REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS', { + min: floor, + max: 86_400, + }); + return { range: resolveTunnelPortRange(box), heartbeatTimeoutSeconds, portReuseMinAgeSeconds }; +} + +/** Worker vars carrying the tunnel settings (the same values gateway.env gives frps). */ +export function tunnelWorkerVars(settings: TunnelSettings): Record { + return { + REVERSE_TUNNEL_PORT_RANGE_START: String(settings.range.start), + REVERSE_TUNNEL_PORT_RANGE_END: String(settings.range.end), + REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS: String(settings.heartbeatTimeoutSeconds), + ...(settings.portReuseMinAgeSeconds === null + ? {} + : { REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS: String(settings.portReuseMinAgeSeconds) }), + }; +} + +/** + * Worker vars that point presigned uploads (attachments, snapshots, compose artifacts) at the + * box's own object store. celld keeps an R2 binding's objects at + * `/r2//` inside the fleet bucket, so the bucket and key prefix + * follow from CELLD_BUCKET and the R2 binding. The public endpoint (R2_S3_ENDPOINT) and its + * signing region (R2_S3_REGION; "auto" by default for a gs:// bucket, required for s3://) come + * from the compose .env and the prefix-scoped R2_ACCESS_KEY_ID / + * R2_SECRET_ACCESS_KEY from secrets.env. Without an endpoint the Worker leaves presigning off. + * Azure (az://) buckets have no S3 interface, so they get no presign vars. + */ +/** GCS's S3-compatible XML API signs with any region; "auto" is what its docs use. */ +const GCS_SIGNING_REGION = 'auto'; + +export function presignVars( + box: Readonly>, + r2BucketName: string +): Record { + const match = /^(?:(s3|gs|az):\/\/)?([^/]+)(?:\/(.*))?$/.exec(box.CELLD_BUCKET ?? ''); + if (!match) throw new Error('CELLD_BUCKET must be [s3://|gs://|az://]NAME[/PREFIX]'); + const [, scheme = 's3', bucket = '', fleetPrefix = ''] = match; + if (scheme === 'az') return {}; + const prefix = fleetPrefix.replace(/^\/+|\/+$/g, ''); + const vars: Record = { + R2_S3_BUCKET: bucket, + R2_S3_KEY_PREFIX: `${prefix ? `${prefix}/` : ''}r2/${r2BucketName}/`, + }; + if (box.R2_S3_ENDPOINT) { + vars.R2_S3_ENDPOINT = box.R2_S3_ENDPOINT; + // The Worker refuses an operator store without a signing region (r2-presign-config.ts). GCS + // accepts "auto"; an S3 store's region is the operator's to name (MinIO usually us-east-1). + const region = box.R2_S3_REGION?.trim() || (scheme === 'gs' ? GCS_SIGNING_REGION : ''); + if (!region) { + throw new Error( + "R2_S3_REGION is required with R2_S3_ENDPOINT for an s3:// CELLD_BUCKET (the store's SigV4 signing region)" + ); + } + vars.R2_S3_REGION = region; + } + return vars; +} + +/** + * The presign credential (R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY, a Worker secret) must be + * scoped to the R2 prefix. The fleet credential reads every Worker secret in the bucket's deploy + * manifests, so a Worker holding it would hold the whole install. Refuse the deploy if they match. + */ +export function assertPresignCredentialIsScoped( + box: Readonly>, + secrets: Readonly> +): void { + const pairs: Array<[string, string]> = [ + ['R2_ACCESS_KEY_ID', 'AWS_ACCESS_KEY_ID'], + ['R2_SECRET_ACCESS_KEY', 'AWS_SECRET_ACCESS_KEY'], + ]; + for (const [presign, fleet] of pairs) { + const presignValue = secrets[presign]?.trim(); + if (presignValue && presignValue === box[fleet]?.trim()) { + throw new Error( + `${presign} is the fleet bucket credential (${fleet}); use a credential scoped to the ` + + 'R2 prefix (deploy/selfhost/README.md, presigned uploads)' + ); + } + } +} + +/** The dotenv docker compose passes to frps and Caddy (`env_file`). */ +export function renderGatewayEnv(gatewaySecret: string, settings: TunnelSettings): string { + if (!/^[0-9a-f]{64}$/.test(gatewaySecret)) { + throw new Error('REVERSE_TUNNEL_GATEWAY_SECRET must be 32 bytes of lowercase hex'); + } + const frps = { + REVERSE_TUNNEL_GATEWAY_SECRET: gatewaySecret, + REVERSE_TUNNEL_PORT_RANGE_START: String(settings.range.start), + REVERSE_TUNNEL_PORT_RANGE_END: String(settings.range.end), + REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS: String(settings.heartbeatTimeoutSeconds), + }; + return Object.entries(frps) + .map(([name, value]) => `${name}=${value}\n`) + .join(''); +} + +/** + * What the deploy does with gateway.env. frps and Caddy read it only when they start, so when + * its content changes (heartbeat timeout, port range, secret) the Worker must not be updated in + * the same run: it would assume a heartbeat timeout (and so a port-reuse age) or a range that the + * running frps is not enforcing yet. A changed file outside `--init` therefore stops the deploy + * until the operator restarts the stack and runs it again. + */ +export function gatewayEnvAction( + existing: string | null, + next: string, + init: boolean +): 'unchanged' | 'write' | 'write-then-restart' { + if (existing === next) return 'unchanged'; + return init || existing === null ? 'write' : 'write-then-restart'; +} + +/** + * Host variables a celld child process may inherit; everything else is dropped. HOME and + * GOOGLE_APPLICATION_CREDENTIALS (a file path) let a gs:// bucket use Application Default + * Credentials when the deploy does not run on GCE. + */ +const INHERITED_ENV = [ + 'PATH', + 'HOME', + 'LANG', + 'TMPDIR', + 'RUST_LOG', + 'GOOGLE_APPLICATION_CREDENTIALS', +] as const; + +/** celld's storage settings, taken from the compose .env. */ +export const STORAGE_ENV_KEYS = [ + 'CELLD_BUCKET', + 'S3_ENDPOINT', + 'AWS_REGION', + 'AWS_ACCESS_KEY_ID', + 'AWS_SECRET_ACCESS_KEY', +] as const; + +/** + * The environment for `celld deploy` / `celld d1`: an allowlist of host variables plus the + * box's storage settings and the esbuild path. Unrelated host secrets never reach celld. + */ +export function celldChildEnv( + host: NodeJS.ProcessEnv, + box: Readonly>, + esbuild: string +): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { CELLD_ESBUILD: esbuild }; + for (const key of INHERITED_ENV) if (host[key]) env[key] = host[key]; + for (const key of STORAGE_ENV_KEYS) if (box[key]) env[key] = box[key]; + return env; +} + +/** Shortest value treated as a secret when scrubbing output; shorter ones are flags like "true". */ +const MIN_REDACTED_LENGTH = 8; + +/** Replaces every occurrence of each secret value (and each line of a multi-line one). */ +export function redactSecrets(text: string, secrets: readonly string[]): string { + const needles = secrets + .flatMap((secret) => [secret, ...secret.split('\n')]) + .map((needle) => needle.trim()) + .filter((needle) => needle.length >= MIN_REDACTED_LENGTH) + .sort((a, b) => b.length - a.length); + let out = text; + for (const needle of needles) out = out.split(needle).join(''); + return out; +} diff --git a/scripts/selfhost/celld-adopt.test.ts b/scripts/selfhost/celld-adopt.test.ts new file mode 100644 index 0000000000..4f2612f03a --- /dev/null +++ b/scripts/selfhost/celld-adopt.test.ts @@ -0,0 +1,232 @@ +/** + * `pnpm selfhost:deploy`'s post-deploy steps (celld-adopt.ts `verifyNewVersionServes`, called by + * deploy.ts right after `celld deploy`), against a small fake celld on loopback that behaves like + * celld 0.6.3: the API serves the ADOPTED version until `POST /reload` (or the 30 s poll, not + * modelled) switches it to the version the pointer names; a version that does not build is + * refused with 422 and the old one keeps serving. The fake answers only `POST /reload` on the + * internal listener, as celld does. (Node's fetch does not send a custom Host header, so the + * box's single Worker answers by path, which is what this fake models.) + * + * Box round R15 (G3): the deploy checked only /health, which the previous version also answers, + * so the agent sign-in route the new version added answered 404 for ~20 s after "deployed". + */ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + adoptNewDeployment, + AGENT_SIGN_IN_PATH, + checkAgentSignInRoute, + verifyNewVersionServes, +} from './celld-adopt'; +import { waitForHealth } from './deploy-steps'; + +interface Version { + id: string; + builds: boolean; + /** The Worker has a usable AGENT_SIGN_IN_TRUST, so the route answers instead of 404. */ + agentSignIn: boolean; +} + +const DOMAIN = 'sam.example.com'; +const ENV_KEYS = [ + 'SELFHOST_ADOPT_CHECK_WINDOW_MS', + 'SELFHOST_HEALTH_POLL_INTERVAL_MS', + 'SELFHOST_HEALTH_TIMEOUT_MS', +] as const; +const saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + +let internal: Server; +let api: Server; +let box: Record; +let serving: Version; +let pointer: Version; +let reloads: number; +let refuseReloads: number; +let reloadStatus: number | null; +let routeStatus: number | null; +/** Every request the fake celld answered, in order: what the deploy did, and when. */ +let events: string[]; + +async function listen(server: Server): Promise { + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + return String((server.address() as AddressInfo).port); +} + +/** What `celld deploy` does: write a new pointer. The node keeps serving the old version. */ +function celldDeploy(version: Version): void { + pointer = version; +} + +const verify = (agentSignInConfigured: boolean, log: string[] = []) => + verifyNewVersionServes( + box, + { celldPort: box.CELLD_PORT!, baseDomain: DOMAIN, agentSignInConfigured }, + (line) => log.push(line) + ); + +beforeEach(async () => { + reloads = 0; + refuseReloads = 0; + reloadStatus = null; + routeStatus = null; + events = []; + serving = { id: 'v1', builds: true, agentSignIn: false }; + pointer = serving; + internal = createServer((req, res) => { + if (req.method !== 'POST' || req.url !== '/reload') { + events.push(`internal ${req.method} ${req.url}`); + return void res.writeHead(404).end(); + } + reloads += 1; + if (reloads <= refuseReloads) { + req.socket.destroy(); + return; + } + if (reloadStatus !== null) return void res.writeHead(reloadStatus).end('{}'); + if (!pointer.builds) { + events.push(`reload failed ${pointer.id}`); + res + .writeHead(422, { 'content-type': 'application/json' }) + .end( + JSON.stringify({ ok: false, outcome: 'failed', version: pointer.id, error: 'syntax' }) + ); + return; + } + serving = pointer; + events.push(`reload ${serving.id}`); + res + .writeHead(200, { 'content-type': 'application/json' }) + .end(JSON.stringify({ ok: true, outcome: 'adopted', generation: 2, version: serving.id })); + }); + api = createServer((req, res) => { + if (req.url === '/health') { + events.push(`health ${serving.id}`); + return void res.writeHead(200).end('{"status":"healthy"}'); + } + if (req.url === AGENT_SIGN_IN_PATH && req.method === 'POST') { + events.push(`sign-in ${serving.id}`); + // The route steps aside (404) when the serving Worker has no usable trust. + const status = routeStatus ?? (serving.agentSignIn ? 400 : 404); + return void res.writeHead(status).end('{}'); + } + res.writeHead(404).end(); + }); + box = { + SAM_DOMAIN: DOMAIN, + CELLD_INTERNAL_PORT: await listen(internal), + CELLD_PORT: await listen(api), + }; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '2000'; + process.env.SELFHOST_HEALTH_POLL_INTERVAL_MS = '20'; + process.env.SELFHOST_HEALTH_TIMEOUT_MS = '2000'; +}); + +afterEach(async () => { + for (const k of ENV_KEYS) { + if (saved[k] === undefined) delete process.env[k]; + else process.env[k] = saved[k]; + } + for (const server of [internal, api]) { + server.closeAllConnections(); + await new Promise((done) => server.close(() => done())); + } +}); + +describe('after celld deploy (verifyNewVersionServes, G3)', () => { + it('adopts first, so health and the agent sign-in route are checked on the new version', async () => { + celldDeploy({ id: 'v2', builds: true, agentSignIn: true }); + const log: string[] = []; + await verify(true, log); + expect(events).toEqual(['reload v2', 'health v2', 'sign-in v2']); + expect(log).toEqual([ + 'celld adopted the new version: adopted version v2', + 'agent sign-in route answers on the new version', + ]); + }); + + it('does not probe the agent sign-in route when no trust is configured', async () => { + celldDeploy({ id: 'v2', builds: true, agentSignIn: false }); + await verify(false); + expect(events).toEqual(['reload v2', 'health v2']); + }); + + it('stops the deploy when the trust is configured but the new version has no usable trust', async () => { + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + celldDeploy({ id: 'v2', builds: true, agentSignIn: false }); + await expect(verify(true)).rejects.toThrow(/answers HTTP 404.*agent_sign_in\.config_invalid/); + expect(events.slice(0, 2)).toEqual(['reload v2', 'health v2']); + }); + + it('stops at once, before any check, when the new version does not build', async () => { + celldDeploy({ id: 'v2', builds: false, agentSignIn: true }); + await expect(verify(true)).rejects.toThrow( + /HTTP 422 version v2: syntax\)\. The previous version keeps serving\.$/ + ); + expect(events).toEqual(['reload failed v2']); + expect(serving.id).toBe('v1'); + }); + + it('without the adoption step (the R15 deploy), health passes on the old version and the route 404s', async () => { + // Control for the ordering above: the checks alone cannot tell the versions apart. + celldDeploy({ id: 'v2', builds: true, agentSignIn: true }); + await waitForHealth(box.CELLD_PORT!, DOMAIN); + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(checkAgentSignInRoute(box)).rejects.toThrow(/answers HTTP 404/); + expect(events[0]).toBe('health v1'); + }); +}); + +describe('adoptNewDeployment', () => { + it('rides out a refused reload while celld stalls', async () => { + refuseReloads = 2; + celldDeploy({ id: 'v2', builds: true, agentSignIn: false }); + expect(await adoptNewDeployment(box)).toBe('adopted version v2'); + expect(reloads).toBe(3); + }); + + it('retries a 500 until the window ends, then names celld’s poll', async () => { + reloadStatus = 500; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(adoptNewDeployment(box)).rejects.toThrow(/HTTP 500\).*CELLD_DEPLOY_POLL_S/); + expect(reloads).toBeGreaterThan(1); + }); + + it('names the celld version on a 404 (no /reload before 0.6.3)', async () => { + reloadStatus = 404; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '100'; + await expect(adoptNewDeployment(box)).rejects.toThrow(/celld 0\.6\.3 or later/); + }); + + it('fails after the window when celld never answers', async () => { + refuseReloads = Number.POSITIVE_INFINITY; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '200'; + await expect(adoptNewDeployment(box)).rejects.toThrow( + /celld did not adopt the deployment .*CELLD_DEPLOY_POLL_S/ + ); + expect(reloads).toBeGreaterThan(1); + }); +}); + +describe('checkAgentSignInRoute', () => { + it('retries a 404 and passes once the route appears within the window', async () => { + setTimeout(() => { + serving = { ...serving, agentSignIn: true }; + }, 120); + await checkAgentSignInRoute(box); + expect(events.filter((e) => e.startsWith('sign-in')).length).toBeGreaterThan(1); + }); + + it('does not count a 500 as present', async () => { + routeStatus = 500; + process.env.SELFHOST_ADOPT_CHECK_WINDOW_MS = '100'; + await expect(checkAgentSignInRoute(box)).rejects.toThrow(/answers HTTP 500/); + }); + + it.each([400, 401, 429])('counts %i as present (the route answered)', async (status) => { + routeStatus = status; + await checkAgentSignInRoute(box); + }); +}); diff --git a/scripts/selfhost/celld-adopt.ts b/scripts/selfhost/celld-adopt.ts new file mode 100644 index 0000000000..917b239ed4 --- /dev/null +++ b/scripts/selfhost/celld-adopt.ts @@ -0,0 +1,184 @@ +/** + * Making celld serve a version the deploy just wrote, and checking it. + * + * celld 0.6.3 nodes read `deploy/current.json` every `CELLD_DEPLOY_POLL_S` seconds (default 30) + * and adopt a new version in place; `POST /reload` on the internal listener adopts it at once + * (celld `docs/README.md`, "A running node does not restart for a new deployment"; + * `internal_reload` in `crates/celld/main.rs`: 200 `adopted`/`unchanged`, 422 `failed` when the + * version does not build, in which case the previous version keeps serving). + * + * Box round R15 (G3): `pnpm selfhost:deploy` did not ask, so its health check passed on the + * PREVIOUS version and "deployed" was printed while that version served for up to one poll + * interval. A deploy that added `AGENT_SIGN_IN_TRUST` answered 404 on the agent sign-in route for + * about 20 s. The deploy now asks celld to adopt before its health check (`adoptNewDeployment`) + * and checks the agent sign-in route when the trust is configured (`checkAgentSignInRoute`). + */ +import { intEnv, sleep, waitForHealth } from './deploy-steps.js'; + +/** + * How long a check after a deploy keeps trying. celld can stall for seconds while it adopts a + * version (6.5 s on sam-box in box round R11), and one refused fetch must not fail a deploy that + * would have succeeded a moment later. A version that is really broken still fails, after this + * window. Override with SELFHOST_ADOPT_CHECK_WINDOW_MS. + */ +export const DEFAULT_ADOPT_CHECK_WINDOW_MS = 30_000; +const DEFAULT_ADOPT_POLL_INTERVAL_MS = 2000; +const DEFAULT_RELOAD_REQUEST_TIMEOUT_MS = 60_000; +const DEFAULT_ROUTE_REQUEST_TIMEOUT_MS = 10_000; +/** The agent sign-in exchange route (apps/api/src/services/agent-sign-in/config.ts). */ +export const AGENT_SIGN_IN_PATH = '/api/auth/workload-identity-login'; +const MAX_DETAIL_CHARS = 300; + +type Box = Readonly>; + +export interface AdoptionResult { + /** celld serves the version `deploy/current.json` names. */ + adopted: boolean; + /** celld refused it because it did not build: retrying cannot help. */ + buildFailed: boolean; + detail: string; +} + +function windowDeadline(): number { + return Date.now() + intEnv('SELFHOST_ADOPT_CHECK_WINDOW_MS', DEFAULT_ADOPT_CHECK_WINDOW_MS); +} + +function pollInterval(): number { + return intEnv('SELFHOST_HEALTH_POLL_INTERVAL_MS', DEFAULT_ADOPT_POLL_INTERVAL_MS); +} + +function apiHeaders(box: Box): Record { + return { host: `api.${box.SAM_DOMAIN ?? ''}`, 'x-forwarded-proto': 'https' }; +} + +/** One `POST /reload` on celld's internal listener. Never throws. */ +export async function requestAdoption(box: Box): Promise { + const internal = box.CELLD_INTERNAL_PORT || '7001'; + const reload = await fetch(`http://127.0.0.1:${internal}/reload`, { + method: 'POST', + signal: AbortSignal.timeout(DEFAULT_RELOAD_REQUEST_TIMEOUT_MS), + }).catch((error: unknown) => error); + if (!(reload instanceof Response)) { + return { + adopted: false, + buildFailed: false, + detail: `celld did not adopt the deployment (${String(reload)})`, + }; + } + const body = (await reload.text().catch(() => '')).slice(0, 2000); + let parsed: Record = {}; + try { + const raw: unknown = JSON.parse(body); + if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) { + parsed = raw as Record; + } + } catch { + parsed = {}; + } + const version = typeof parsed.version === 'string' ? ` version ${parsed.version}` : ''; + if (reload.ok) { + const outcome = typeof parsed.outcome === 'string' ? parsed.outcome : 'adopted'; + return { adopted: true, buildFailed: false, detail: `${outcome}${version}` }; + } + const error = + typeof parsed.error === 'string' ? `: ${parsed.error.slice(0, MAX_DETAIL_CHARS)}` : ''; + // celld before 0.6.3 has no /reload; the deploy pins 0.6.3 (versions.ts CELLD_VERSION). + const tooOld = reload.status === 404 ? '; celld 0.6.3 or later is needed for /reload' : ''; + const buildFailed = reload.status === 422; + return { + adopted: false, + buildFailed, + detail: + `celld did not adopt the deployment (HTTP ${reload.status}${version}${error})${tooOld}` + + (buildFailed ? '. The previous version keeps serving' : ''), + }; +} + +/** + * Runs `attempt` until `done` accepts its result or the window would end, then returns the last + * result. Attempts are sequential on purpose: each is a retry of the one before. + */ +async function pollWithinWindow( + attempt: () => Promise, + done: (result: T) => boolean, + deadline: number +): Promise { + const result = await attempt(); + if (done(result) || Date.now() + pollInterval() >= deadline) return result; + await sleep(pollInterval()); + return pollWithinWindow(attempt, done, deadline); +} + +/** + * Asks celld to adopt the newest deployment now, retrying a refused or failed request within the + * window. Throws when the version did not build (celld keeps the previous one serving) or when + * celld never answered, so a deploy cannot report success while the old version serves. + */ +export async function adoptNewDeployment(box: Box): Promise { + const result = await pollWithinWindow( + () => requestAdoption(box), + (r) => r.adopted || r.buildFailed, + windowDeadline() + ); + if (result.adopted) return result.detail; + if (result.buildFailed) throw new Error(`${result.detail}.`); + throw new Error( + `${result.detail}. celld adopts it by itself within CELLD_DEPLOY_POLL_S (default 30 s); ` + + 'check docker compose ps and the celld log, then run pnpm selfhost:deploy again.' + ); +} + +/** One POST of an empty body to the agent sign-in route: present, or what answered instead. */ +async function probeAgentSignInRoute(box: Box): Promise<{ present: boolean; answer: string }> { + const url = `http://127.0.0.1:${box.CELLD_PORT || '8080'}${AGENT_SIGN_IN_PATH}`; + const response = await fetch(url, { + method: 'POST', + headers: { ...apiHeaders(box), 'content-type': 'application/json' }, + body: '{}', + signal: AbortSignal.timeout(DEFAULT_ROUTE_REQUEST_TIMEOUT_MS), + }).catch((error: unknown) => error); + if (!(response instanceof Response)) return { present: false, answer: String(response) }; + await response.arrayBuffer().catch(() => undefined); + return { + present: response.status !== 404 && response.status < 500, + answer: `HTTP ${response.status}`, + }; +} + +/** + * With `AGENT_SIGN_IN_TRUST` configured, the agent sign-in route must exist on the version that + * now serves. An empty body is refused with 400 before any token is looked at; 404 means the route + * stepped aside because the Worker has no usable trust (an unparseable value logs + * `agent_sign_in.config_invalid`). Retried within the window, then throws. + */ +export async function checkAgentSignInRoute(box: Box): Promise { + const probe = await pollWithinWindow( + () => probeAgentSignInRoute(box), + (r) => r.present, + windowDeadline() + ); + if (probe.present) return; + throw new Error( + `AGENT_SIGN_IN_TRUST is set in secrets.env but POST ${AGENT_SIGN_IN_PATH} answers ${probe.answer}: ` + + 'the Worker has no usable trust. Look for agent_sign_in.config_invalid in the celld log ' + + '(docker compose logs celld), fix the value and deploy again.' + ); +} + +/** + * What `pnpm selfhost:deploy` runs after `celld deploy`: celld adopts the new version, then the + * API answers `/health`, then (with `AGENT_SIGN_IN_TRUST` among the Worker's secrets) the agent + * sign-in route answers. In this order, so the checks reach the new version (box round R15, G3). + */ +export async function verifyNewVersionServes( + box: Box, + input: { celldPort: string; baseDomain: string; agentSignInConfigured: boolean }, + log: (message: string) => void +): Promise { + log(`celld adopted the new version: ${await adoptNewDeployment(box)}`); + await waitForHealth(input.celldPort, input.baseDomain); + if (input.agentSignInConfigured) { + await checkAgentSignInRoute(box); + log('agent sign-in route answers on the new version'); + } +} diff --git a/scripts/selfhost/celld-binary.ts b/scripts/selfhost/celld-binary.ts new file mode 100644 index 0000000000..a907f6004f --- /dev/null +++ b/scripts/selfhost/celld-binary.ts @@ -0,0 +1,100 @@ +/** + * Locate the tools `celld deploy` needs on the deploying machine: the pinned celld binary + * (downloaded and checksum-verified) and an esbuild executable. + */ + +import { createHash } from 'node:crypto'; +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { arch, platform } from 'node:os'; +import { dirname, join } from 'node:path'; +import { gunzipSync } from 'node:zlib'; + +import { CELLD_RELEASE_SHA256, CELLD_VERSION, DEFAULT_CELLD_RELEASE_BASE_URL } from './versions.js'; + +export function celldReleaseTarget(os = platform(), cpu = arch()): string { + const target = + os === 'linux' && cpu === 'x64' + ? 'x86_64-unknown-linux-gnu' + : os === 'linux' && cpu === 'arm64' + ? 'aarch64-unknown-linux-gnu' + : os === 'darwin' && cpu === 'arm64' + ? 'aarch64-apple-darwin' + : null; + if (!target || !CELLD_RELEASE_SHA256[target]) { + throw new Error( + `celld ${CELLD_VERSION} has no release for ${os}/${cpu}; set CELLD_BIN to a celld binary` + ); + } + return target; +} + +export function sha256Hex(bytes: Uint8Array): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +/** + * Returns a celld binary path: `CELLD_BIN` when set (unverified, and said so), otherwise the + * pinned release under `binDir`. The compressed asset is kept beside the binary; every run + * re-checks it against the pinned sha256 and the binary against its decompressed bytes, so a + * tampered cache is replaced rather than executed with the bucket credential. + */ +export async function ensureCelldBinary( + binDir: string, + env: NodeJS.ProcessEnv = process.env +): Promise { + if (env.CELLD_BIN) { + console.warn(`[selfhost] using CELLD_BIN=${env.CELLD_BIN} without checksum verification`); + return env.CELLD_BIN; + } + const target = celldReleaseTarget(); + const expected = CELLD_RELEASE_SHA256[target]; + const path = join(binDir, `celld-${CELLD_VERSION}`); + const gzPath = `${path}.gz`; + + if (existsSync(gzPath) && existsSync(path)) { + const gz = readFileSync(gzPath); + if (sha256Hex(gz) === expected && sha256Hex(gunzipSync(gz)) === sha256Hex(readFileSync(path))) { + return path; + } + console.warn(`[selfhost] cached celld in ${binDir} failed verification; downloading again`); + } + + const base = env.CELLD_RELEASE_BASE_URL || DEFAULT_CELLD_RELEASE_BASE_URL; + const url = `${base}/v${CELLD_VERSION}/celld-${target}.gz`; + const response = await fetch(url); + if (!response.ok) throw new Error(`downloading ${url}: HTTP ${response.status}`); + const gz = new Uint8Array(await response.arrayBuffer()); + const actual = sha256Hex(gz); + if (actual !== expected) throw new Error(`${url}: sha256 ${actual}, expected ${expected}`); + + mkdirSync(binDir, { recursive: true, mode: 0o700 }); + writeFileSync(`${gzPath}.download`, gz, { mode: 0o600 }); + renameSync(`${gzPath}.download`, gzPath); + const temp = `${path}.download`; + writeFileSync(temp, gunzipSync(gz), { mode: 0o700 }); + chmodSync(temp, 0o700); + renameSync(temp, path); + return path; +} + +/** + * An esbuild executable for celld's bundler: `CELLD_ESBUILD` when set, otherwise the esbuild + * wrangler depends on (the same toolchain that bundles the Worker for Cloudflare). + */ +export function resolveEsbuild(apiDir: string, env: NodeJS.ProcessEnv = process.env): string { + if (env.CELLD_ESBUILD) return env.CELLD_ESBUILD; + const fromApi = createRequire(join(apiDir, 'package.json')); + const fromWrangler = createRequire(fromApi.resolve('wrangler/package.json')); + const pkgPath = fromWrangler.resolve('esbuild/package.json'); + const pkg: unknown = JSON.parse(readFileSync(pkgPath, 'utf8')) as unknown; + const binField = typeof pkg === 'object' && pkg !== null && 'bin' in pkg ? pkg.bin : undefined; + const bin = + typeof binField === 'string' + ? binField + : typeof binField === 'object' && binField !== null && 'esbuild' in binField + ? String(binField.esbuild) + : undefined; + if (!bin) throw new Error(`${pkgPath} declares no esbuild binary; set CELLD_ESBUILD`); + return join(dirname(pkgPath), bin); +} diff --git a/scripts/selfhost/celld-config.test.ts b/scripts/selfhost/celld-config.test.ts new file mode 100644 index 0000000000..5b5b1a44a6 --- /dev/null +++ b/scripts/selfhost/celld-config.test.ts @@ -0,0 +1,259 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +import * as TOML from '@iarna/toml'; +import { describe, expect, it } from 'vitest'; + +import type { WranglerToml } from '../deploy/types.js'; +import { + assertOperatorSecretsAllowed, + buildCelldConfig, + SELFHOST_VAR_OVERRIDES, +} from './celld-config.js'; + +const WRANGLER_TOML = resolve(import.meta.dirname, '../../apps/api/wrangler.toml'); + +/** celld 0.6.x's accepted top-level keys (celld docs, configuration reference). */ +const CELLD_TOP_LEVEL_KEYS = new Set([ + 'name', + 'main', + 'no_bundle', + 'compatibility_date', + 'compatibility_flags', + 'durable_objects', + 'migrations', + 'assets', + 'services', + 'triggers', + 'vars', + 'd1_databases', + 'kv_namespaces', + 'queues', + 'workflows', + 'r2_buckets', + 'worker_loaders', + 'containers', + 'define', + 'rules', +]); + +function loadToml(): WranglerToml { + return TOML.parse(readFileSync(WRANGLER_TOML, 'utf8')) as WranglerToml; +} + +const options = { main: 'src/index.ts', baseDomain: 'sam.example.com' }; + +describe('buildCelldConfig against the real apps/api/wrangler.toml', () => { + const source = loadToml(); + const plan = buildCelldConfig(source, { ...options, assetsDirectory: 'web' }); + const { config } = plan; + + it('emits only keys celld accepts', () => { + for (const key of Object.keys(config)) expect(CELLD_TOP_LEVEL_KEYS.has(key)).toBe(true); + }); + + it('drops every Cloudflare-only key and reports why', () => { + for (const key of [ + 'port', + 'limits', + 'alias', + 'artifacts', + 'analytics_engine_datasets', + 'ai', + 'containers', + ]) { + expect(config).not.toHaveProperty(key); + expect(plan.report.some((line) => line.startsWith(`drop [${key}]`))).toBe(true); + } + }); + + it('runs no container and leaves SAM-native git off', () => { + expect(config).not.toHaveProperty('containers'); + // No Artifacts binding and no other backend registered: resolveArtifactsBackend is null. + expect(config.vars.ARTIFACTS_ENABLED).not.toBe('true'); + }); + + it('folds every legacy new_classes create into new_sqlite_classes, keeping tag order', () => { + const sourceMigrations = source.migrations as Array<{ + tag: string; + new_classes?: string[]; + new_sqlite_classes?: string[]; + }>; + expect(sourceMigrations.some((m) => m.new_classes?.length)).toBe(true); + // wrangler.toml's tags, in order, and nothing else. + expect(config.migrations.map((m) => m.tag)).toEqual(sourceMigrations.map((m) => m.tag)); + for (const migration of config.migrations) { + expect(Object.keys(migration).sort()).toEqual(['new_sqlite_classes', 'tag']); + } + const created = config.migrations.flatMap((m) => m.new_sqlite_classes); + const expected = sourceMigrations.flatMap((m) => [ + ...(m.new_sqlite_classes ?? []), + ...(m.new_classes ?? []), + ]); + expect(new Set(created)).toEqual(new Set(expected)); + }); + + it('binds exactly the Durable Objects wrangler.toml binds', () => { + expect(config.durable_objects.bindings).toEqual( + (source.durable_objects as { bindings: Array<{ name: string; class_name: string }> }).bindings + ); + }); + + it('keeps container DO bindings (the classes stay exported) but not their containers', () => { + const classes = config.durable_objects.bindings.map((b) => b.class_name); + expect(classes).toContain('SandboxDO'); + expect(classes).toContain('VmAgentContainer'); + }); + + it('gives every R2 binding a distinct bucket and points R2_BUCKET_NAME at the R2 binding', () => { + const names = config.r2_buckets.map((b) => b.bucket_name); + expect(new Set(names).size).toBe(names.length); + const r2 = config.r2_buckets.find((b) => b.binding === 'R2')!; + expect(config.vars.R2_BUCKET_NAME).toBe(r2.bucket_name); + }); + + it('plans one flat migrations directory per database inside the project', () => { + expect(config.d1_databases).toHaveLength(2); + for (const db of config.d1_databases) { + expect(db.migrations_dir.startsWith('d1-migrations/')).toBe(true); + expect(db.migrations_dir.split('/')).not.toContain('..'); + } + expect(plan.migrationDirs.map((d) => d.sourceDir)).toEqual([ + 'src/db/migrations', + 'src/db/migrations/observability', + ]); + // Distinct dirs even though one source is nested inside the other. + expect(new Set(config.d1_databases.map((d) => d.migrations_dir)).size).toBe(2); + }); + + it('keeps the cron triggers', () => { + expect(config.triggers.crons).toEqual((source.triggers as { crons: string[] }).crons); + expect(config.triggers.crons.length).toBeGreaterThan(0); + }); + + it('turns the Cloudflare-only switches off and sets BASE_DOMAIN', () => { + for (const [key, value] of Object.entries(SELFHOST_VAR_OVERRIDES)) + expect(config.vars[key]).toBe(value); + expect(config.vars.CF_CONTAINER_ENABLED).toBe('false'); + // wrangler.toml's AI Gateway id would build gateway URLs with no account id. + expect((source.vars as Record).AI_GATEWAY_ID).toBeTruthy(); + expect(config.vars.AI_GATEWAY_ID).toBe(''); + expect(config.vars.BASE_DOMAIN).toBe('sam.example.com'); + // Provider ownership labels need it (resolveEnvironmentLabel); Cloudflare sets it at sync. + expect(config.vars.ENVIRONMENT).toBe('selfhost'); + // Ordinary tunables still flow through from wrangler.toml [vars]. + expect(config.vars.MAX_NODES_PER_USER).toBe( + (source.vars as Record).MAX_NODES_PER_USER + ); + }); + + it('leaves the AI features to admin settings instead of forcing them off', () => { + // Titles use the admin's OpenAI-compatible endpoint (truncation without one), the gatewayless + // AI proxy waits for `aiProxy.directUpstreamEnabled`, read-aloud for `speech.synthesis.*`. + for (const key of ['TASK_TITLE_GENERATION_ENABLED', 'AI_PROXY_ENABLED', 'TTS_ENABLED']) + expect(SELFHOST_VAR_OVERRIDES).not.toHaveProperty(key); + expect(config.vars.TASK_TITLE_GENERATION_ENABLED).not.toBe('false'); + expect(config.vars.TTS_ENABLED).not.toBe('false'); + // The env kill switch passes through from wrangler.toml; it no longer turns the proxy off. + expect(config.vars.AI_PROXY_ENABLED).toBe('true'); + // Clef runs on Workers AI only, so the classifier stays off. + expect(config.vars.STALLED_TASK_CLASSIFIER_ENABLED).toBe('false'); + }); + + it('serves the web build through ASSETS with SPA fallback, Worker first', () => { + expect(config.assets).toEqual({ + directory: 'web', + binding: 'ASSETS', + not_found_handling: 'single-page-application', + run_worker_first: true, + }); + expect(config.main).toBe('src/index.ts'); + }); + + it('does not mutate the parsed wrangler.toml', () => { + expect(loadToml()).toEqual(source); + }); +}); + +describe('buildCelldConfig failure modes', () => { + const base = (): WranglerToml => loadToml(); + + it('fails loudly on a top-level key it has no rule for', () => { + for (const key of [ + 'routes', + 'tail_consumers', + 'observability', + 'env', + 'send_email', + 'workers_dev', + ]) { + const source = { ...base(), [key]: [] }; + expect(() => buildCelldConfig(source, options)).toThrow( + new RegExp(`no self-host translation: ${key}`) + ); + } + }); + + it('fails on a binding field it does not translate', () => { + const source = base(); + (source.d1_databases as Array>)[0]!.preview_database_id = 'x'; + expect(() => buildCelldConfig(source, options)).toThrow( + /d1_databases\[0\] has keys .*preview_database_id/ + ); + }); + + it('accepts an empty legacy new_classes list', () => { + const source = base(); + (source.migrations as unknown[]).push({ + tag: 'v999', + new_classes: [], + new_sqlite_classes: ['X'], + }); + const plan = buildCelldConfig(source, options); + expect(plan.config.migrations.find((m) => m.tag === 'v999')).toEqual({ + tag: 'v999', + new_sqlite_classes: ['X'], + }); + }); + + it('fails on a Durable Object migration celld cannot apply', () => { + const source = base(); + (source.migrations as unknown[]).push({ + tag: 'v999', + renamed_classes: [{ from: 'A', to: 'B' }], + }); + expect(() => buildCelldConfig(source, options)).toThrow(/migration v999 uses renamed_classes/); + }); + + it('refuses caller vars for keys the generator owns', () => { + expect(() => + buildCelldConfig(base(), { ...options, vars: { BASE_DOMAIN: 'evil.example' } }) + ).toThrow(/vars.BASE_DOMAIN is generated/); + }); + + it('refuses an assets directory outside the project', () => { + expect(() => buildCelldConfig(base(), { ...options, assetsDirectory: '../web' })).toThrow( + /no \.\./ + ); + }); + + it('omits assets when no web build is given', () => { + expect(buildCelldConfig(base(), options).config).not.toHaveProperty('assets'); + }); +}); + +describe('operator overrides', () => { + it('refuses the vars the deployment generates in secrets.env', () => { + for (const name of ['BASE_DOMAIN', 'R2_BUCKET_NAME', 'VM_AGENT_REQUIRED_VERSION']) { + expect(() => assertOperatorSecretsAllowed({ [name]: 'x' }, 'secrets.env')).toThrow( + new RegExp(`${name} is generated`) + ); + } + }); + + it('still accepts ordinary switches (turning a self-host switch back on)', () => { + expect(() => + assertOperatorSecretsAllowed({ TTS_ENABLED: 'true', CF_CONTAINER_ENABLED: 'true' }, 'x') + ).not.toThrow(); + }); +}); diff --git a/scripts/selfhost/celld-config.ts b/scripts/selfhost/celld-config.ts new file mode 100644 index 0000000000..ddfd29d195 --- /dev/null +++ b/scripts/selfhost/celld-config.ts @@ -0,0 +1,429 @@ +/** + * Translate the top-level `apps/api/wrangler.toml` into a celld `wrangler.json`. + * + * celld (https://celld.dev) reads Wrangler JSON only and stops a deploy on any key it + * does not know, so this is an explicit translation table rather than a filter: every + * top-level key in wrangler.toml must have a rule here, and an unknown key throws. That + * way a new Cloudflare-only binding cannot slip into (or silently out of) a self-hosted + * deployment. + * + * This module is pure. Filesystem work (symlinks, writing the file) lives in + * `celld-project.ts`. The Cloudflare pipeline (`scripts/deploy/sync-wrangler-config.ts`) + * never imports it. + */ + +import { resolveDurableObjectMigrations } from '../deploy/durable-object-migrations.js'; +import type { MigrationEntry, WranglerToml } from '../deploy/types.js'; + +/** Worker vars set for every celld deployment, overriding wrangler.toml [vars]. */ +export const SELFHOST_VAR_OVERRIDES: Readonly> = { + // Cloudflare Containers: Instant sessions and the Sandbox SDK. celld's container fence + // blocks container -> host traffic on a one-box install (idea 01M72M9AEB933ZY8269D376DKC). + CF_CONTAINER_ENABLED: 'false', + SANDBOX_ENABLED: 'false', + // Managed devcontainer cache uses the Cloudflare container registry API. + DEVCONTAINER_CACHE_ENABLED: 'false', + // Not forced off here (overnight B3): task titles use the admin's OpenAI-compatible endpoint + // and truncate without one (task-title.ts); the AI proxy without a gateway stays off until an + // admin turns on `aiProxy.directUpstreamEnabled` (ai-proxy-availability.ts); read-aloud follows + // the `speech.synthesis.*` settings (platform-capabilities.ts). The stalled-task classifier + // runs the Workers AI Clef model only. + STALLED_TASK_CLASSIFIER_ENABLED: 'false', + // No Analytics Engine here: product analytics go to the D1 sink in OBSERVABILITY_DATABASE + // (apps/api/src/selfhost/analytics/, installed by selfhost/build.ts; analytics.d1.* bounds). + ANALYTICS_SINK: 'd1', + // No tail worker on celld, so nothing feeds Admin → Stream; the page says to read logs on + // the box instead (platform-capabilities.ts hasLiveLogStream). + LOG_TAIL_AVAILABLE: 'false', + // AI Gateway cost reports. + COST_MONITORING_ENABLED: 'false', + // wrangler.toml ships AI_GATEWAY_ID="sam". Empty makes every gateway consumer take its + // no-gateway branch (direct Anthropic/OpenAI URLs, no AI Gateway log or cost queries). + AI_GATEWAY_ID: '', + // Nodes reach the box through frps on loopback instead of per-node Cloudflare DNS/tunnels + // (reverse-tunnel transport, sibling task T2 on sam/selfhost-pass-2). + VM_AGENT_TRANSPORT: 'reverse-tunnel', + // The environment label that, with SAM_INSTALLATION_ID, scopes provider resources to this + // install (node-provider-labels.ts). Cloudflare deploys set staging/production in + // sync-wrangler-config.ts; unset, a node whose create response was lost can never be + // recovered ("Allocation ownership scope is unavailable") and the provider-orphan sweep is + // skipped. Verified on the T4 GCP box. + ENVIRONMENT: 'selfhost', +}; + +/** + * Vars the deployment writes and an operator's secrets.env may not override (deploy.ts merges + * secrets.env last): the domain and bucket the config was built for, and the vm-agent release + * this deploy published. + */ +export const OPERATOR_FORBIDDEN_VARS = [ + 'BASE_DOMAIN', + 'R2_BUCKET_NAME', + 'VM_AGENT_REQUIRED_VERSION', +] as const; + +/** Throws when secrets.env sets a var the deployment writes (`OPERATOR_FORBIDDEN_VARS`). */ +export function assertOperatorSecretsAllowed( + secrets: Readonly>, + secretsPath: string +): void { + for (const name of OPERATOR_FORBIDDEN_VARS) { + if (name in secrets) throw new Error(`${secretsPath}: ${name} is generated; remove it`); + } +} + +/** Keys the generator owns. Values a caller passes for these are rejected. */ +const GENERATED_VAR_KEYS = ['BASE_DOMAIN', 'R2_BUCKET_NAME'] as const; + +export interface CelldD1Database { + binding: string; + database_name: string; + database_id: string; + migrations_dir: string; +} + +export interface CelldAssets { + directory: string; + binding: string; + not_found_handling: 'single-page-application'; + run_worker_first: true; +} + +export interface CelldWranglerConfig { + name: string; + main: string; + compatibility_date: string; + compatibility_flags: string[]; + vars: Record; + d1_databases: CelldD1Database[]; + kv_namespaces: Array<{ binding: string; id: string }>; + r2_buckets: Array<{ binding: string; bucket_name: string }>; + durable_objects: { bindings: Array<{ name: string; class_name: string }> }; + migrations: Array<{ tag: string; new_sqlite_classes: string[] }>; + triggers: { crons: string[] }; + assets?: CelldAssets; +} + +/** One flat migrations directory to materialise inside the project dir. */ +export interface MigrationDirPlan { + databaseName: string; + /** Relative to the project dir; celld requires a path inside it with no `..`. */ + projectRelativeDir: string; + /** Relative to apps/api: the real directory the .sql files live in. */ + sourceDir: string; +} + +export interface CelldConfigPlan { + config: CelldWranglerConfig; + migrationDirs: MigrationDirPlan[]; + /** Human-readable account of every dropped or translated key. */ + report: string[]; +} + +export interface CelldConfigOptions { + /** `main` relative to the project dir (the project dir mirrors apps/api/src via a symlink). */ + main: string; + baseDomain: string; + /** Web UI build directory relative to the project dir. Omit to deploy the API only. */ + assetsDirectory?: string; + /** Extra plain vars (installation id, operator settings). Secrets are merged later. */ + vars?: Record; +} + +/** Name used for the per-database flat migration directories inside the project dir. */ +export const MIGRATIONS_ROOT = 'd1-migrations'; +export const ASSETS_BINDING = 'ASSETS'; + +type Rule = + | { kind: 'drop'; reason: string } + | { kind: 'translate'; apply: (value: unknown, ctx: TranslateContext) => void }; + +interface TranslateContext { + out: Partial; + plan: Omit; + options: CelldConfigOptions; +} + +function fail(message: string): never { + throw new Error(`celld config: ${message}`); +} + +function asRecord(value: unknown, context: string): Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + fail(`${context} must be a table`); + } + return value as Record; +} + +function asArray(value: unknown, context: string): unknown[] { + if (!Array.isArray(value)) fail(`${context} must be an array`); + return value; +} + +function asString(value: unknown, context: string): string { + if (typeof value !== 'string' || value.length === 0) + fail(`${context} must be a non-empty string`); + return value; +} + +/** Copies exactly `fields` from a binding entry and throws on any other field. */ +function pickFields( + value: unknown, + context: string, + fields: readonly K[] +): Record { + const record = asRecord(value, context); + const allowed = new Set(fields); + const unknown = Object.keys(record).filter((key) => !allowed.has(key)); + if (unknown.length > 0) { + fail(`${context} has keys celld config does not translate: ${unknown.join(', ')}`); + } + const picked = {} as Record; + for (const key of fields) picked[key] = asString(record[key], `${context}.${key}`); + return picked; +} + +function stringArray(value: unknown, context: string): string[] { + return asArray(value, context).map((entry, index) => asString(entry, `${context}[${index}]`)); +} + +/** `src/db/migrations` -> `d1-migrations/workspaces-dev`; flat, inside the project. */ +function migrationDirName(databaseName: string): string { + if (!/^[a-z0-9][a-z0-9-]*$/.test(databaseName)) { + fail(`D1 database_name "${databaseName}" is not a safe directory name`); + } + return `${MIGRATIONS_ROOT}/${databaseName}`; +} + +function translateMigrations(value: unknown, ctx: TranslateContext): void { + const entries = asArray(value, 'migrations') as MigrationEntry[]; + // A celld fleet is always a clean install from the Cloudflare migration history's point of + // view: fold every legacy `new_classes` create into `new_sqlite_classes` with the shared + // resolver the Cloudflare pipeline uses for clean installs. + // An empty `new_classes: []` is a no-op the resolver leaves in place; drop it so it is not + // mistaken for an untranslatable key below. + const withoutEmpty = entries.map(({ new_classes, ...rest }) => + new_classes?.length ? { ...rest, new_classes } : rest + ); + const resolved = resolveDurableObjectMigrations(withoutEmpty, null) ?? []; + ctx.out.migrations = resolved.map((entry) => { + const extra = Object.keys(entry).filter((key) => key !== 'tag' && key !== 'new_sqlite_classes'); + if (extra.length > 0) { + fail( + `migration ${entry.tag} uses ${extra.join(', ')}; celld accepts only tag + new_sqlite_classes` + ); + } + return { + tag: asString(entry.tag, 'migrations[].tag'), + new_sqlite_classes: stringArray(entry.new_sqlite_classes ?? [], `migrations ${entry.tag}`), + }; + }); + const folded = entries.filter((entry) => entry.new_classes?.length).map((entry) => entry.tag); + if (folded.length > 0) { + ctx.plan.report.push(`fold new_classes into new_sqlite_classes: ${folded.join(', ')}`); + } +} + +function translateD1(value: unknown, ctx: TranslateContext): void { + ctx.out.d1_databases = asArray(value, 'd1_databases').map((entry, index) => { + const d = pickFields(entry, `d1_databases[${index}]`, [ + 'binding', + 'database_name', + 'database_id', + 'migrations_dir', + ]); + const projectRelativeDir = migrationDirName(d.database_name); + ctx.plan.migrationDirs.push({ + databaseName: d.database_name, + projectRelativeDir, + sourceDir: d.migrations_dir, + }); + ctx.plan.report.push( + `d1 ${d.binding}: migrations_dir ${d.migrations_dir} -> ${projectRelativeDir} (flat)` + ); + return { + binding: d.binding, + database_name: d.database_name, + database_id: d.database_id, + migrations_dir: projectRelativeDir, + }; + }); +} + +function translateR2(value: unknown, ctx: TranslateContext): void { + // celld refuses two bindings that name one bucket. SAM binds R2 and + // PROJECT_DATA_ARCHIVE_R2 to one Cloudflare bucket and separates them by key prefix, + // so later duplicates get a name derived from their binding. + const seen = new Set(); + ctx.out.r2_buckets = asArray(value, 'r2_buckets').map((entry, index) => { + const b = pickFields(entry, `r2_buckets[${index}]`, ['binding', 'bucket_name']); + let bucketName = b.bucket_name; + if (seen.has(bucketName)) { + bucketName = `${bucketName}-${b.binding.toLowerCase().replaceAll('_', '-')}`; + if (seen.has(bucketName)) fail(`r2 binding ${b.binding} cannot get a distinct bucket name`); + ctx.plan.report.push(`r2 ${b.binding}: shared bucket ${b.bucket_name} -> ${bucketName}`); + } + seen.add(bucketName); + return { binding: b.binding, bucket_name: bucketName }; + }); +} + +const RULES: Readonly> = { + name: { kind: 'translate', apply: (v, ctx) => (ctx.out.name = asString(v, 'name')) }, + main: { kind: 'translate', apply: (_v, ctx) => (ctx.out.main = ctx.options.main) }, + compatibility_date: { + kind: 'translate', + apply: (v, ctx) => (ctx.out.compatibility_date = asString(v, 'compatibility_date')), + }, + compatibility_flags: { + kind: 'translate', + apply: (v, ctx) => (ctx.out.compatibility_flags = stringArray(v, 'compatibility_flags')), + }, + port: { kind: 'drop', reason: 'wrangler dev port; celld listens where the node is started' }, + limits: { kind: 'drop', reason: 'no celld equivalent (CELLD_HANDLER_BUDGET_S is node-wide)' }, + alias: { kind: 'drop', reason: "celld's own esbuild bundles apps/api without the shim" }, + vars: { + kind: 'translate', + apply: (v, ctx) => { + const vars = asRecord(v, 'vars'); + ctx.out.vars = Object.fromEntries( + Object.entries(vars).map(([key, value]) => { + if (typeof value === 'object' && value !== null) fail(`vars.${key} must be a scalar`); + return [key, String(value)]; + }) + ); + }, + }, + artifacts: { + kind: 'drop', + reason: 'Cloudflare Artifacts binding; a box has no SAM-native git backend', + }, + analytics_engine_datasets: { + kind: 'drop', + reason: 'Analytics Engine binding; ANALYTICS_SINK=d1 records analytics in D1 instead', + }, + ai: { kind: 'drop', reason: 'Workers AI binding' }, + containers: { + kind: 'drop', + reason: 'Cloudflare Containers; celld runs none, so their classes stay bound as plain DOs', + }, + d1_databases: { kind: 'translate', apply: translateD1 }, + kv_namespaces: { + kind: 'translate', + apply: (v, ctx) => + (ctx.out.kv_namespaces = asArray(v, 'kv_namespaces').map((entry, index) => { + const kv = pickFields(entry, `kv_namespaces[${index}]`, ['binding', 'id']); + return { binding: kv.binding, id: kv.id }; + })), + }, + r2_buckets: { kind: 'translate', apply: translateR2 }, + durable_objects: { + kind: 'translate', + apply: (v, ctx) => { + const record = asRecord(v, 'durable_objects'); + const unknown = Object.keys(record).filter((key) => key !== 'bindings'); + if (unknown.length > 0) fail(`durable_objects has untranslated keys: ${unknown.join(', ')}`); + ctx.out.durable_objects = { + bindings: asArray(record.bindings, 'durable_objects.bindings').map((entry, index) => { + const b = pickFields(entry, `durable_objects.bindings[${index}]`, ['name', 'class_name']); + return { name: b.name, class_name: b.class_name }; + }), + }; + }, + }, + migrations: { kind: 'translate', apply: translateMigrations }, + triggers: { + kind: 'translate', + apply: (v, ctx) => { + const record = asRecord(v, 'triggers'); + const unknown = Object.keys(record).filter((key) => key !== 'crons'); + if (unknown.length > 0) fail(`triggers has untranslated keys: ${unknown.join(', ')}`); + ctx.out.triggers = { crons: stringArray(record.crons ?? [], 'triggers.crons') }; + }, + }, +}; + +const REQUIRED_OUTPUT_KEYS = [ + 'name', + 'main', + 'compatibility_date', + 'vars', + 'd1_databases', + 'kv_namespaces', + 'r2_buckets', + 'durable_objects', + 'migrations', + 'triggers', +] as const; + +/** + * Builds the celld config for one deployment. + * + * Throws on any wrangler.toml key without a translation rule, on binding fields it does not + * know, and on Durable Object migrations celld cannot apply (renames, deletes, transfers). + */ +export function buildCelldConfig( + source: WranglerToml, + options: CelldConfigOptions +): CelldConfigPlan { + if (!/^[a-z0-9.-]+$/i.test(options.baseDomain) || !options.baseDomain.includes('.')) { + fail(`baseDomain "${options.baseDomain}" is not a domain name`); + } + for (const key of GENERATED_VAR_KEYS) { + if (options.vars && key in options.vars) fail(`vars.${key} is generated; do not pass it`); + } + + const unknownKeys = Object.keys(source).filter((key) => !(key in RULES)); + if (unknownKeys.length > 0) { + fail( + `wrangler.toml has top-level keys with no self-host translation: ${unknownKeys.join(', ')}. ` + + 'Add a rule to scripts/selfhost/celld-config.ts (translate it, or drop it with a reason ' + + 'and make the Worker inert without it).' + ); + } + + const ctx: TranslateContext = { out: {}, plan: { migrationDirs: [], report: [] }, options }; + for (const [key, value] of Object.entries(source)) { + const rule = RULES[key]; + if (!rule) continue; // unreachable: unknown keys were rejected above + if (rule.kind === 'drop') ctx.plan.report.push(`drop [${key}]: ${rule.reason}`); + else rule.apply(value, ctx); + } + for (const key of REQUIRED_OUTPUT_KEYS) { + if (ctx.out[key] === undefined) fail(`wrangler.toml is missing ${key}`); + } + + const out = ctx.out as CelldWranglerConfig; + out.compatibility_flags ??= []; + const r2 = out.r2_buckets.find((bucket) => bucket.binding === 'R2'); + out.vars = { + ...out.vars, + ...SELFHOST_VAR_OVERRIDES, + ...(options.vars ?? {}), + BASE_DOMAIN: options.baseDomain, + ...(r2 ? { R2_BUCKET_NAME: r2.bucket_name } : {}), + }; + + if (options.assetsDirectory !== undefined) { + if ( + options.assetsDirectory.startsWith('/') || + options.assetsDirectory.split('/').includes('..') + ) { + fail('assetsDirectory must be relative to the project dir with no ..'); + } + if (out.durable_objects.bindings.some((b) => b.name === ASSETS_BINDING)) { + fail(`binding name ${ASSETS_BINDING} is already used`); + } + // run_worker_first: every request reaches the Worker, which sends only + // app.${BASE_DOMAIN} to env.ASSETS (lib/pages-proxy.ts). Without it celld would answer + // api./ws-* requests whose path matches a file in the web build. + out.assets = { + directory: options.assetsDirectory, + binding: ASSETS_BINDING, + not_found_handling: 'single-page-application', + run_worker_first: true, + }; + } + + return { config: out, migrationDirs: ctx.plan.migrationDirs, report: ctx.plan.report }; +} diff --git a/scripts/selfhost/celld-project.test.ts b/scripts/selfhost/celld-project.test.ts new file mode 100644 index 0000000000..887e29fc92 --- /dev/null +++ b/scripts/selfhost/celld-project.test.ts @@ -0,0 +1,152 @@ +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + readlinkSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +import * as TOML from '@iarna/toml'; +import { describe, expect, it } from 'vitest'; + +import type { WranglerToml } from '../deploy/types.js'; +import { buildCelldConfig } from './celld-config.js'; +import { + CELLD_MAIN, + listMigrationFiles, + prepareCelldProject, + renderCelldMain, + writeCelldConfig, +} from './celld-project.js'; + +const API_DIR = resolve(import.meta.dirname, '../../apps/api'); + +function plan(assets = false) { + const source = TOML.parse(readFileSync(join(API_DIR, 'wrangler.toml'), 'utf8')) as WranglerToml; + return buildCelldConfig(source, { + main: 'src/index.ts', + baseDomain: 'sam.example.com', + ...(assets ? { assetsDirectory: 'web' } : {}), + }); +} + +function fakeWebDist(): string { + const dir = mkdtempSync(join(tmpdir(), 'sam-web-')); + mkdirSync(join(dir, 'assets')); + writeFileSync(join(dir, 'index.html'), ''); + writeFileSync(join(dir, '_headers'), '/oauth/consent\n X-Frame-Options: DENY\n'); + writeFileSync(join(dir, 'assets', 'app.js'), 'x'); + writeFileSync(join(dir, 'assets', 'app.js.map'), '{}'); + return dir; +} + +describe('prepareCelldProject', () => { + it('writes the plain celld entry: the shared entry, the runtime switch and the self-host build', () => { + const projectDir = join(mkdtempSync(join(tmpdir(), 'sam-celld-')), 'project'); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan: plan() }); + const main = readFileSync(join(projectDir, CELLD_MAIN), 'utf8'); + expect(main).toBe(renderCelldMain()); + expect(main).toContain("import worker from './src/index.ts';"); + expect(main).toContain('resumeSharedFlightJoinsOnOwnTimer();'); + expect(main).toContain("export * from './src/index.ts';"); + expect(main).toContain('export default withSelfHostBuild(worker);'); + // Every module the entry imports exists in apps/api (the symlinked src). + const specifiers = [...main.matchAll(/from '\.\/src\/([^']+)'/g)].map((m) => m[1]!); + expect(specifiers.length).toBeGreaterThanOrEqual(3); + for (const specifier of specifiers) { + expect(existsSync(join(API_DIR, 'src', specifier)), specifier).toBe(true); + } + // Nothing but the shared entry's own exports and the default. + expect(main.match(/^export /gm)).toHaveLength(2); + expect(statSync(join(projectDir, CELLD_MAIN)).mode & 0o777).toBe(0o600); + }); + + it('builds flat per-database migration dirs from the real migrations without moving them', () => { + const projectDir = join(mkdtempSync(join(tmpdir(), 'sam-celld-')), 'project'); + const p = plan(); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan: p }); + + expect(readlinkSync(join(projectDir, 'src'))).toBe(join(API_DIR, 'src')); + const main = listMigrationFiles(join(API_DIR, 'src/db/migrations')); + const observability = listMigrationFiles(join(API_DIR, 'src/db/migrations/observability')); + expect(main.length).toBeGreaterThan(200); + expect(observability.length).toBeGreaterThan(0); + + const [mainDir, obsDir] = p.config.d1_databases.map((db) => + join(projectDir, db.migrations_dir) + ); + // The primary database also carries the self-host-only reverse-tunnel lease migration, the + // only source of node_reverse_tunnel_leases since the shared 0232 copy was removed. + const leases = '0255_node_reverse_tunnel_leases.sql'; + expect(main).not.toContain(leases); + expect(readdirSync(mainDir!).sort()).toEqual([...main, leases].sort()); + expect(readlinkSync(join(mainDir!, leases))).toBe( + join(API_DIR, 'src/selfhost/migrations', leases) + ); + // OBSERVABILITY_DATABASE likewise carries the self-host-only D1 analytics sink table (L20), + // which the shared observability directory (wrangler.toml) no longer holds. + const analytics = '0002_analytics_events.sql'; + expect(observability).not.toContain(analytics); + expect(readdirSync(obsDir!).sort()).toEqual([...observability, analytics].sort()); + expect(readlinkSync(join(obsDir!, analytics))).toBe( + join(API_DIR, 'src/selfhost/migrations/observability', analytics) + ); + // Flat: no subdirectory holding .sql files (celld refuses that), and links, not copies. + for (const dir of [mainDir!, obsDir!]) { + for (const entry of readdirSync(dir)) + expect(lstatSync(join(dir, entry)).isSymbolicLink()).toBe(true); + } + expect(existsSync(join(API_DIR, 'src/db/migrations/observability'))).toBe(true); + }); + + it('is idempotent and drops links to migrations that no longer exist', () => { + const projectDir = join(mkdtempSync(join(tmpdir(), 'sam-celld-')), 'project'); + const p = plan(); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan: p }); + const mainDir = join(projectDir, p.config.d1_databases[0]!.migrations_dir); + writeFileSync(join(mainDir, '9999_stale.sql'), 'SELECT 1;'); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan: p }); + expect(existsSync(join(mainDir, '9999_stale.sql'))).toBe(false); + }); + + it('refuses to replace a real directory where the src symlink belongs', () => { + const projectDir = mkdtempSync(join(tmpdir(), 'sam-celld-')); + mkdirSync(join(projectDir, 'src')); + expect(() => prepareCelldProject({ apiDir: API_DIR, projectDir, plan: plan() })).toThrow( + /not a symlink/ + ); + }); + + it('copies the web build with _headers but without source maps', () => { + const projectDir = join(mkdtempSync(join(tmpdir(), 'sam-celld-')), 'project'); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan: plan(true), webDist: fakeWebDist() }); + expect(readFileSync(join(projectDir, 'web/_headers'), 'utf8')).toContain( + 'X-Frame-Options: DENY' + ); + expect(existsSync(join(projectDir, 'web/assets/app.js'))).toBe(true); + expect(existsSync(join(projectDir, 'web/assets/app.js.map'))).toBe(false); + }); + + it('refuses a web build containing a symlink', () => { + const projectDir = join(mkdtempSync(join(tmpdir(), 'sam-celld-')), 'project'); + const dist = fakeWebDist(); + symlinkSync('/etc/hostname', join(dist, 'assets', 'leak.txt')); + expect(() => + prepareCelldProject({ apiDir: API_DIR, projectDir, plan: plan(true), webDist: dist }) + ).toThrow(/is a symlink/); + }); + + it('writes the config root-only', () => { + const projectDir = mkdtempSync(join(tmpdir(), 'sam-celld-')); + const path = writeCelldConfig(projectDir, plan().config); + expect(statSync(path).mode & 0o777).toBe(0o600); + expect(JSON.parse(readFileSync(path, 'utf8')).name).toBe('workspaces-api'); + }); +}); diff --git a/scripts/selfhost/celld-project.ts b/scripts/selfhost/celld-project.ts new file mode 100644 index 0000000000..84a97ba23d --- /dev/null +++ b/scripts/selfhost/celld-project.ts @@ -0,0 +1,159 @@ +/** + * Materialise a celld project directory for `apps/api`. + * + * celld requires `main`, `assets.directory` and every D1 `migrations_dir` to sit inside the + * project directory with no `..`, and reads migrations from flat directories only. The + * repository keeps the observability migrations nested inside the main ones, so the project + * gets one flat directory of symlinks per database. The real migration files are never moved. + */ + +import { + cpSync, + existsSync, + lstatSync, + mkdirSync, + readdirSync, + readlinkSync, + renameSync, + rmSync, + symlinkSync, +} from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +import type { CelldConfigPlan, CelldWranglerConfig } from './celld-config.js'; +import { appendSelfhostObservabilityMigrations } from './observability-migrations.js'; +import { appendReverseTunnelMigrations } from './reverse-tunnel-migrations.js'; +import { writePrivateFile } from './secret-files.js'; + +export const CONFIG_FILE = 'wrangler.json'; +export const SOURCE_LINK = 'src'; +export const ASSETS_DIR = 'web'; +/** The generated celld entry module (renderCelldMain). */ +export const CELLD_MAIN = 'celld-main.ts'; +/** apps/api/wrangler.toml `migrations_dir` of the primary DATABASE. */ +const PRIMARY_MIGRATIONS_DIR = 'src/db/migrations'; +/** apps/api/wrangler.toml `migrations_dir` of OBSERVABILITY_DATABASE. */ +const OBSERVABILITY_MIGRATIONS_DIR = 'src/db/migrations/observability'; + +/** + * The celld entry: the API's own entry (`src/index.ts`, every export kept by `export *`), plus + * what only a celld build turns on before any request runs: + * + * - `resumeSharedFlightJoinsOnOwnTimer()`: on celld the code that runs when a promise settles + * belongs to the request that settled it, so a request joining another's in-flight read must + * resume on its own timer (packages/worker-core/src/shared-flight.ts, imported through its + * apps/api/src/lib/shared-flight.ts re-export); + * - `withSelfHostBuild` (apps/api/src/selfhost/build.ts): the speech backend, the D1 analytics + * sink and the reverse-tunnel transport, gateway and lease sweep. + * + * The Cloudflare entry never imports either module from here, and never sees this file + * (apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts). + */ +export function renderCelldMain(): string { + return [ + '// Generated by scripts/selfhost/celld-project.ts (renderCelldMain). Do not edit.', + `import worker from './${SOURCE_LINK}/index.ts';`, + `import { resumeSharedFlightJoinsOnOwnTimer } from './${SOURCE_LINK}/lib/shared-flight.ts';`, + `import { withSelfHostBuild } from './${SOURCE_LINK}/selfhost/build.ts';`, + '', + 'resumeSharedFlightJoinsOnOwnTimer();', + `export * from './${SOURCE_LINK}/index.ts';`, + 'export default withSelfHostBuild(worker);', + '', + ].join('\n'); +} + +export interface PrepareProjectOptions { + /** Absolute path to apps/api. */ + apiDir: string; + /** Absolute path to the generated project directory. */ + projectDir: string; + plan: CelldConfigPlan; + /** Absolute path to the apps/web build output; copied into the project when set. */ + webDist?: string; +} + +/** Points `link` at `target`, replacing a stale symlink but never a real file or directory. */ +function ensureSymlink(target: string, link: string): void { + if (existsSync(link) || isSymlink(link)) { + if (!isSymlink(link)) + throw new Error(`${link} exists and is not a symlink; refusing to replace it`); + if (readlinkSync(link) === target) return; + rmSync(link); + } + symlinkSync(target, link); +} + +function isSymlink(path: string): boolean { + try { + return lstatSync(path).isSymbolicLink(); + } catch { + return false; + } +} + +/** The .sql files directly inside `dir`, sorted; subdirectories are ignored. */ +export function listMigrationFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.sql')) + .map((entry) => entry.name) + .sort(); +} + +export function prepareCelldProject(options: PrepareProjectOptions): void { + const { apiDir, projectDir, plan } = options; + mkdirSync(projectDir, { recursive: true, mode: 0o700 }); + ensureSymlink(resolve(apiDir, 'src'), join(projectDir, SOURCE_LINK)); + + for (const dir of plan.migrationDirs) { + const source = resolve(apiDir, dir.sourceDir); + const files = listMigrationFiles(source); + if (files.length === 0) throw new Error(`no .sql migrations in ${source}`); + const target = join(projectDir, dir.projectRelativeDir); + // Rebuilt every run so a deleted or renamed migration cannot linger as a stale link. + rmSync(target, { recursive: true, force: true }); + mkdirSync(target, { recursive: true }); + for (const file of files) symlinkSync(join(source, file), join(target, file)); + // The primary database also gets the self-host-only migrations (reverse-tunnel leases, + // apps/api/src/selfhost/migrations/), which apps/api/wrangler.toml never lists. + if (dir.sourceDir === PRIMARY_MIGRATIONS_DIR) appendReverseTunnelMigrations(apiDir, target); + // OBSERVABILITY_DATABASE gets the D1 analytics sink's table the same way (L20, + // apps/api/src/selfhost/observability-migrations.ts). + if (dir.sourceDir === OBSERVABILITY_MIGRATIONS_DIR) { + appendSelfhostObservabilityMigrations(apiDir, target); + } + } + + writePrivateFile(join(projectDir, CELLD_MAIN), renderCelldMain()); + + if (options.webDist) { + if (!existsSync(join(options.webDist, 'index.html'))) { + throw new Error(`${options.webDist} has no index.html; build apps/web first`); + } + const target = join(projectDir, ASSETS_DIR); + const staging = `${target}.next`; + rmSync(staging, { recursive: true, force: true }); + // Source maps stay out of the box: they triple the upload and the browser never needs them. + // A symlink in the build could publish any file on the box at app.*; refuse it. + cpSync(options.webDist, staging, { + recursive: true, + filter: (src) => { + if (lstatSync(src).isSymbolicLink()) { + throw new Error(`${src} is a symlink; the web build must contain only regular files`); + } + return !src.endsWith('.map'); + }, + }); + rmSync(target, { recursive: true, force: true }); + renameSync(staging, target); + } +} + +/** Writes the config with mode 0600; atomic so celld never reads a half-written file. */ +export function writeCelldConfig(projectDir: string, config: CelldWranglerConfig): string { + const path = join(projectDir, CONFIG_FILE); + const temp = join(dirname(path), `.${CONFIG_FILE}.tmp`); + writePrivateFile(temp, `${JSON.stringify(config, null, 2)}\n`); + renameSync(temp, path); + return path; +} diff --git a/scripts/selfhost/create-account.test.ts b/scripts/selfhost/create-account.test.ts new file mode 100644 index 0000000000..faed75213d --- /dev/null +++ b/scripts/selfhost/create-account.test.ts @@ -0,0 +1,187 @@ +import { describe, expect, it } from 'vitest'; + +import { + type AccountPlan, + createAccountSql, + OWNER_ESTABLISHED_SETTING, + parseAccountReport, +} from './account-sql.js'; +import { mainDatabaseName, ownerLockoutRefusal } from './create-account.js'; + +describe('mainDatabaseName', () => { + it('finds the database bound as DATABASE in the deployed celld config', () => { + const config = { + d1_databases: [ + { binding: 'OBSERVABILITY_DATABASE', database_name: 'observability-dev' }, + { binding: 'DATABASE', database_name: 'workspaces-dev' }, + ], + }; + expect(mainDatabaseName(JSON.stringify(config))).toBe('workspaces-dev'); + }); + + it('refuses a config without it (not deployed yet)', () => { + expect(() => mainDatabaseName('{"d1_databases":[]}')).toThrow('run pnpm selfhost:deploy first'); + expect(() => mainDatabaseName('{}')).toThrow('run pnpm selfhost:deploy first'); + }); +}); + +describe('createAccountSql', () => { + const plan = { email: 'teammate@example.com', id: 'A'.repeat(32), nowMs: 1_700_000_000_000 }; + + it('promotes only with --superadmin', () => { + expect(createAccountSql({ ...plan, superadmin: false })).not.toContain('UPDATE users'); + expect(createAccountSql({ ...plan, superadmin: true })).toContain( + "UPDATE users SET role = 'superadmin', status = CASE WHEN status = 'pending'" + ); + }); + + it('refuses values it did not generate or check', () => { + expect(() => + createAccountSql({ ...plan, superadmin: false, email: "x'@example.com" }) + ).toThrow(); + expect(() => + createAccountSql({ ...plan, superadmin: false, id: "x'); DROP TABLE users;--" }) + ).toThrow('bad account id'); + expect(() => createAccountSql({ ...plan, superadmin: false, nowMs: Number.NaN })).toThrow( + 'bad timestamp' + ); + }); +}); + +describe('parseAccountReport', () => { + // `celld d1 execute` output, as observed on celld 0.6.3. + const table = [ + 'id email role status emailVerified activeSuperadmins', + '-------------------------------- -------------------- ---- ------ ------------- -----------------', + 'UNX8rGfGHBFjvlB7HLFS4ZRF6XTp3BBI teammate@example.com user active 1 1', + 'Executed 2 statement(s) in 3ms', + ].join('\n'); + + it('reads the account row', () => { + expect(parseAccountReport(table, 'teammate@example.com')).toEqual({ + id: 'UNX8rGfGHBFjvlB7HLFS4ZRF6XTp3BBI', + role: 'user', + status: 'active', + }); + }); + + it('finds nothing when the report has no row, even if the address appears elsewhere', () => { + const empty = [ + "INSERT INTO users ... '01234567890123456789012345678901', 'teammate@example.com' ...;", + 'id email role status emailVerified activeSuperadmins', + 'Executed 2 statement(s) in 1ms', + ].join('\n'); + expect(parseAccountReport(empty, 'teammate@example.com')).toBeNull(); + expect(parseAccountReport(table, 'other@example.com')).toBeNull(); + }); +}); + +describe('--superadmin before the bootstrap owner is established (plan finding F13)', () => { + // A real SQL engine: the guard is a predicate in the statements create-account runs. + async function database() { + const { DatabaseSync } = await import('node:sqlite'); + const db = new DatabaseSync(':memory:'); + db.exec(`CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT NOT NULL, + email_verified INTEGER NOT NULL DEFAULT 0, name TEXT, role TEXT NOT NULL DEFAULT 'user', + status TEXT NOT NULL DEFAULT 'active', created_at INTEGER, updated_at INTEGER); + CREATE TABLE platform_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL, + updated_at TEXT, updated_by TEXT); + INSERT INTO users (id, email, email_verified, name, role, status) + VALUES ('system_anonymous_trials', 'system@internal', 0, 'System', 'user', 'system');`); + return db; + } + const OWNER = 'owner@example.com'; + const plan = (email: string, extra: Partial = {}): AccountPlan => ({ + email, + superadmin: true, + id: 'B'.repeat(32), + nowMs: 1_700_000_000_000, + bootstrapOwnerEmail: OWNER, + ...extra, + }); + type Row = { email: string; role: string }; + const rows = (db: Awaited>) => + db + .prepare(`SELECT email, role FROM users WHERE status != 'system' ORDER BY email`) + .all() as unknown as Row[]; + + it('writes no superadmin for another address and explains why', async () => { + const db = await database(); + const teammate = plan('teammate@example.com'); + db.exec(createAccountSql(teammate)); + expect(rows(db)).toEqual([]); + expect(ownerLockoutRefusal(teammate, null)).toContain( + 'owner@example.com (BOOTSTRAP_OWNER_EMAIL) has not signed in yet' + ); + }); + + it('does not promote an existing account for another address either', async () => { + const db = await database(); + db.exec(createAccountSql(plan('teammate@example.com', { superadmin: false }))); + const teammate = plan('teammate@example.com'); + db.exec(createAccountSql(teammate)); + expect(rows(db)).toEqual([{ email: 'teammate@example.com', role: 'user' }]); + expect(ownerLockoutRefusal(teammate, { id: 'x', role: 'user', status: 'active' })).not.toBe( + null + ); + }); + + it('control: the owner themselves may be made superadmin', async () => { + const db = await database(); + const owner = plan(OWNER); + db.exec(createAccountSql(owner)); + expect(rows(db)).toEqual([{ email: OWNER, role: 'superadmin' }]); + expect(ownerLockoutRefusal(owner, { id: 'x', role: 'superadmin', status: 'active' })).toBe( + null + ); + }); + + it('control: a plain account for another address is still created', async () => { + const db = await database(); + const teammate = plan('teammate@example.com', { superadmin: false }); + db.exec(createAccountSql(teammate)); + expect(rows(db)).toEqual([{ email: 'teammate@example.com', role: 'user' }]); + expect(ownerLockoutRefusal(teammate, { id: 'x', role: 'user', status: 'active' })).toBe(null); + }); + + it.each([ + [ + 'the owner-established marker', + `INSERT INTO platform_settings (key, value) VALUES ('${OWNER_ESTABLISHED_SETTING}', '{"version":1,"ownerId":"o"}')`, + ], + [ + 'the owner as a verified active superadmin', + `INSERT INTO users (id, email, email_verified, name, role, status) + VALUES ('o', '${OWNER}', 1, 'Owner', 'superadmin', 'active')`, + ], + ])('allows another superadmin once the owner is established (%s)', async (_name, seed) => { + const db = await database(); + db.exec(seed); + db.exec(createAccountSql(plan('teammate@example.com'))); + expect(rows(db).find((row) => row.email === 'teammate@example.com')?.role).toBe('superadmin'); + }); + + it('control: an unverified or suspended owner row does not count as established', async () => { + const db = await database(); + db.exec(`INSERT INTO users (id, email, email_verified, name, role, status) + VALUES ('o', '${OWNER}', 0, 'Owner', 'superadmin', 'active')`); + db.exec(createAccountSql(plan('teammate@example.com'))); + expect(rows(db).map((row) => row.email)).toEqual([OWNER]); + }); + + it('unchanged without an owner email: any address may be made superadmin', async () => { + const db = await database(); + const teammate = plan('teammate@example.com', { bootstrapOwnerEmail: undefined }); + db.exec(createAccountSql(teammate)); + expect(rows(db)).toEqual([{ email: 'teammate@example.com', role: 'superadmin' }]); + expect(ownerLockoutRefusal(teammate, { id: 'x', role: 'superadmin', status: 'active' })).toBe( + null + ); + }); + + it('refuses an owner email it cannot safely put in SQL', () => { + expect(() => + createAccountSql(plan('teammate@example.com', { bootstrapOwnerEmail: "o'@example.com" })) + ).toThrow(); + }); +}); diff --git a/scripts/selfhost/create-account.ts b/scripts/selfhost/create-account.ts new file mode 100644 index 0000000000..1a826a077f --- /dev/null +++ b/scripts/selfhost/create-account.ts @@ -0,0 +1,157 @@ +#!/usr/bin/env tsx +/** + * Create a SAM account on a deployed celld box, so that address can sign in with an emailed code. + * + * pnpm selfhost:create-account --email someone@example.com [--superadmin] + * [--env-file deploy/selfhost/.env] [--state-dir /.state] + * [--dry-run] + * + * For an install whose first-account path is already used (a seeded smoke-test superadmin, or an + * owner who signed up): email sign-in sends codes only to existing accounts, so a new person needs + * an account first. Idempotent: an existing account is left as it is, except that --superadmin + * promotes it. Writes the `users` table BetterAuth reads (account-sql.ts) through + * `celld d1 execute`, so the stack must be running and deployed (`pnpm selfhost:deploy`). + */ +import { spawnSync } from 'node:child_process'; +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; + +import { + type AccountPlan, + type AccountReport, + createAccountSql, + generateAccountId, + normalizeAccountEmail, + parseAccountReport, + superadminWaitsForOwner, +} from './account-sql.js'; +import { celldChildEnv, redactSecrets } from './box-settings.js'; +import { ensureCelldBinary, resolveEsbuild } from './celld-binary.js'; +import { assertPrivateFile, parseDotenv, readSecretsFile } from './secret-files.js'; + +const REPO_ROOT = resolve(import.meta.dirname, '../..'); +/** Upper bound on captured celld output. */ +const CHILD_OUTPUT_MAX_BYTES = 16 * 1024 * 1024; + +function log(message: string): void { + console.log(`[selfhost] ${message}`); +} + +/** + * Why `--superadmin` was refused, or null. The SQL writes nothing for a non-owner superadmin + * while the bootstrap owner is not established (account-sql.ts), so a missing account, or one + * that is still not a superadmin, means the guard held. + */ +export function ownerLockoutRefusal( + plan: AccountPlan, + account: AccountReport | null +): string | null { + if (!superadminWaitsForOwner(plan) || account?.role === 'superadmin') return null; + return ( + `refused: ${plan.bootstrapOwnerEmail} (BOOTSTRAP_OWNER_EMAIL) has not signed in yet. ` + + `SAM makes the owner the administrator on their first sign-in only while no other ` + + `superadmin exists, and admits no one else before that, so a superadmin for ` + + `${plan.email} now would lock everyone out. Nothing was changed. Sign in as the owner ` + + `first, then run this again, or run it without --superadmin.` + ); +} + +/** The D1 database bound as DATABASE in the deployed (secrets-free) celld config. */ +export function mainDatabaseName(wranglerJson: string): string { + const config: unknown = JSON.parse(wranglerJson); + const databases = + config && typeof config === 'object' && 'd1_databases' in config ? config.d1_databases : null; + if (Array.isArray(databases)) { + for (const entry of databases as unknown[]) { + if (entry && typeof entry === 'object' && 'binding' in entry && 'database_name' in entry) { + if (entry.binding === 'DATABASE' && typeof entry.database_name === 'string') { + return entry.database_name; + } + } + } + } + throw new Error('the deployed config has no DATABASE binding; run pnpm selfhost:deploy first'); +} + +async function main(): Promise { + const { values } = parseArgs({ + options: { + email: { type: 'string' }, + superadmin: { type: 'boolean', default: false }, + 'env-file': { type: 'string' }, + 'state-dir': { type: 'string' }, + 'dry-run': { type: 'boolean', default: false }, + }, + }); + if (!values.email) throw new Error('--email is required'); + const email = normalizeAccountEmail(values.email); + + const envFile = resolve(values['env-file'] ?? join(REPO_ROOT, 'deploy/selfhost/.env')); + assertPrivateFile(envFile); + const box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); + const stateDir = resolve( + dirname(envFile), + values['state-dir'] ?? box.SAM_SELFHOST_STATE_DIR ?? '.state' + ); + const owner = readSecretsFile(join(stateDir, 'secrets.env')).BOOTSTRAP_OWNER_EMAIL?.trim(); + // The Worker treats a present but empty owner email as configured and admits no one + // (bootstrap-owner.ts); refuse rather than write accounts nobody can use. + if (owner === '') { + throw new Error( + 'BOOTSTRAP_OWNER_EMAIL is set but empty in secrets.env: SAM would admit no one. Set the ' + + "owner's address or remove the line, then deploy, before creating accounts." + ); + } + const plan = { + email, + superadmin: values.superadmin ?? false, + id: generateAccountId(), + nowMs: Date.now(), + bootstrapOwnerEmail: owner ? normalizeAccountEmail(owner) : undefined, + }; + const sql = createAccountSql(plan); + if (values['dry-run']) { + console.log(sql); + return; + } + + const projectDir = join(stateDir, 'project'); + const configPath = join(projectDir, 'wrangler.json'); + if (!existsSync(configPath)) throw new Error(`${configPath} not found; run pnpm selfhost:deploy`); + const database = mainDatabaseName(readFileSync(configPath, 'utf8')); + + const celld = await ensureCelldBinary(join(stateDir, 'bin')); + const env = celldChildEnv(process.env, box, resolveEsbuild(join(REPO_ROOT, 'apps/api'))); + log(`${values.superadmin ? 'creating or promoting' : 'creating'} the account for ${email}`); + const result = spawnSync( + celld, + ['d1', 'execute', database, '--command', sql, projectDir, '--bucket', box.CELLD_BUCKET], + { cwd: REPO_ROOT, env, encoding: 'utf8', maxBuffer: CHILD_OUTPUT_MAX_BYTES } + ); + const secrets = [box.AWS_SECRET_ACCESS_KEY ?? ''].filter(Boolean); + process.stdout.write(redactSecrets(`${result.stdout ?? ''}${result.stderr ?? ''}`, secrets)); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`celld d1 execute failed (exit ${result.status})`); + // The last statement reports the account; no row means nothing usable was written. + const account = parseAccountReport(result.stdout ?? '', email); + const refusal = ownerLockoutRefusal(plan, account); + if (refusal) throw new Error(refusal); + if (!account) throw new Error(`no account for ${email} after the command; nothing was created`); + if (account.status === 'suspended') { + log(`note: ${email} is suspended; an administrator must reactivate it in Admin → Users`); + } + log(`done: ${email} can now request a sign-in code at https://app.${box.SAM_DOMAIN ?? ''}`); + // Until the installer owner has signed in once, SAM admits no one else (bootstrap-owner.ts). + if (owner && owner.toLowerCase() !== email) { + log(`note: BOOTSTRAP_OWNER_EMAIL is set; if ${owner} has not signed in yet, only they can`); + } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch((error: unknown) => { + console.error(`[selfhost] ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); + }); +} diff --git a/scripts/selfhost/deploy-harness.ts b/scripts/selfhost/deploy-harness.ts new file mode 100644 index 0000000000..4ea0882283 --- /dev/null +++ b/scripts/selfhost/deploy-harness.ts @@ -0,0 +1,56 @@ +/** + * Test harness: runs the real `pnpm selfhost:deploy` entry (deploy.ts) as a child process on a + * throwaway `.env`, exactly as an operator does. + */ +import { spawn } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +const DEPLOY = resolve(import.meta.dirname, 'deploy.ts'); +/** The repository's own tsx, not `npx tsx` (npx resolution costs seconds under load). */ +const TSX = resolve(import.meta.dirname, '../../node_modules/.bin/tsx'); +/** Per-test timeout for files that start these child processes. */ +export const CHILD_TEST_TIMEOUT_MS = 120_000; + +export const BASE_BOX_ENV = [ + 'SAM_DOMAIN=sam.example.com', + 'SAM_TLS_MODE=internal', + 'COMPOSE_PROFILES=tunnel,local-store', + 'CELLD_BUCKET=s3://fleet/celld', + 'S3_ENDPOINT=http://127.0.0.1:9000', + 'AWS_ACCESS_KEY_ID=fleet-key', + 'AWS_SECRET_ACCESS_KEY=fleet-secret-0123456789', +]; + +export function writeBox(dir: string, extra: string[] = []): string { + const envFile = join(dir, '.env'); + writeFileSync(envFile, `${[...BASE_BOX_ENV, ...extra].join('\n')}\n`, { mode: 0o600 }); + return envFile; +} + +export function runTsx( + script: string, + args: string[], + env: NodeJS.ProcessEnv = {} +): Promise<{ status: number; out: string }> { + return new Promise((done, fail) => { + const child = spawn(TSX, [script, ...args], { env: { ...process.env, ...env } }); + let out = ''; + child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString())); + child.stderr.on('data', (chunk: Buffer) => (out += chunk.toString())); + const timer = setTimeout(() => child.kill('SIGKILL'), 90_000); + child.on('error', fail); + child.on('close', (code) => { + clearTimeout(timer); + done({ status: code ?? 1, out }); + }); + }); +} + +export function runDeploy( + envFile: string, + args: string[], + env: NodeJS.ProcessEnv = {} +): Promise<{ status: number; out: string }> { + return runTsx(DEPLOY, ['--env-file', envFile, ...args], env); +} diff --git a/scripts/selfhost/deploy-health.test.ts b/scripts/selfhost/deploy-health.test.ts new file mode 100644 index 0000000000..7ae1588d88 --- /dev/null +++ b/scripts/selfhost/deploy-health.test.ts @@ -0,0 +1,68 @@ +/** + * waitForHealth (deploy-steps.ts) against a real HTTP server on loopback. On sam-box a health + * request that celld dispatched to a stuck fresh isolate hung for celld's whole handler budget, + * outlived the deploy's deadline and failed a deploy whose Worker answered every other request. + */ +import { createServer, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { waitForHealth } from './deploy-steps'; + +let server: Server; +let port: string; +let requests: number; +let hangFirst: number; +let held: ServerResponse[]; +const saved = { ...process.env }; + +beforeEach(async () => { + requests = 0; + held = []; + server = createServer((_req, res) => { + requests += 1; + if (requests <= hangFirst) { + held.push(res); // never answered: a request stuck in a fresh isolate + return; + } + res.writeHead(200).end('ok'); + }); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + port = String((server.address() as AddressInfo).port); + process.env.SELFHOST_HEALTH_TIMEOUT_MS = '5000'; + process.env.SELFHOST_HEALTH_REQUEST_TIMEOUT_MS = '200'; + process.env.SELFHOST_HEALTH_POLL_INTERVAL_MS = '20'; +}); + +afterEach(async () => { + for (const res of held) res.destroy(); + server.closeAllConnections(); + await new Promise((done) => server.close(() => done())); + process.env = { ...saved }; +}); + +describe('waitForHealth', () => { + it('abandons a request that never answers and succeeds on the next one', async () => { + hangFirst = 1; + const started = Date.now(); + await waitForHealth(port, 'box.example'); + expect(requests).toBe(2); + expect(Date.now() - started).toBeLessThan(2000); + }); + + it('still fails when every request hangs, within the overall deadline', async () => { + hangFirst = Number.MAX_SAFE_INTEGER; + process.env.SELFHOST_HEALTH_TIMEOUT_MS = '700'; + const started = Date.now(); + await expect(waitForHealth(port, 'box.example')).rejects.toThrow(/did not become healthy/); + expect(requests).toBeGreaterThanOrEqual(2); + expect(Date.now() - started).toBeLessThan(2000); + }); + + it('returns at once when the first request answers 200 (control)', async () => { + hangFirst = 0; + await waitForHealth(port, 'box.example'); + expect(requests).toBe(1); + }); +}); diff --git a/scripts/selfhost/deploy-plaintext.test.ts b/scripts/selfhost/deploy-plaintext.test.ts new file mode 100644 index 0000000000..650eb78530 --- /dev/null +++ b/scripts/selfhost/deploy-plaintext.test.ts @@ -0,0 +1,118 @@ +/** + * `pnpm selfhost:deploy --init` and `--dry-run` run as child processes on a throwaway `.env` and + * `.state/`, exactly as an operator runs them (deploy-harness.ts). This is the plaintext path end to + * end, short of `celld deploy`: --init generates the platform keys and gateway.env once, and the + * config celld would store carries every secret as a Worker var, redacted in the printed copy. + */ +import { randomBytes } from 'node:crypto'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { CHILD_TEST_TIMEOUT_MS, runDeploy, writeBox } from './deploy-harness.js'; +import { PLATFORM_KEY_NAMES, PLATFORM_KEYS_FILE } from './platform-keys.js'; + +// Generated per run so no secret-shaped literal sits in the tree. +const OPERATOR_SECRET = randomBytes(16).toString('hex'); +let dir: string; +let state: string; + +function writeSecrets(lines: string[]): void { + writeFileSync(join(state, 'secrets.env'), `${lines.join('\n')}\n`, { mode: 0o600 }); +} + +async function dryRun(envFile: string): Promise<{ out: string; config: Record }> { + const result = await runDeploy(envFile, ['--dry-run', '--skip-vm-agent']); + expect(result.status, result.out).toBe(0); + return { + out: result.out, + config: JSON.parse(result.out.slice(result.out.indexOf('{\n'))) as Record, + }; +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'sam-deploy-')); + state = join(dir, '.state'); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('selfhost:deploy, plaintext', { timeout: CHILD_TEST_TIMEOUT_MS }, () => { + it('--init writes the platform keys and gateway.env once; --dry-run renders them as redacted vars', async () => { + const envFile = writeBox(dir); + const init = await runDeploy(envFile, ['--init']); + expect(init.status, init.out).toBe(0); + const keysPath = join(state, PLATFORM_KEYS_FILE); + expect(statSync(keysPath).mode & 0o777).toBe(0o600); + const keys = JSON.parse(readFileSync(keysPath, 'utf8')) as Record; + expect(Object.keys(keys).sort()).toEqual([...PLATFORM_KEY_NAMES].sort()); + expect(readFileSync(join(state, 'gateway.env'), 'utf8')).toContain( + keys.REVERSE_TUNNEL_GATEWAY_SECRET + ); + + // A second --init keeps every key. + const before = readFileSync(keysPath, 'utf8'); + expect((await runDeploy(envFile, ['--init'])).status).toBe(0); + expect(readFileSync(keysPath, 'utf8')).toBe(before); + + writeSecrets([`GITHUB_CLIENT_SECRET=${OPERATOR_SECRET}`]); + const { out, config } = await dryRun(envFile); + const vars = config.vars as Record; + for (const name of PLATFORM_KEY_NAMES.filter((n) => n !== 'SAM_INSTALLATION_ID')) { + expect(vars[name], name).toBe(''); + expect(out).not.toContain(keys[name]); + } + expect(vars.GITHUB_CLIENT_SECRET).toBe(''); + expect(out).not.toContain(OPERATOR_SECRET); + // An identifier, not a secret: the ownership label every node VM carries. + expect(vars.SAM_INSTALLATION_ID).toBe(keys.SAM_INSTALLATION_ID); + expect(vars.ENVIRONMENT).toBe('selfhost'); + expect(vars.BASE_DOMAIN).toBe('sam.example.com'); + // The plaintext path is the only one: no key agent, no containers. + expect(Object.keys(vars).filter((name) => name.startsWith('SAM_KEY_'))).toEqual([]); + expect(config).not.toHaveProperty('containers'); + expect(config.main).toBe('celld-main.ts'); + }); + + it('refuses a state dir whose platform keys are sealed, and writes no new keys', async () => { + const envFile = writeBox(dir); + mkdirSync(join(state, 'key-agent', 'bundles'), { recursive: true }); + writeFileSync(join(state, 'key-agent', 'bundles', 'b1.json'), '{}'); + const result = await runDeploy(envFile, ['--init']); + expect(result.status).toBe(1); + expect(result.out).toContain('platform keys are sealed'); + expect(existsSync(join(state, PLATFORM_KEYS_FILE))).toBe(false); + }); + + it('refuses an s3:// operator store without R2_S3_REGION, and passes one through', async () => { + const endpoint = 'R2_S3_ENDPOINT=https://s3.example.com'; + const without = writeBox(dir, [endpoint]); + expect((await runDeploy(without, ['--init'])).status).toBe(0); + const refused = await runDeploy(without, ['--dry-run', '--skip-vm-agent']); + expect(refused.status).toBe(1); + expect(refused.out).toContain('R2_S3_REGION is required'); + + const withRegion = writeBox(dir, [endpoint, 'R2_S3_REGION=us-east-1']); + const vars = (await dryRun(withRegion)).config.vars as Record; + expect(vars.R2_S3_REGION).toBe('us-east-1'); + expect(vars.R2_S3_ENDPOINT).toBe('https://s3.example.com'); + }); + + it('refuses secrets.env setting a var the deployment generates', async () => { + const envFile = writeBox(dir); + expect((await runDeploy(envFile, ['--init'])).status).toBe(0); + writeSecrets(['VM_AGENT_REQUIRED_VERSION=pinned-by-hand']); + const result = await runDeploy(envFile, ['--dry-run', '--skip-vm-agent']); + expect(result.status).toBe(1); + expect(result.out).toContain('VM_AGENT_REQUIRED_VERSION is generated'); + }); +}); diff --git a/scripts/selfhost/deploy-steps.ts b/scripts/selfhost/deploy-steps.ts new file mode 100644 index 0000000000..9e3a6f8541 --- /dev/null +++ b/scripts/selfhost/deploy-steps.ts @@ -0,0 +1,148 @@ +/** + * Small steps of `pnpm selfhost:deploy` (deploy.ts), kept apart so the orchestration stays short. + */ +import { existsSync, readFileSync } from 'node:fs'; + +import { gatewayEnvAction } from './box-settings.js'; +import type { CelldWranglerConfig } from './celld-config.js'; +import { writePrivateFile } from './secret-files.js'; + +function log(message: string): void { + console.log(`[selfhost] ${message}`); +} + +export function redact(config: CelldWranglerConfig, secretNames: Set): CelldWranglerConfig { + const vars = Object.fromEntries( + Object.entries(config.vars).map(([key, value]) => [ + key, + secretNames.has(key) ? '' : value, + ]) + ); + return { ...config, vars }; +} + +/** + * Write gateway.env (frps and Caddy read it via env_file) when it changed. Outside `--init` a + * change stops the deploy before the Worker is updated: frps reads the file only when it starts, + * so the Worker must not assume a heartbeat timeout or range the running frps is not enforcing. + */ +export function syncGatewayEnv(path: string, content: string, init: boolean): void { + const existing = existsSync(path) ? readFileSync(path, 'utf8') : null; + const action = gatewayEnvAction(existing, content, init); + if (action === 'unchanged') return; + writePrivateFile(path, content); + log(`wrote ${path}; (re)start the stack: docker compose up -d`); + if (action === 'write-then-restart') { + throw new Error( + `${path} changed. Restart frps and Caddy so they run it (docker compose up -d), ` + + 'then run pnpm selfhost:deploy again; the Worker is not updated before they agree.' + ); + } +} + +/** Runs a command with secret values scrubbed from its printed output (deploy.ts `run`). */ +export type RunCommand = ( + command: string, + args: string[], + env: NodeJS.ProcessEnv +) => { status: number; output: string }; + +const NO_LEASES = /no node leases/i; + +/** Attempts while the freshly deployed node takes its leases. */ +export const DEFAULT_MIGRATION_ATTEMPTS = 20; +/** Attempts before the deploy; an upgraded fleet answers at once, a fresh one never does. */ +export const DEFAULT_PREDEPLOY_MIGRATION_ATTEMPTS = 2; +const DEFAULT_MIGRATION_RETRY_DELAY_MS = 3000; +const DEFAULT_HEALTH_TIMEOUT_MS = 120_000; +const DEFAULT_HEALTH_POLL_INTERVAL_MS = 2000; +/** + * One health request's limit. Without it a request that celld dispatches to a stuck fresh isolate + * waits out celld's 300 s handler budget, so a single probe outlives the whole deadline and the + * deploy fails on a box that answered every other request (sam-box, 2026-11-12). + */ +const DEFAULT_HEALTH_REQUEST_TIMEOUT_MS = 10_000; + +export function intEnv(name: string, fallback: number): number { + const raw = process.env[name]; + const parsed = raw ? Number.parseInt(raw, 10) : NaN; + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback; +} + +export function sleep(ms: number): Promise { + return new Promise((done) => setTimeout(done, ms)); +} + +export function bucketOf(env: NodeJS.ProcessEnv): string { + const bucket = env.CELLD_BUCKET; + if (!bucket) throw new Error('CELLD_BUCKET is not set'); + return bucket; +} + +/** + * Applies one database's migrations. `celld d1` talks to a node holding a lease, and a node + * takes leases only once a Worker is deployed, so on a fresh fleet this reports `no-leases` + * instead of failing; the caller deploys and retries. Other failures throw. + */ +async function applyMigrations( + run: RunCommand, + celld: string, + databaseName: string, + projectDir: string, + env: NodeJS.ProcessEnv, + attempts: number +): Promise<'applied' | 'no-leases'> { + const delay = intEnv('SELFHOST_MIGRATION_RETRY_DELAY_MS', DEFAULT_MIGRATION_RETRY_DELAY_MS); + for (let attempt = 1; ; attempt += 1) { + log(`applying D1 migrations: ${databaseName} (attempt ${attempt}/${attempts})`); + const result = run( + celld, + ['d1', 'migrations', 'apply', databaseName, projectDir, '--bucket', bucketOf(env)], + env + ); + if (result.status === 0) return 'applied'; + if (!NO_LEASES.test(result.output)) { + throw new Error(`celld d1 migrations apply ${databaseName} failed (exit ${result.status})`); + } + if (attempt >= attempts) return 'no-leases'; + await sleep(delay); + } +} + +export async function applyAllMigrations( + run: RunCommand, + celld: string, + databases: readonly string[], + projectDir: string, + env: NodeJS.ProcessEnv, + attempts: number +): Promise<'applied' | 'no-leases'> { + for (const name of databases) { + if ((await applyMigrations(run, celld, name, projectDir, env, attempts)) === 'no-leases') + return 'no-leases'; + } + return 'applied'; +} + +export async function waitForHealth(port: string, baseDomain: string): Promise { + const deadline = Date.now() + intEnv('SELFHOST_HEALTH_TIMEOUT_MS', DEFAULT_HEALTH_TIMEOUT_MS); + const requestTimeout = intEnv( + 'SELFHOST_HEALTH_REQUEST_TIMEOUT_MS', + DEFAULT_HEALTH_REQUEST_TIMEOUT_MS + ); + let last = 'no response'; + while (Date.now() < deadline) { + try { + const response = await fetch(`http://127.0.0.1:${port}/health`, { + headers: { host: `api.${baseDomain}`, 'x-forwarded-proto': 'https' }, + signal: AbortSignal.timeout(Math.max(1, Math.min(requestTimeout, deadline - Date.now()))), + }); + if (response.ok) return; + last = `HTTP ${response.status}`; + } catch (error) { + last = error instanceof Error ? error.message : String(error); + } + await sleep(intEnv('SELFHOST_HEALTH_POLL_INTERVAL_MS', DEFAULT_HEALTH_POLL_INTERVAL_MS)); + } + throw new Error(`API Worker did not become healthy on 127.0.0.1:${port}: ${last}`); +} diff --git a/scripts/selfhost/deploy.ts b/scripts/selfhost/deploy.ts new file mode 100644 index 0000000000..10eef5598b --- /dev/null +++ b/scripts/selfhost/deploy.ts @@ -0,0 +1,354 @@ +#!/usr/bin/env tsx +/** + * Deploy (or upgrade) the SAM control plane onto a running celld node. + * + * pnpm selfhost:deploy [--env-file deploy/selfhost/.env] [--state-dir /.state] + * [--secrets /secrets.env] [--web-dist DIR] [--dry-run] [--init] + * [--skip-vm-agent] + * + * `--init` generates the platform keys (`/platform-keys.json`, platform-keys.ts), and + * writes `/gateway.env` (the shared secret docker compose hands to frps and Caddy) and + * the mail-collector files; run it once before the first `docker compose up`. + * + * Re-runnable: platform keys are generated once and kept, the project directory is rebuilt, + * D1 migrations are applied idempotently, and `celld deploy` publishes a new version that the + * node adopts in place. celld has no secrets store for real nodes: the platform keys and + * secrets.env are rendered into the Worker's `vars`, which celld keeps in the fleet bucket. The + * fleet bucket credential can therefore read every Worker secret. + * + * Nodes download the vm-agent from this install, so the deploy builds it (pinned Go image) and + * publishes it into the fleet bucket the way the Cloudflare pipeline does, then pins + * VM_AGENT_REQUIRED_VERSION to that release. `--skip-vm-agent` skips both and leaves the + * version unpinned (nodes then use the legacy `agents/vm-agent-linux-` objects). + * + * Email (mail-settings.ts): the Worker gets SMTP settings from the .env, or points at the + * `mail-collector` profile, whose UI password only `--init` generates; run `--init` again after + * turning that profile on. + * + * The Cloudflare pipeline never runs this script. + */ + +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; + +import * as TOML from '@iarna/toml'; + +import type { WranglerToml } from '../deploy/types.js'; +import { + assertPresignCredentialIsScoped, + celldChildEnv, + presignVars, + redactSecrets, + renderGatewayEnv, + resolveTunnelSettings, + tunnelWorkerVars, +} from './box-settings.js'; +import { verifyNewVersionServes } from './celld-adopt.js'; +import { ensureCelldBinary, resolveEsbuild } from './celld-binary.js'; +import { + assertOperatorSecretsAllowed, + buildCelldConfig, + type CelldWranglerConfig, +} from './celld-config.js'; +import { ASSETS_DIR, CELLD_MAIN, prepareCelldProject, writeCelldConfig } from './celld-project.js'; +import { + applyAllMigrations, + bucketOf, + DEFAULT_MIGRATION_ATTEMPTS, + DEFAULT_PREDEPLOY_MIGRATION_ATTEMPTS, + intEnv, + redact, + syncGatewayEnv, +} from './deploy-steps.js'; +import { inboundMailWorkerVars } from './inbound-mail-settings.js'; +import { + ensureMailCollectorPassword, + MAIL_COLLECTOR_PASSWORD_FILE, + MAIL_COLLECTOR_UI_USER, + mailCollectorHostLabel, + smtpWorkerVars, + writeMailCollectorFiles, +} from './mail-settings.js'; +import { ensurePlatformKeys } from './platform-keys.js'; +import { + assertPrivateFile, + ensurePrivateDir, + parseDotenv, + readSecretsFile, +} from './secret-files.js'; +import { + buildVmAgentBinaries, + publishVmAgentArtifacts, + removeVmAgentBuild, + resolveVmAgentRelease, +} from './vm-agent-artifacts.js'; + +const REPO_ROOT = resolve(import.meta.dirname, '../..'); +const API_DIR = join(REPO_ROOT, 'apps/api'); +const WEB_DIR = join(REPO_ROOT, 'apps/web'); + +/** Upper bound on captured celld output (bundle reports are a few KiB). */ +const CHILD_OUTPUT_MAX_BYTES = 64 * 1024 * 1024; +const DEFAULT_CELLD_PORT = '8080'; + +function log(message: string): void { + console.log(`[selfhost] ${message}`); +} + +interface RunResult { + status: number; + output: string; +} + +/** Secret values scrubbed from any child output before it is printed. */ +let knownSecrets: string[] = []; + +/** Runs a command, printing its output (with secret values scrubbed) and capturing it. */ +function run(command: string, args: string[], env: NodeJS.ProcessEnv, cwd = REPO_ROOT): RunResult { + const result = spawnSync(command, args, { + cwd, + env, + encoding: 'utf8', + maxBuffer: CHILD_OUTPUT_MAX_BYTES, + }); + const output = redactSecrets(`${result.stdout ?? ''}${result.stderr ?? ''}`, knownSecrets); + process.stdout.write(output); + if (result.error) throw result.error; + return { status: result.status ?? 1, output }; +} + +function buildWeb(baseDomain: string): string { + log(`building apps/web for https://api.${baseDomain}`); + const env = { ...process.env, VITE_API_URL: `https://api.${baseDomain}` }; + const result = spawnSync( + 'pnpm', + ['exec', 'turbo', 'run', 'build', '--filter=@simple-agent-manager/web'], + { + cwd: REPO_ROOT, + env, + stdio: 'inherit', + } + ); + if (result.status !== 0) throw new Error('apps/web build failed'); + return join(WEB_DIR, 'dist'); +} + +/** + * celld bundles `apps/api/src` with its own esbuild, which resolves the workspace packages + * (`shared`, `providers`, `cloud-init`) through their built `dist/` entry points. A fresh + * checkout has none, so build the API's dependencies (not the API itself) first. + */ +function buildApiDependencies(): void { + log("building the API Worker's workspace dependencies"); + const result = spawnSync( + 'pnpm', + ['exec', 'turbo', 'run', 'build', '--filter=@simple-agent-manager/api^...'], + { cwd: REPO_ROOT, stdio: 'inherit' } + ); + if (result.status !== 0) throw new Error('building the API Worker dependencies failed'); +} + +async function main(): Promise { + const { values } = parseArgs({ + options: { + 'env-file': { type: 'string' }, + 'state-dir': { type: 'string' }, + secrets: { type: 'string' }, + 'web-dist': { type: 'string' }, + 'dry-run': { type: 'boolean', default: false }, + init: { type: 'boolean', default: false }, + 'skip-vm-agent': { type: 'boolean', default: false }, + }, + }); + const envFile = resolve(values['env-file'] ?? join(REPO_ROOT, 'deploy/selfhost/.env')); + // The .env holds the bucket credential, which can read every deployed secret. + assertPrivateFile(envFile); + const box = parseDotenv(readFileSync(envFile, 'utf8'), envFile); + // Same default and base directory docker compose uses for SAM_SELFHOST_STATE_DIR. + const stateDir = resolve( + dirname(envFile), + values['state-dir'] ?? box.SAM_SELFHOST_STATE_DIR ?? '.state' + ); + ensurePrivateDir(stateDir); + const secretsPath = resolve(values.secrets ?? join(stateDir, 'secrets.env')); + const projectDir = join(stateDir, 'project'); + const baseDomain = box.SAM_DOMAIN; + if (!baseDomain) throw new Error(`${envFile}: SAM_DOMAIN is required`); + if (!box.CELLD_BUCKET) throw new Error(`${envFile}: CELLD_BUCKET is required`); + + const { keys, generated } = ensurePlatformKeys(stateDir); + if (generated.length > 0) { + log(`generated platform keys: ${generated.join(', ')} (back up ${stateDir})`); + } + // docker compose passes this file to frps and Caddy (env_file); rewritten only on change. + // The port range and heartbeat timeout go to the Worker from the same resolved values + // (below). Resolution fails the deploy on a range overlapping a box listener or too large. + const tunnelSettings = resolveTunnelSettings(box); + syncGatewayEnv( + join(stateDir, 'gateway.env'), + renderGatewayEnv(keys.REVERSE_TUNNEL_GATEWAY_SECRET, tunnelSettings), + values.init ?? false + ); + // The collector's UI password (generated by --init only) and Caddy's view of the collector. + const collectorPasswordPath = join(stateDir, MAIL_COLLECTOR_PASSWORD_FILE); + const collectorPassword = ensureMailCollectorPassword( + collectorPasswordPath, + box, + values.init ?? false + ); + for (const path of writeMailCollectorFiles(stateDir, box, collectorPassword)) { + log(`wrote ${path}; restart the stack so it applies: docker compose up -d`); + } + if (values.init) return; + const operatorSecrets = readSecretsFile(secretsPath); + // VM_AGENT_REQUIRED_VERSION must name the release this deploy published (or stay unset). + assertOperatorSecretsAllowed(operatorSecrets, secretsPath); + assertPresignCredentialIsScoped(box, operatorSecrets); + const { SAM_INSTALLATION_ID, ...platformSecrets } = keys; + // What the Worker runs with, rendered into its `vars` below (secrets.env wins over the keys). + const secrets: Record = { ...platformSecrets, ...operatorSecrets }; + knownSecrets = Object.values(secrets); + + const smtpVars = smtpWorkerVars(box, secrets, baseDomain); + const source = TOML.parse(readFileSync(join(API_DIR, 'wrangler.toml'), 'utf8')) as WranglerToml; + const plan = buildCelldConfig(source, { + main: CELLD_MAIN, + baseDomain, + assetsDirectory: ASSETS_DIR, + vars: { + SAM_INSTALLATION_ID, + VAPID_SUBJECT: `https://app.${baseDomain}`, + ...tunnelWorkerVars(tunnelSettings), + ...smtpVars, + ...inboundMailWorkerVars(box, smtpVars), + }, + }); + const vmAgentRelease = values['skip-vm-agent'] ? null : resolveVmAgentRelease(REPO_ROOT); + if (vmAgentRelease) plan.config.vars.VM_AGENT_REQUIRED_VERSION = vmAgentRelease.release; + // Needs the R2 binding's final bucket name, so it is applied after translation. + Object.assign(plan.config.vars, presignVars(box, plan.config.vars.R2_BUCKET_NAME ?? '')); + for (const line of plan.report) log(line); + // What `celld deploy` gets, and celld stores in the fleet bucket for this version. Only this + // in-memory copy and a transient project file (below) carry the secrets. + const withSecrets: CelldWranglerConfig = { + ...plan.config, + vars: { ...plan.config.vars, ...secrets }, + }; + + if (values['dry-run']) { + console.log(JSON.stringify(redact(withSecrets, new Set(Object.keys(secrets))), null, 2)); + return; + } + + let vmAgentBinDir: string | null = null; + if (vmAgentRelease) { + log(`building vm-agent release ${vmAgentRelease.release}`); + vmAgentBinDir = buildVmAgentBinaries(REPO_ROOT, join(stateDir, 'go-cache'), vmAgentRelease); + } + const webDist = values['web-dist'] ? resolve(values['web-dist']) : buildWeb(baseDomain); + buildApiDependencies(); + prepareCelldProject({ apiDir: API_DIR, projectDir, plan, webDist }); + + const celld = await ensureCelldBinary(join(stateDir, 'bin')); + const env = celldChildEnv(process.env, box, resolveEsbuild(API_DIR)); + + // Before the Worker that pins VM_AGENT_REQUIRED_VERSION is published, as on Cloudflare. + if (vmAgentRelease && vmAgentBinDir) { + const agentBucket = plan.config.r2_buckets.find((bucket) => bucket.binding === 'R2'); + if (!agentBucket) throw new Error('the Worker has no R2 binding to serve the vm-agent from'); + try { + publishVmAgentArtifacts({ + celld, + env, + fleetBucket: bucketOf(env), + r2BucketName: agentBucket.bucket_name, + binDir: vmAgentBinDir, + release: vmAgentRelease.release, + redact: (text) => redactSecrets(text, knownSecrets), + log, + }); + } finally { + removeVmAgentBuild(vmAgentBinDir); + } + } + + // The secrets-free config is what stays on disk: migrations and operator `celld d1`/`kv` + // commands read it. On an upgrade, migrations run before the new Worker version, as on + // Cloudflare. A fresh fleet has no leases until its first deploy, so it migrates after. + writeCelldConfig(projectDir, plan.config); + const databases = plan.config.d1_databases.map((db) => db.database_name); + const preDeploy = await applyAllMigrations( + run, + celld, + databases, + projectDir, + env, + intEnv('SELFHOST_PREDEPLOY_MIGRATION_ATTEMPTS', DEFAULT_PREDEPLOY_MIGRATION_ATTEMPTS) + ); + if (preDeploy === 'no-leases') + log('no node holds a lease yet (first deploy?); deploying before migrating'); + + // spawnSync blocks the event loop, so a signal lands here after celld exits; `finally` + // alone would not run on one. A SIGKILL or power loss can still leave the secrets-bearing + // file until the next run rewrites it; it is 0600 in the 0700 state dir, which already holds + // the same values in platform-keys.json and secrets.env. + const signals = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'] as const; + const scrub = (): void => { + try { + writeCelldConfig(projectDir, plan.config); + } catch (error) { + console.error(`[selfhost] could not scrub ${projectDir}/wrangler.json: ${String(error)}`); + } + process.exit(130); + }; + for (const signal of signals) process.once(signal, scrub); + writeCelldConfig(projectDir, withSecrets); + try { + log(`celld deploy ${plan.config.name}`); + const result = run(celld, ['deploy', projectDir, '--bucket', bucketOf(env)], env); + if (result.status !== 0) throw new Error(`celld deploy failed (exit ${result.status})`); + } finally { + writeCelldConfig(projectDir, plan.config); + for (const signal of signals) process.off(signal, scrub); + } + + if (preDeploy === 'no-leases') { + const migrated = await applyAllMigrations( + run, + celld, + databases, + projectDir, + env, + intEnv('SELFHOST_MIGRATION_ATTEMPTS', DEFAULT_MIGRATION_ATTEMPTS) + ); + if (migrated === 'no-leases') { + throw new Error('no celld node holds a lease; is the stack running (docker compose ps)?'); + } + } + + // celld reads deploy/current.json only every CELLD_DEPLOY_POLL_S (30 s); without this the + // health check below passed on the previous version (box round R15, G3). celld-adopt.ts. + await verifyNewVersionServes( + box, + { + celldPort: box.CELLD_PORT || DEFAULT_CELLD_PORT, + baseDomain, + agentSignInConfigured: Boolean(secrets.AGENT_SIGN_IN_TRUST?.trim()), + }, + log + ); + log(`deployed: https://app.${baseDomain} (API https://api.${baseDomain})`); + if (collectorPassword) { + log( + `mail collector: https://${mailCollectorHostLabel(box)}.${baseDomain} ` + + `(user ${MAIL_COLLECTOR_UI_USER}, password in ${collectorPasswordPath})` + ); + } +} + +main().catch((error: unknown) => { + console.error(`[selfhost] ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); +}); diff --git a/scripts/selfhost/inbound-mail-settings.test.ts b/scripts/selfhost/inbound-mail-settings.test.ts new file mode 100644 index 0000000000..8e2b340344 --- /dev/null +++ b/scripts/selfhost/inbound-mail-settings.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; + +import { inboundMailEnabled, inboundMailWorkerVars } from './inbound-mail-settings.js'; +import { smtpWorkerVars } from './mail-settings.js'; + +describe('inbound agent email settings', () => { + it('is off unless the mail-in profile is on', () => { + const box = { COMPOSE_PROFILES: 'tunnel,gce' }; + expect(inboundMailEnabled(box)).toBe(false); + expect(inboundMailWorkerVars(box, {})).toEqual({}); + }); + + it('turns agent email on with the mail collector as the reply transport', () => { + const box = { COMPOSE_PROFILES: 'tunnel, mail-in ,mail-collector' }; + const smtp = smtpWorkerVars(box, {}, 'box.example'); + expect(inboundMailWorkerVars(box, smtp)).toEqual({ AGENT_EMAIL_INBOUND_SMTP: 'true' }); + }); + + it('turns agent email on with a real relay', () => { + const box = { + COMPOSE_PROFILES: 'mail-in', + SMTP_HOST: 'smtp.example.com', + SMTP_USERNAME: 'sam', + SMTP_FROM: 'sam@box.example', + }; + const smtp = smtpWorkerVars(box, { SMTP_PASSWORD: 'pw' }, 'box.example'); + expect(inboundMailWorkerVars(box, smtp)).toEqual({ AGENT_EMAIL_INBOUND_SMTP: 'true' }); + }); + + it('refuses the profile without an SMTP transport for replies', () => { + const box = { COMPOSE_PROFILES: 'mail-in' }; + expect(() => inboundMailWorkerVars(box, smtpWorkerVars(box, {}, 'box.example'))).toThrow( + /needs an SMTP relay/ + ); + }); +}); diff --git a/scripts/selfhost/inbound-mail-settings.ts b/scripts/selfhost/inbound-mail-settings.ts new file mode 100644 index 0000000000..8e38730268 --- /dev/null +++ b/scripts/selfhost/inbound-mail-settings.ts @@ -0,0 +1,32 @@ +/** + * Inbound agent email for a celld box: the `mail-in` compose profile runs sam-mx + * (deploy/selfhost/sam-mx), an SMTP receiver on port 25 that hands agent mail to the Worker's + * loopback gateway route. The Worker turns agent email on only when the deploy tells it the + * receiver is installed (AGENT_EMAIL_INBOUND_SMTP, apps/api/src/services/agent-email/ + * self-host-inbound.ts), and replies need an SMTP transport, so the profile without one is refused + * here rather than deploying addresses whose agents cannot answer. + */ +import { composeProfiles } from './mail-settings.js'; + +export const MAIL_IN_PROFILE = 'mail-in'; + +type Box = Readonly>; + +export function inboundMailEnabled(box: Box): boolean { + return composeProfiles(box).includes(MAIL_IN_PROFILE); +} + +/** Worker vars for inbound agent email ({} when the profile is off). */ +export function inboundMailWorkerVars( + box: Box, + smtpVars: Readonly> +): Record { + if (!inboundMailEnabled(box)) return {}; + if (!smtpVars.SMTP_HOST) { + throw new Error( + `the ${MAIL_IN_PROFILE} profile needs an SMTP relay for agent replies: set SMTP_HOST ` + + '(or, on a test install, add mail-collector to COMPOSE_PROFILES)' + ); + } + return { AGENT_EMAIL_INBOUND_SMTP: 'true' }; +} diff --git a/scripts/selfhost/mail-settings.test.ts b/scripts/selfhost/mail-settings.test.ts new file mode 100644 index 0000000000..5c2d851e39 --- /dev/null +++ b/scripts/selfhost/mail-settings.test.ts @@ -0,0 +1,229 @@ +import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { resolveTunnelPortRange } from './box-settings.js'; +import { + ensureMailCollectorPassword, + mailCollectorEnabled, + mailCollectorPorts, + renderMailCollectorEnv, + smtpWorkerVars, + writeMailCollectorFiles, +} from './mail-settings.js'; + +const DOMAIN = 'sam.example.com'; +const COLLECTOR = { COMPOSE_PROFILES: 'tunnel, mail-collector' }; +const RELAY = { + SMTP_HOST: 'smtp.example.com', + SMTP_USERNAME: 'relay-user', + SMTP_FROM: `sign-in@${DOMAIN}`, +}; + +describe('smtpWorkerVars', () => { + it('gives the Worker no SMTP settings when the box sends no email (unchanged default)', () => { + expect(smtpWorkerVars({ COMPOSE_PROFILES: 'tunnel' }, {}, DOMAIN)).toEqual({}); + }); + + it('points the Worker at the loopback collector when the profile is on', () => { + expect(smtpWorkerVars(COLLECTOR, {}, DOMAIN)).toEqual({ + SMTP_HOST: '127.0.0.1', + SMTP_PORT: '1025', + SMTP_TLS: 'none', + SMTP_FROM: `sign-in@${DOMAIN}`, + }); + expect( + smtpWorkerVars( + { ...COLLECTOR, MAIL_COLLECTOR_SMTP_PORT: '2525', SMTP_FROM: 'a@b.example' }, + {}, + DOMAIN + ) + ).toMatchObject({ SMTP_PORT: '2525', SMTP_FROM: 'a@b.example' }); + }); + + it('passes a relay through and validates it with the Worker parser, password from secrets.env', () => { + expect(smtpWorkerVars(RELAY, { SMTP_PASSWORD: 'relay-pass' }, DOMAIN)).toEqual(RELAY); + expect(() => smtpWorkerVars(RELAY, {}, DOMAIN)).toThrow( + 'SMTP settings: SMTP_USERNAME and SMTP_PASSWORD must be set together' + ); + expect(() => + smtpWorkerVars( + { ...RELAY, SMTP_TLS: 'none', SMTP_PORT: '25' }, + { SMTP_PASSWORD: 'x' }, + DOMAIN + ) + ).toThrow('SMTP_TLS=none is allowed only for a loopback SMTP_HOST'); + }); + + it('refuses a relay and the collector together, and a password in the compose .env', () => { + expect(() => + smtpWorkerVars({ ...COLLECTOR, ...RELAY }, { SMTP_PASSWORD: 'p' }, DOMAIN) + ).toThrow('choose one place for sign-in codes'); + expect(() => smtpWorkerVars({ ...RELAY, SMTP_PASSWORD: 'p' }, {}, DOMAIN)).toThrow( + 'SMTP_PASSWORD is a secret' + ); + }); +}); + +describe('mail collector profile', () => { + it('is on only when COMPOSE_PROFILES names it exactly', () => { + expect(mailCollectorEnabled(COLLECTOR)).toBe(true); + expect(mailCollectorEnabled({ COMPOSE_PROFILES: 'tunnel,mail-collector-x' })).toBe(false); + expect(mailCollectorEnabled({})).toBe(false); + }); + + it('keeps node lease ranges off the collector ports even with the collector off', () => { + expect(() => + resolveTunnelPortRange({ + REVERSE_TUNNEL_PORT_RANGE_START: '8020', + REVERSE_TUNNEL_PORT_RANGE_END: '8030', + }) + ).toThrow('MAIL_COLLECTOR_UI_PORT (8025)'); + expect(() => + resolveTunnelPortRange({ + REVERSE_TUNNEL_PORT_RANGE_START: '1024', + REVERSE_TUNNEL_PORT_RANGE_END: '1100', + }) + ).toThrow('MAIL_COLLECTOR_SMTP_PORT (1025)'); + }); +}); + +describe('collector UI password', () => { + let dir: string; + let path: string; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'sam-mail-')); + path = join(dir, 'mail-collector-ui-password'); + }); + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + it('is generated by --init only, kept afterwards, and private', () => { + expect(() => ensureMailCollectorPassword(path, COLLECTOR, false)).toThrow( + 'run pnpm selfhost:deploy --init first' + ); + const generated = ensureMailCollectorPassword(path, COLLECTOR, true); + expect(generated).toMatch(/^[0-9a-f]{64}$/); + expect(statSync(path).mode & 0o777).toBe(0o600); + expect(ensureMailCollectorPassword(path, COLLECTOR, false)).toBe(generated); + expect(ensureMailCollectorPassword(path, COLLECTOR, true)).toBe(generated); + }); + + it('is not created while the profile is off', () => { + expect(ensureMailCollectorPassword(path, {}, true)).toBeNull(); + expect(() => readFileSync(path)).toThrow(); + }); + + it('refuses a password file it did not generate', () => { + writeFileSync(path, 'hunter2\n', { mode: 0o600 }); + expect(() => ensureMailCollectorPassword(path, COLLECTOR, false)).toThrow( + 'not a generated collector password' + ); + }); +}); + +describe('renderMailCollectorEnv', () => { + const password = 'a'.repeat(64); + + it('turns the Caddy route off when the profile is off', () => { + expect(renderMailCollectorEnv({}, null)).toBe('SAM_MAIL_COLLECTOR=off\n'); + }); + + it('turns it on with the generated password, host label and UI port', () => { + expect(renderMailCollectorEnv(COLLECTOR, password)).toBe( + [ + 'SAM_MAIL_COLLECTOR=on', + 'MAIL_COLLECTOR_HOST_LABEL=mail', + 'MAIL_COLLECTOR_UI_PORT=8025', + 'MAIL_COLLECTOR_UI_USER=collector', + `MAIL_COLLECTOR_UI_PASSWORD=${password}`, + '', + ].join('\n') + ); + }); + + it('refuses to turn it on without the password, or on a host SAM serves', () => { + expect(() => renderMailCollectorEnv(COLLECTOR, null)).toThrow( + 'needs its generated UI password' + ); + for (const label of ['api', 'app', 'ws-abc', 'Mail', 'a.b']) { + expect(() => + renderMailCollectorEnv({ ...COLLECTOR, MAIL_COLLECTOR_HOST_LABEL: label }, password) + ).toThrow('MAIL_COLLECTOR_HOST_LABEL'); + } + }); +}); + +describe('writeMailCollectorFiles', () => { + const password = 'b'.repeat(64); + let dir: string; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'sam-mail-files-')); + }); + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + it('gives Mailpit its own copy of the credentials, privately, while the profile is on', () => { + const changed = writeMailCollectorFiles(dir, COLLECTOR, password); + expect(changed.map((path) => path.slice(dir.length + 1)).sort()).toEqual([ + 'mail-collector-ui.env', + 'mail-collector.env', + ]); + expect(readFileSync(join(dir, 'mail-collector-ui.env'), 'utf8')).toBe( + `MP_UI_AUTH=collector:${password}\n` + ); + for (const name of ['mail-collector.env', 'mail-collector-ui.env']) { + expect(statSync(join(dir, name)).mode & 0o777).toBe(0o600); + } + expect(writeMailCollectorFiles(dir, COLLECTOR, password)).toEqual([]); + }); + + it('turning the profile off turns the Caddy route off and removes the password copy', () => { + writeMailCollectorFiles(dir, COLLECTOR, password); + writeMailCollectorFiles(dir, { COMPOSE_PROFILES: 'tunnel' }, null); + expect(readFileSync(join(dir, 'mail-collector.env'), 'utf8')).toBe('SAM_MAIL_COLLECTOR=off\n'); + expect(existsSync(join(dir, 'mail-collector-ui.env'))).toBe(false); + }); + + it('refuses to turn the collector on without the generated password', () => { + expect(() => writeMailCollectorFiles(dir, COLLECTOR, null)).toThrow( + 'needs its generated UI password' + ); + expect(existsSync(join(dir, 'mail-collector-ui.env'))).toBe(false); + }); +}); + +describe('half-applied SMTP settings', () => { + it.each([ + [{ SMTP_FROM: 'a@b.example' }, {}, 'SMTP_FROM'], + [{ SMTP_USERNAME: 'u' }, {}, 'SMTP_USERNAME'], + [{}, { SMTP_PASSWORD: 'p' }, 'SMTP_PASSWORD'], + [{ ...COLLECTOR, SMTP_USERNAME: 'u' }, {}, 'SMTP_USERNAME'], + [{ ...COLLECTOR, SMTP_TLS: 'tls' }, {}, 'SMTP_TLS'], + [COLLECTOR, { SMTP_PASSWORD: 'p' }, 'SMTP_PASSWORD'], + ] as Array<[Record, Record, string]>)( + 'refuses %o / secrets %o', + (box, secrets, name) => { + expect(() => smtpWorkerVars(box, secrets, DOMAIN)).toThrow( + `${name} set without an SMTP relay` + ); + } + ); + + it('control: SMTP_FROM may accompany the collector', () => { + expect(smtpWorkerVars({ ...COLLECTOR, SMTP_FROM: 'a@b.example' }, {}, DOMAIN).SMTP_FROM).toBe( + 'a@b.example' + ); + }); +}); + +describe('collector ports', () => { + it.each([ + [{ MAIL_COLLECTOR_SMTP_PORT: '25' }, 'MAIL_COLLECTOR_SMTP_PORT must be'], + [{ MAIL_COLLECTOR_UI_PORT: '70000' }, 'MAIL_COLLECTOR_UI_PORT must be'], + [{ MAIL_COLLECTOR_UI_PORT: '80x' }, 'MAIL_COLLECTOR_UI_PORT must be'], + [{ MAIL_COLLECTOR_SMTP_PORT: '2525', MAIL_COLLECTOR_UI_PORT: '2525' }, 'must differ'], + ])('refuses %o', (ports, message) => { + expect(() => mailCollectorPorts({ ...COLLECTOR, ...ports })).toThrow(message); + }); +}); diff --git a/scripts/selfhost/mail-settings.ts b/scripts/selfhost/mail-settings.ts new file mode 100644 index 0000000000..1933fe1b41 --- /dev/null +++ b/scripts/selfhost/mail-settings.ts @@ -0,0 +1,230 @@ +/** + * Email for a celld box: the Worker's SMTP settings and the optional mail collector. + * + * The API Worker sends sign-in codes through SMTP when it has no Cloudflare Email Sending binding + * (apps/api/src/services/agent-email/provider.ts). Two ways to give a box one: + * - a real relay: SMTP_HOST, SMTP_PORT, SMTP_TLS, SMTP_USERNAME, SMTP_FROM in the compose .env and + * SMTP_PASSWORD in .state/secrets.env; + * - the `mail-collector` compose profile: Mailpit on loopback catches every message and shows it + * in a web UI at https://mail.SAM_DOMAIN behind basic auth. Anyone who can read the collector can + * sign in as any account, so it is for test installs, off by default, and the deploy refuses + * it until `--init` has generated the UI password. + * Both at once is refused: one install, one place its codes go. + */ +import { randomBytes } from 'node:crypto'; +import { existsSync, readFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; + +import { resolveSmtpConfig } from '../../packages/agent-email/src/smtp-config.js'; +import { writePrivateFile } from './secret-files.js'; + +export const MAIL_COLLECTOR_PROFILE = 'mail-collector'; +/** Mailpit's SMTP listener (loopback, no TLS: plaintext SMTP is accepted only to loopback). */ +export const DEFAULT_MAIL_COLLECTOR_SMTP_PORT = 1025; +/** Mailpit's web UI (loopback; Caddy publishes it behind basic auth). */ +export const DEFAULT_MAIL_COLLECTOR_UI_PORT = 8025; +/** The collector UI is served at