#!/usr/bin/env node import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { dirname, resolve } from 'node:path'; import type { Kysely } from 'kysely'; import { buildApp } from '../app/buildApp'; import { loadCdnConfigFromEnv } from '../cdn/config/loadCdnConfigFromEnv'; import { createCdnSigner } from '../cdn/createCdnSigner'; import { createPostgresDb, type CreatePostgresDbOptions } from '../db/drivers/postgres'; import { createSqliteDb, type CreateSqliteDbOptions } from '../db/drivers/sqlite'; import { postgresMigrations } from '../db/migrations/postgres/index'; import { sqliteMigrations } from '../db/migrations/sqlite/index'; import { migrate, migrateDown, status, validate, type MigrationSource, } from '../db/migrator/runner'; import type { Database as Schema } from '../db/schema'; import { loadImportConnectionsFromEnv } from '../import/config/loadImportConnectionsFromEnv'; import { loadImportPolicyFromEnv } from '../import/config/loadImportPolicyFromEnv'; import { ConnectedUsageReporter } from '../licensing/ConnectedUsageReporter'; import { LicenseRuntime } from '../licensing/LicenseRuntime'; import { createLicenseRuntime, licenseRuntimeOf } from '../licensing/public'; import { UsageMeters } from '../licensing/UsageMeters'; import { loadModules } from '../modules/load'; import { PostgresRealtimeBus } from '../realtime/PostgresRealtimeBus'; import { readCgroupMemory } from '../runtime/cgroup-memory'; import { resolveRecycleConfig } from '../runtime/EngineRecycler'; import { loadServerFontsFromEnv } from '../runtime/loadServerFontsFromEnv'; import { loadKmsConfigFromEnv } from '../security/kms/config/loadKmsConfigFromEnv'; import { createKmsKeyring } from '../security/kms/createKmsKeyring'; import type { KmsKeyring } from '../security/kms/KmsKeyring'; import { loadSecretsConfigFromEnv } from '../security/secrets/config/loadSecretsConfigFromEnv'; import { createSecretsProviderRegistry } from '../security/secrets/createSecretsProvider'; import { createSecretResolver, type SecretResolver } from '../security/secrets/SecretResolver'; import { resolveQuarantineConfig } from '../services/CrashJournal'; import { EventLogService } from '../services/EventLogService'; import { loadObjectStoreConfigFromEnv } from '../storage/config/loadObjectStoreConfigFromEnv'; import { createObjectStore } from '../storage/createObjectStore'; import type { ObjectStore } from '../storage/ObjectStore'; /** * @license FCL-1.0-ALv2 * * Warning: The license bootstrap imported below is part of CloudPDF's * license-key functionality. Removing or modifying it to disable or circumvent * license enforcement, enable protected functionality without a valid license * key, or remove protected functionality is a breach of FCL-1.0-ALv2 while * this release is governed by that license. See cloudpdf/server/LICENSE. */ /** * Multi-command CLI: * * cloudpdf-server → serve (default) * cloudpdf-server serve * cloudpdf-server migrate status * cloudpdf-server migrate up [--dry-run] * cloudpdf-server migrate down [--to NNN | --steps N | --all] [--dry-run] [--yes] [--force] * cloudpdf-server migrate validate [--strict] * cloudpdf-server db doctor * cloudpdf-server audit export --day yesterday * cloudpdf-server license request [--output cloudpdf-license-request.json] * cloudpdf-server license install --file cloudpdf-license.lic * cloudpdf-server license status * cloudpdf-server --help * * Config is read from env (12-factor friendly). `serve` runs the full * adapter bootstrap (secrets -> storage -> CDN -> KMS, see * `docs/conventions/server-adapters.md`) * so the same binary scales from zero-config SQLite + filesystem to * Postgres + S3/GCS/Azure purely by changing env: * CLOUDPDF_DB_DRIVER sqlite|postgres (default: sqlite) * CLOUDPDF_DB_SQLITE_PATH (default: ./data/cloudpdf.db) * CLOUDPDF_DB_URL postgres://... (required for postgres) * CLOUDPDF_REALTIME in-process (opt out of LISTEN/NOTIFY; postgres * defaults to cross-replica delivery) * CLOUDPDF_JWT_SECRET (default: dev secret — allowed only on development licenses) * CLOUDPDF_API_AUTH_TOKENS comma-separated static root credentials, valid on * every surface; a list so rotation is * overlap-then-retire. Each token must be >= 32 * bytes under a production license. Unset = * JWT-only deployment. * CLOUDPDF_PASSWORD_VERIFICATION_HMAC_SECRET / CLOUDPDF_PASSWORD_SESSION_SERVER_SECRET * (>= 32 bytes; required with a production license) * CLOUDPDF_TRUST_PROXY 1|hops|CSV of proxy IPs (real client IPs behind a LB) * CLOUDPDF_AUTH_FAILURE_LIMIT failed auths/IP/window, 'off' to disable (default 30) * CLOUDPDF_ENABLE_REVOCATION 1 mounts tokens.revoke + enforces the jti denylist * CLOUDPDF_CORS_ORIGINS '*' (reflect any) or CSV allowlist; unset = CORS off. * Needed for browser-direct viewing across origins — * bearer tokens stay the security boundary, and the * per-credential origins claim carries the origin policy. * CLOUDPDF_STORAGE_KIND fs|s3|gcs|azure-blob (default: fs) * CLOUDPDF_STORAGE_FS_ROOT (default: ./data/objects) * CLOUDPDF_CACHE_ROOT (default: ./data/cache; enables /v1/docs/*) * CLOUDPDF_SIGNING_TMP (default: /cloudpdf-signing; signing candidates) * CLOUDPDF_SIGNING_TTL_MS (default: 900000; a prepared signing waits this long for its CMS) * CLOUDPDF_IMPORT_ENABLED=0 disable documents.importFrom server-side pulls (default: on) * CLOUDPDF_IMPORT_MAX_BYTES / CLOUDPDF_IMPORT_TIMEOUT_MS / CLOUDPDF_IMPORT_MAX_CONCURRENT * CLOUDPDF_IMPORT_ALLOW_HTTP=1 / CLOUDPDF_IMPORT_ALLOW_PRIVATE_NETWORKS=1 (dev / MinIO) * CLOUDPDF_IMPORT_CONNECTIONS=name1,name2 operator-registered pull sources; per name: * CLOUDPDF_IMPORT_CONNECTION__KIND=s3 + _S3_BUCKET/_S3_REGION[/_S3_ENDPOINT], * _CREDENTIALS=api-token[,tenant-jwt] (default api-token) _TENANTS=*|csv * _SCOPE=whole-bucket|shared-prefixes|tenant-template (+_SCOPE_PREFIXES/_SCOPE_TEMPLATE) * CLOUDPDF_CDN_KIND none|bunny|... (default: none) * CLOUDPDF_KMS_KIND static|aws-kms|... (opt-in; encrypted-PDF sessions) * CLOUDPDF_SECRETS_PROVIDERS registry names (default: env) * CLOUDPDF_AUTO_MIGRATE=0|1 apply migrations on boot (default: on for sqlite) * CLOUDPDF_FAIL_ON_PENDING=1 refuse to start with pending migrations * CLOUDPDF_AUTO_PROVISION_TENANT=1 lazily create tenant rows (dev) * port (default: 3000) * host (default: 0.0.0.0) * CLOUDPDF_WORKER_POOL_SIZE int|max (default: min(2, cpus)) * CLOUDPDF_FONTS JSON [{key,path,familyName?,...,serve?}] (default: none) * CLOUDPDF_MODULES comma-separated server modules (packages or paths); * each reads its settings from CLOUDPDF__* * CLOUDPDF_LICENSE_MODE connected|air-gapped * CLOUDPDF_LICENSE_KEY required for connected mode; usage reporting * derives its credential from this key * (CLOUDPDF_LICENSE_REPORTING_TOKEN is retired) * * Exit codes: * 0 success * 1 user error / drift / failed command * 2 missing required config */ type Dialect = 'sqlite' | 'postgres'; interface DbContext { dialect: Dialect; db: Kysely; migrations: ReadonlyArray; describe: string; } function readDbConfig(): { dialect: Dialect; sqliteOpts?: CreateSqliteDbOptions; pgOpts?: CreatePostgresDbOptions; describe: string; } { const driver = (process.env['CLOUDPDF_DB_DRIVER'] ?? 'sqlite').toLowerCase() as Dialect; if (driver === 'postgres') { const url = process.env['CLOUDPDF_DB_URL']; if (!url) { fail(2, 'CLOUDPDF_DB_DRIVER=postgres requires CLOUDPDF_DB_URL=postgres://...'); } return { dialect: 'postgres', pgOpts: { connectionString: url!, // The message only: pg-pool hangs the client, with its // connection parameters (password included), on the error. onIdleConnectionError: (err) => console.warn(`[cloudpdf] idle database connection closed: ${err.message}`), }, describe: `postgres ${redact(url!)}`, }; } if (driver !== 'sqlite') { fail(2, `CLOUDPDF_DB_DRIVER must be 'sqlite' or 'postgres' (got ${driver!})`); } const path = process.env['CLOUDPDF_DB_SQLITE_PATH'] ?? './data/cloudpdf.db'; return { dialect: 'sqlite', sqliteOpts: { path }, describe: `sqlite ${path}` }; } function openDb(): DbContext { const cfg = readDbConfig(); if (cfg.dialect === 'postgres') { return { dialect: 'postgres', db: createPostgresDb(cfg.pgOpts!), migrations: postgresMigrations, describe: cfg.describe, }; } return { dialect: 'sqlite', db: createSqliteDb(cfg.sqliteOpts!), migrations: sqliteMigrations, describe: cfg.describe, }; } /** * Build the secrets resolver from env (`CLOUDPDF_SECRETS_*`). Defaults * to a single `env` provider with 1h caching, so this is safe with no * extra config. Adapter factories use it to resolve `secret://` refs. */ function buildSecretResolver(): SecretResolver { return createSecretResolver(createSecretsProviderRegistry(loadSecretsConfigFromEnv(process.env))); } async function openObjectStore(): Promise { try { return await createObjectStore(loadObjectStoreConfigFromEnv(process.env), { resolver: buildSecretResolver(), }); } catch (err) { fail(2, err instanceof Error ? err.message : String(err)); } } /** * Build a KMS keyring only when explicitly configured. KMS powers * encrypted-PDF password-session persistence; without it the server * still serves normal documents (that feature just stays off). Static * KMS requires CLOUDPDF_KMS_STATIC_KEK, so we never call the loader * unless the operator opted in via CLOUDPDF_KMS_*. */ async function buildKms(resolver: SecretResolver): Promise { const configured = process.env['CLOUDPDF_KMS_KIND'] !== undefined || process.env['CLOUDPDF_KMS_STATIC_KEK'] !== undefined; if (!configured) return null; try { return await createKmsKeyring(loadKmsConfigFromEnv(process.env), { resolver }); } catch (err) { fail(2, err instanceof Error ? err.message : String(err)); } } function redact(url: string): string { return url.replace(/(:\/\/[^:]+:)[^@]+(@)/, '$1***$2'); } /** * CLOUDPDF_TRUST_PROXY → Fastify `trustProxy`: `1`/`true` trusts the direct * peer's X-Forwarded-For, an integer trusts that many hops, anything else is * a comma-separated list of proxy addresses / CIDRs. */ function readTrustProxyEnv(): boolean | number | string[] | undefined { const raw = process.env['CLOUDPDF_TRUST_PROXY']?.trim(); if (!raw) return undefined; const lower = raw.toLowerCase(); if (lower === '1' || lower === 'true') return true; if (lower === '0' || lower === 'false') return false; if (/^\d+$/.test(raw)) return Number(raw); return raw .split(',') .map((s) => s.trim()) .filter((s) => s.length > 0); } /** * CLOUDPDF_CORS_ORIGINS → buildApp `corsOrigins`: `*` reflects any * origin (bearer tokens are the security boundary; per-credential * origin locks carry the real policy), a CSV pins an allowlist, absent * leaves CORS off (same-origin / proxy-fronted deployments). */ function readCorsOriginsEnv(): '*' | string[] | undefined { const raw = process.env['CLOUDPDF_CORS_ORIGINS']?.trim(); if (!raw) return undefined; if (raw === '*') return '*'; const origins = raw .split(',') .map((s) => s.trim()) .filter((s) => s.length > 0); if (origins.length === 0) return undefined; for (const origin of origins) { if (!/^https?:\/\//.test(origin)) { fail( 2, `CLOUDPDF_CORS_ORIGINS entries must be origins like https://app.example.com (got ${origin})`, ); } } return origins; } function readUploadProxyPolicyEnv(): 'fallback-only' | 'allowed' | 'disabled' { const raw = process.env['CLOUDPDF_UPLOAD_PROXY_POLICY']?.trim().toLowerCase(); if (!raw) return 'fallback-only'; if (raw === 'fallback-only' || raw === 'allowed' || raw === 'disabled') return raw; fail(2, `CLOUDPDF_UPLOAD_PROXY_POLICY must be fallback-only, allowed, or disabled (got ${raw})`); } /** CLOUDPDF_ENABLE_REVOCATION=1 mounts tokens.revoke and enforces the jti denylist. */ function readEnableRevocationEnv(): boolean { const raw = process.env['CLOUDPDF_ENABLE_REVOCATION']?.trim().toLowerCase(); return raw === '1' || raw === 'true'; } function readAuthFailureLimitEnv(): { maxFailures: number; windowMs?: number } | false | undefined { const raw = process.env['CLOUDPDF_AUTH_FAILURE_LIMIT']?.trim(); const windowRaw = process.env['CLOUDPDF_AUTH_FAILURE_WINDOW_MS']?.trim(); if (raw !== undefined && raw.toLowerCase() === 'off') return false; if (raw === undefined && windowRaw === undefined) return undefined; const maxFailures = raw !== undefined ? Number(raw) : 30; if (!Number.isInteger(maxFailures) || maxFailures <= 0) { fail(2, `CLOUDPDF_AUTH_FAILURE_LIMIT must be a positive integer or 'off' (got ${raw!})`); } if (windowRaw === undefined) return { maxFailures }; const windowMs = Number(windowRaw); if (!Number.isInteger(windowMs) || windowMs <= 0) { fail(2, `CLOUDPDF_AUTH_FAILURE_WINDOW_MS must be a positive integer (got ${windowRaw})`); } return { maxFailures, windowMs }; } function fail(code: number, msg: string): never { console.error(`cloudpdf-server: ${msg}`); process.exit(code); } function printHelp(): void { console.log( [ 'cloudpdf-server [command] [args]', '', 'Commands:', ' serve (default) Start the HTTP server', ' migrate status Show applied / pending / drift state', ' migrate up Apply pending migrations', ' migrate up --dry-run List what would be applied without changing the DB', ' migrate down Roll back migrations (manual break-glass; destructive)', ' quarantine list Show engine-crash quarantined documents', ' quarantine clear --reason "…" Lift a quarantine (audited)', ' --to NNN Roll back everything newer than version NNN', ' --steps N Roll back the N highest applied (default 1)', ' --all Roll back every applied migration', ' --dry-run Preview the rollback plan without touching the DB', ' --yes Required to actually run (containers are non-interactive)', ' --force Roll back even if the up-checksum drifted from code', ' migrate validate Refuse to exit 0 if drift is detected', ' migrate validate --strict Treat pending migrations as drift too', ' db doctor Connect, run validate, print version info', ' audit export --day yesterday', ' Export closed-day audit_log rows to JSONL storage', ' license request [--output FILE] [--force]', ' Create a machine-bound air-gap activation request', ' license install --file FILE', ' Verify and install a signed air-gap certificate', ' license status Validate and print the current license decision', '', 'Environment:', ' Database', ' CLOUDPDF_DB_DRIVER sqlite|postgres (default: sqlite)', ' CLOUDPDF_DB_SQLITE_PATH (default: ./data/cloudpdf.db)', ' CLOUDPDF_DB_URL postgres://... (required for postgres)', ' Storage (object store)', ' CLOUDPDF_STORAGE_KIND fs|s3|gcs|azure-blob (default: fs)', ' CLOUDPDF_STORAGE_FS_ROOT (default: ./data/objects)', ' CLOUDPDF_STORAGE_S3_BUCKET, CLOUDPDF_STORAGE_S3_REGION, CLOUDPDF_STORAGE_S3_ENDPOINT', ' Auth', ' CLOUDPDF_JWT_SECRET HS256 secret, >= 32 bytes (required with a production license)', ' CLOUDPDF_API_AUTH_TOKENS comma-separated root tokens, each >= 32 bytes in production', ' CLOUDPDF_PASSWORD_VERIFICATION_HMAC_SECRET >= 32 bytes (required with a production license)', ' CLOUDPDF_PASSWORD_SESSION_SERVER_SECRET >= 32 bytes (required with a production license + KMS)', ' CLOUDPDF_PASSWORD_SESSION_SERVER_SECRET_ID secret rotation id (default: dev-v1)', ' CLOUDPDF_TRUST_PROXY 1|true, hop count, or CSV of proxy IPs/CIDRs', ' CLOUDPDF_SHUTDOWN_TIMEOUT_MS app.close() budget before teardown proceeds (default 30000)', ' CLOUDPDF_SHUTDOWN_DRAIN_MS settle window after readiness flips 503 (default 0)', ' CLOUDPDF_METRICS 1 exposes an unauthenticated Prometheus /metrics endpoint', ' CLOUDPDF_ENGINE_ISOLATION inline (default) or host: run PDFium in a supervised child process', ' CLOUDPDF_ENGINE_SHARDS engine shard count (host mode; worker total must divide evenly; default 1)', ' CLOUDPDF_ENGINE_RECYCLE 1 enables engine recycling (host mode; opt-in until soak data)', ' CLOUDPDF_ENGINE_RECYCLE_SOFT_PCT / _HARD_PCT container working-set watermarks (70 / 85)', ' CLOUDPDF_ENGINE_MAX_RSS_MB / CLOUDPDF_ENGINE_MAX_LIFETIME_HOURS secondary recycle guards', ' CLOUDPDF_QUARANTINE_ENFORCE 1 refuses quarantined documents with 422 (default: observe-only journal)', ' CLOUDPDF_QUARANTINE_TTL_HOURS quarantine/strike TTL (default 24)', ' (set behind a LB so rate limits see real client IPs)', ' CLOUDPDF_AUTH_FAILURE_LIMIT failed auths per IP per window; off to disable (default: 30)', ' CLOUDPDF_AUTH_FAILURE_WINDOW_MS window for the failure limit (default: 60000)', ' CLOUDPDF_ENABLE_REVOCATION 1 mounts tokens.revoke + enforces the jti denylist', ' CLOUDPDF_CORS_ORIGINS * (reflect any) or CSV allowlist; absent = CORS off', ' (needed for browser-direct viewing across origins)', ' Commercial license', ' CLOUDPDF_LICENSE_MODE connected|air-gapped (explicit in production)', ' CLOUDPDF_LICENSE_KEY required for connected mode', ' Engine cache (enables /v1/docs/* read+render routes)', ' CLOUDPDF_CACHE_ROOT (default: ./data/cache)', ' CLOUDPDF_CACHE_MAX_BYTES (default: 4 GiB)', ' CLOUDPDF_SIGNING_TMP (default: /cloudpdf-signing)', ' Fonts', ' CLOUDPDF_FONTS JSON [{key,path,familyName?,...,serve?}] (default: none)', ' Modules', ' CLOUDPDF_MODULES comma-separated packages or paths; each module reads CLOUDPDF__*', ' Optional adapters (see ADAPTERS.md)', ' CLOUDPDF_CDN_KIND none|bunny|cloud-cdn|cloudfront|azure-fd|custom-hmac (default: none)', ' CLOUDPDF_KMS_KIND static|aws-kms|gcp-kms|azure-kv (opt-in; needed for encrypted-PDF sessions)', ' CLOUDPDF_SECRETS_PROVIDERS comma-separated provider registry (default: env)', ' Lifecycle', ' CLOUDPDF_AUTO_MIGRATE=0|1 apply migrations on boot (default: on for sqlite, off for postgres)', ' CLOUDPDF_FAIL_ON_PENDING=1 refuse to serve with pending migrations', ' CLOUDPDF_AUTO_PROVISION_TENANT=1 lazily create tenant rows (dev convenience)', ' Process', ' PORT (default: 3000), HOST (default: 0.0.0.0)', ' CLOUDPDF_WORKER_POOL_SIZE int|max (default: min(2, cpus))', ].join('\n'), ); } // ------- commands ------- /** * Operator surface for the engine crash quarantine: * cloudpdf-server quarantine list * cloudpdf-server quarantine clear --reason "verified fixed" * CLI-first on purpose — no contract/SDK churn; a dashboard op can * follow when a UI needs it. */ async function cmdQuarantine(args: string[]): Promise { const { CrashJournal } = await import('../services/CrashJournal'); const sub = args[0]; const ctx = openDb(); try { const journal = new CrashJournal({ db: ctx.db }); if (sub === 'list') { const rows = await journal.listQuarantine(); if (rows.length === 0) { console.log('no quarantined documents'); return; } for (const row of rows) { const state = row.expires_at > Date.now() ? 'active' : 'expired'; console.log( `${row.base_sha} build=${row.engine_build} reason=${row.reason} ` + `${state} until ${new Date(row.expires_at).toISOString()}`, ); } return; } if (sub === 'clear') { const sha = args[1]; const reason = readFlagValue(args, '--reason'); if (!sha) fail(1, 'quarantine clear: missing '); if (!reason) { fail(1, 'quarantine clear: --reason is required (it lands in the audit trail)'); } const removed = await journal.clear(sha!, { actor: 'cli', reason: reason! }); console.log(`cleared ${removed} quarantine row(s) for ${sha} (audited)`); return; } fail(1, `unknown quarantine subcommand: ${sub ?? '(none)'} (use: list | clear --reason)`); } finally { await ctx.db.destroy(); } } async function cmdMigrateStatus(): Promise { const ctx = openDb(); try { const rows = await status(ctx.db, ctx.migrations); console.log(`db: ${ctx.describe}`); if (rows.length === 0) { console.log('(no migrations registered)'); return; } for (const r of rows) { const when = r.appliedAt ? new Date(r.appliedAt).toISOString() : '-'; console.log(` ${r.version} ${pad(r.state, 8)} ${pad(r.name, 32)} ${when}`); if (r.drift) { console.log( ` drift db=${r.drift.dbChecksum.slice(0, 12)}.. code=${r.drift.codeChecksum.slice(0, 12)}..`, ); } } const hasDrift = rows.some((r) => r.state === 'drift' || r.state === 'orphan'); process.exit(hasDrift ? 1 : 0); } finally { await ctx.db.destroy(); } } /** * Progress logger for waits on the cross-migrator advisory lock — * another replica, deploy hook, or CLI is migrating. Throttled so the * 400ms poll doesn't flood the console. */ function makeLockWaitLogger(): (waitedMs: number) => void { let lastLogAt = 0; return (waitedMs) => { if (waitedMs - lastLogAt < 5_000) return; lastLogAt = waitedMs; console.log( `waiting for the migration lock (${Math.round(waitedMs / 1000)}s) — ` + `another migrator is running`, ); }; } async function cmdMigrateUp(args: string[]): Promise { const dryRun = args.includes('--dry-run'); const ctx = openDb(); try { if (dryRun) { const rows = await status(ctx.db, ctx.migrations); const pending = rows.filter((r) => r.state === 'pending'); console.log(`db: ${ctx.describe}`); if (pending.length === 0) { console.log('no pending migrations'); return; } console.log(`${pending.length} pending migration(s):`); for (const p of pending) { console.log(` ${p.version} ${p.name}`); } console.log('(dry-run: nothing applied)'); return; } const applied = await migrate(ctx.db, { source: { kind: 'inline', migrations: ctx.migrations }, dialect: ctx.dialect, onApply: (m) => console.log(`applying ${m.version} ${m.name}`), onLockWait: makeLockWaitLogger(), }); if (applied.length === 0) { console.log('nothing to apply (db up to date)'); } else { console.log(`applied ${applied.length} migration(s)`); } } finally { await ctx.db.destroy(); } } async function cmdMigrateDown(args: string[]): Promise { const dryRun = args.includes('--dry-run'); const yes = args.includes('--yes'); const force = args.includes('--force'); const all = args.includes('--all'); const to = readFlagValue(args, '--to'); const steps = readOptionalNumberFlag(args, '--steps'); if (to !== undefined && steps !== undefined) { fail(2, 'migrate down: pass either --to or --steps, not both'); } if (all && (to !== undefined || steps !== undefined)) { fail(2, 'migrate down: --all cannot be combined with --to or --steps'); } const ctx = openDb(); try { // Build the human-readable plan from status (read-only). The runner // recomputes + validates the same set; this is just the preview. const rows = await status(ctx.db, ctx.migrations); const appliedDesc = rows .filter((r) => r.state === 'applied' || r.state === 'drift') .sort((a, b) => (a.version < b.version ? 1 : a.version > b.version ? -1 : 0)); let planned: typeof appliedDesc; if (all) { planned = appliedDesc; } else if (to !== undefined) { planned = appliedDesc.filter((r) => r.version > to); } else { planned = appliedDesc.slice(0, steps ?? 1); } console.log(`db: ${ctx.describe}`); if (planned.length === 0) { console.log('nothing to roll back'); return; } console.log(`${planned.length} migration(s) will be rolled back (newest first):`); for (const p of planned) { const flag = p.reversible === false ? ' [IRREVERSIBLE — will fail]' : ''; const drift = p.state === 'drift' ? ' [up-checksum drift]' : ''; console.log(` ${p.version} ${p.name}${flag}${drift}`); } if (dryRun) { console.log('(dry-run: nothing rolled back)'); return; } if (!yes) { fail( 1, 'refusing to roll back without --yes (down migrations are destructive and ' + 'restore structure, not data). Re-run with --yes, or use --dry-run to preview.', ); } const reverted = await migrateDown(ctx.db, { source: { kind: 'inline', migrations: ctx.migrations }, ...(all ? { all: true } : {}), ...(to !== undefined ? { to } : {}), ...(steps !== undefined ? { steps } : {}), force, dialect: ctx.dialect, onRevert: (m) => console.log(`reverting ${m.version} ${m.name}`), onLockWait: makeLockWaitLogger(), }); console.log(`rolled back ${reverted.length} migration(s)`); } finally { await ctx.db.destroy(); } } async function cmdMigrateValidate(args: string[]): Promise { const strict = args.includes('--strict'); const ctx = openDb(); try { const issues = await validate(ctx.db, ctx.migrations, { treatPendingAsDrift: strict }); console.log(`db: ${ctx.describe}`); if (issues.length === 0) { console.log('ok (no drift)'); return; } console.error(`drift detected (${issues.length} issue(s)):`); for (const i of issues) { console.error(` - [${i.kind}] ${i.message}`); } process.exit(1); } finally { await ctx.db.destroy(); } } async function cmdDbDoctor(): Promise { const ctx = openDb(); console.log(`db: ${ctx.describe}`); try { // 1. Connection check. await ctx.db.selectFrom('schema_migrations').select('version').limit(1).execute(); console.log(' connection: ok'); } catch (err) { console.error(` connection: FAIL (${(err as Error).message})`); process.exit(1); } try { const issues = await validate(ctx.db, ctx.migrations); if (issues.length === 0) { console.log(' drift: none'); } else { console.error(` drift: ${issues.length} issue(s)`); for (const i of issues) console.error(` - [${i.kind}] ${i.message}`); process.exit(1); } const rows = await status(ctx.db, ctx.migrations); const applied = rows.filter((r) => r.state === 'applied').length; const pending = rows.filter((r) => r.state === 'pending').length; console.log(` migrations: ${applied} applied, ${pending} pending`); } finally { await ctx.db.destroy(); } } async function cmdAuditExport(args: string[]): Promise { const dayRaw = readFlagValue(args, '--day') ?? 'yesterday'; const day = resolveAuditDay(dayRaw); const tenantId = readFlagValue(args, '--tenant'); const docId = readFlagValue(args, '--doc'); if ((tenantId && !docId) || (!tenantId && docId)) { fail(2, 'audit export requires --tenant and --doc together, or neither'); } const force = args.includes('--force'); const allowOpenDay = args.includes('--allow-open-day'); const lagMinutes = readOptionalNumberFlag(args, '--lag-minutes') ?? 30; const dbCtx = openDb(); const storage = await openObjectStore(); const service = new EventLogService({ storage }); try { console.log(`db: ${dbCtx.describe}`); console.log(`storage: ${storage.info.kind} ${storage.info.location}`); if (tenantId && docId) { const result = await service.exportDocDayJsonl(dbCtx.db, { tenantId, docId, day, force, allowOpenDay, closedDayLagMs: lagMinutes * 60 * 1000, }); console.log( `audit export ${result.status}: day=${day} tenant=${tenantId} doc=${docId} ` + `events=${result.count} key=${result.key}`, ); return; } const result = await service.exportDayJsonl(dbCtx.db, { day, force, allowOpenDay, closedDayLagMs: lagMinutes * 60 * 1000, }); console.log( `audit export day=${day}: targets=${result.targets} exported=${result.exported} ` + `skipped=${result.skipped} alreadyRunning=${result.alreadyRunning} empty=${result.empty}`, ); } finally { await dbCtx.db.destroy(); } } async function cmdLicenseRequest(args: string[]): Promise { requireAirGappedMode(); const outputPath = resolve(readFlagValue(args, '--output') ?? 'cloudpdf-license-request.json'); const dbCtx = openDb(); try { await assertLicenseSchemaCurrent(dbCtx); const runtime = await LicenseRuntime.create({ db: dbCtx.db, env: process.env, secretResolver: buildSecretResolver(), startTimer: false, }); try { const request = await runtime.createActivationRequest(); await mkdir(dirname(outputPath), { recursive: true }); await writeFile(outputPath, `${JSON.stringify(request, null, 2)}\n`, { encoding: 'utf8', flag: args.includes('--force') ? 'w' : 'wx', mode: 0o600, }); console.log(`air-gap activation request written: ${outputPath}`); } finally { await runtime.close(); } } catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') { fail(1, `${outputPath} already exists; pass --force to replace it`); } throw error; } finally { await dbCtx.db.destroy(); } } async function cmdLicenseInstall(args: string[]): Promise { requireAirGappedMode(); const file = readFlagValue(args, '--file'); if (!file) fail(2, 'license install requires --file FILE'); const filePath = resolve(file); const certificate = await readFile(filePath, 'utf8'); const dbCtx = openDb(); try { await assertLicenseSchemaCurrent(dbCtx); const runtime = await LicenseRuntime.create({ db: dbCtx.db, env: process.env, secretResolver: buildSecretResolver(), startTimer: false, }); try { const verified = await runtime.installCertificate(certificate); console.log(`air-gap certificate installed: ${filePath}`); console.log(` license: ${verified.licenseId}`); console.log(` certificate expires: ${verified.artifactExpiresAt}`); } finally { await runtime.close(); } } finally { await dbCtx.db.destroy(); } } async function cmdLicenseStatus(): Promise { const dbCtx = openDb(); try { await assertLicenseSchemaCurrent(dbCtx); const runtime = await LicenseRuntime.create({ db: dbCtx.db, env: process.env, secretResolver: buildSecretResolver(), startTimer: false, }); try { console.log(JSON.stringify(runtime.getStatus(), null, 2)); } finally { await runtime.close(); } } finally { await dbCtx.db.destroy(); } } async function assertLicenseSchemaCurrent(dbCtx: DbContext): Promise { const rows = await status(dbCtx.db, dbCtx.migrations); const licenseMigration = rows.find((row) => row.version === '016'); if (!licenseMigration || licenseMigration.state !== 'applied') { fail(2, 'licensing requires migration 016; run: cloudpdf-server migrate up'); } } function requireAirGappedMode(): void { const mode = process.env['CLOUDPDF_LICENSE_MODE'] ?? (process.env['CLOUDPDF_LICENSE_KEY'] ? 'connected' : 'air-gapped'); if (mode !== 'air-gapped') { fail(2, 'this command requires CLOUDPDF_LICENSE_MODE=air-gapped'); } } function engineShardsEnv(): number | undefined { const raw = process.env['CLOUDPDF_ENGINE_SHARDS']; if (raw === undefined || raw === '') return undefined; const n = Number(raw); if (!Number.isInteger(n) || n < 1) { fail(2, `CLOUDPDF_ENGINE_SHARDS must be a positive integer, got ${JSON.stringify(raw)}`); } if (n > 1 && process.env['CLOUDPDF_ENGINE_ISOLATION'] !== 'host') { fail(2, 'CLOUDPDF_ENGINE_SHARDS > 1 requires CLOUDPDF_ENGINE_ISOLATION=host'); } return n; } function schedulingEnv(): Record | null { const parse = (name: string): number | undefined => { const raw = process.env[name]; if (raw === undefined || raw === '') return undefined; const n = Number(raw); if (!Number.isInteger(n) || n < 1) { fail(2, `${name} must be a positive integer, got ${JSON.stringify(raw)}`); } return n; }; const parseZeroOk = (name: string): number | undefined => { const raw = process.env[name]; if (raw === undefined || raw === '') return undefined; const n = Number(raw); if (!Number.isInteger(n) || n < 0) { fail(2, `${name} must be a non-negative integer, got ${JSON.stringify(raw)}`); } return n; }; const cfg = { maxInFlight: parse('CLOUDPDF_ENGINE_MAX_IN_FLIGHT'), // 0 = strict disable (background sheds instantly). backgroundMaxInFlight: parseZeroOk('CLOUDPDF_ENGINE_BG_MAX_IN_FLIGHT'), backgroundMaxQueued: parseZeroOk('CLOUDPDF_ENGINE_BG_MAX_QUEUED'), interactiveMaxQueued: parseZeroOk('CLOUDPDF_ENGINE_MAX_QUEUED'), backgroundQueueTimeoutMs: parse('CLOUDPDF_ENGINE_BG_QUEUE_TIMEOUT_MS'), interactiveQueueTimeoutMs: parse('CLOUDPDF_ENGINE_QUEUE_TIMEOUT_MS'), }; const entries = Object.entries(cfg).filter((e): e is [string, number] => e[1] !== undefined); if (entries.length === 0) return null; return Object.fromEntries(entries); } async function cmdServe(): Promise { const PORT = Number(process.env['PORT'] ?? 3000); const HOST = process.env['HOST'] ?? '0.0.0.0'; const JWT_SECRET = process.env['CLOUDPDF_JWT_SECRET'] ?? 'cloudpdf-dev-secret-change-me'; if (JWT_SECRET === 'cloudpdf-dev-secret-change-me') { console.warn( '[cloudpdf-server] WARNING: CLOUDPDF_JWT_SECRET not set, using insecure dev secret', ); } const API_AUTH_TOKENS = (process.env['CLOUDPDF_API_AUTH_TOKENS'] ?? '') .split(',') .map((t) => t.trim()) .filter((t) => t.length > 0); const FAIL_ON_PENDING = process.env['CLOUDPDF_FAIL_ON_PENDING'] === '1'; const AUTO_PROVISION_TENANT = process.env['CLOUDPDF_AUTO_PROVISION_TENANT'] === '1'; const CACHE_ROOT = process.env['CLOUDPDF_CACHE_ROOT'] ?? './data/cache'; const SIGNING_ROOT = process.env['CLOUDPDF_SIGNING_TMP']; const SIGNING_TTL_MS = process.env['CLOUDPDF_SIGNING_TTL_MS'] ? Number(process.env['CLOUDPDF_SIGNING_TTL_MS']) : undefined; const CACHE_MAX_BYTES = process.env['CLOUDPDF_CACHE_MAX_BYTES'] ? Number(process.env['CLOUDPDF_CACHE_MAX_BYTES']) : undefined; // Shutdown posture: keep the app.close() budget below the supervisor's // kill deadline (k8s terminationGracePeriodSeconds, docker stop -t). const SHUTDOWN_TIMEOUT_MS = process.env['CLOUDPDF_SHUTDOWN_TIMEOUT_MS'] ? Number(process.env['CLOUDPDF_SHUTDOWN_TIMEOUT_MS']) : undefined; const SHUTDOWN_DRAIN_MS = process.env['CLOUDPDF_SHUTDOWN_DRAIN_MS'] ? Number(process.env['CLOUDPDF_SHUTDOWN_DRAIN_MS']) : undefined; const WORKER_ENTRY_URL = new URL('../runtime/worker-entry.js', import.meta.url); const ENGINE_HOST_ENTRY_URL = new URL('../runtime/engine-host-entry.js', import.meta.url); // Engine plane placement: 'inline' (worker threads in this process, // default) or 'host' (supervised child process — a native PDFium crash // costs one sub-second engine respawn, never the API). const engineIsolationRaw = process.env['CLOUDPDF_ENGINE_ISOLATION'] ?? 'inline'; if (engineIsolationRaw !== 'inline' && engineIsolationRaw !== 'host') { fail(2, `CLOUDPDF_ENGINE_ISOLATION must be 'inline' or 'host' (got ${engineIsolationRaw})`); } const ENGINE_ISOLATION = engineIsolationRaw as 'inline' | 'host'; // Quarantine config fails boot on invalid or silently-inert settings // (enforce without host isolation, non-positive TTL). let quarantineConfig: ReturnType; try { quarantineConfig = resolveQuarantineConfig(process.env, ENGINE_ISOLATION); } catch (err) { fail(2, err instanceof Error ? err.message : String(err)); } for (const warning of quarantineConfig!.warnings) { console.warn(`[cloudpdf-server] WARNING: ${warning}`); } // Database defaults to SQLite (see readDbConfig), so a bare `serve` // boots the full admin + document pipeline with zero external infra. const dbCtx = openDb(); // Auto-migrate defaults on for SQLite (frictionless local/try-it-out) // and off for Postgres (production runs `migrate up` explicitly and // sets CLOUDPDF_FAIL_ON_PENDING=1). Override with CLOUDPDF_AUTO_MIGRATE. const autoMigrateEnv = process.env['CLOUDPDF_AUTO_MIGRATE']; const autoMigrate = autoMigrateEnv !== undefined ? autoMigrateEnv === '1' : dbCtx.dialect === 'sqlite'; if (autoMigrate) { const applied = await migrate(dbCtx.db, { source: { kind: 'inline', migrations: dbCtx.migrations }, dialect: dbCtx.dialect, onApply: (m) => console.log(`applying ${m.version} ${m.name}`), onLockWait: makeLockWaitLogger(), }); if (applied.length > 0) console.log(`auto-migrate: applied ${applied.length} migration(s)`); } // One resolver instance is shared by the license and infrastructure // adapters. This keeps secret:// license keys out of environment values // while preserving the same provider/cache behavior as every other secret. const resolver = buildSecretResolver(); // The license as any embedder makes it; its runtime also feeds usage reporting. const license = await createLicenseRuntime({ db: dbCtx.db, secretResolver: resolver }); const licenseRuntime = licenseRuntimeOf(license); const initialLicense = licenseRuntime.getStatus(); if (initialLicense.access === 'none') { await licenseRuntime.close(); await dbCtx.db.destroy(); fail(2, `${initialLicense.message} (${initialLicense.code})`); } if (initialLicense.access === 'restricted') { console.warn( `[cloudpdf-server] LICENSE RESTRICTED: ${initialLicense.message} (${initialLicense.code})`, ); } if (initialLicense.licenseKind === 'development') { console.warn( '[cloudpdf-server] DEVELOPMENT LICENSE: this deployment runs on a ' + 'development key with development-scale usage limits. Use your ' + 'subscription license key for production and staging.', ); } let usageReporter: ConnectedUsageReporter | undefined; if ( initialLicense.mode === 'connected' && initialLicense.telemetryProfile === 'aggregated-usage' ) { if (process.env['CLOUDPDF_LICENSE_REPORTING_TOKEN']) { console.warn( '[cloudpdf-server] CLOUDPDF_LICENSE_REPORTING_TOKEN is retired and ignored: ' + 'the usage-reporting credential is derived from CLOUDPDF_LICENSE_KEY. ' + 'Remove the variable from this deployment.', ); } try { const cloudPdfLicenseId = licenseRuntime.getConnectedReportingLicenseId(); const reportingCredential = licenseRuntime.getConnectedReportingCredential(); if (!cloudPdfLicenseId || !reportingCredential) { throw new Error( 'Connected license requires usage reporting but its signed metadata is missing cloudpdfLicenseId', ); } usageReporter = await ConnectedUsageReporter.create({ cloudPdfLicenseId, db: dbCtx.db, meters: new UsageMeters(dbCtx.db, licenseRuntime), reportingCredential, }); } catch (error) { await licenseRuntime.close(); await dbCtx.db.destroy(); fail(2, error instanceof Error ? error.message : String(error)); } } // Adapter bootstrap (see `docs/conventions/server-adapters.md`): // secrets registry -> resolver, then storage / CDN / KMS. Storage // defaults to filesystem and CDN to `none`, so this works with no // extra env. KMS is opt-in. const objectStore = await createObjectStoreOrExit(resolver); const cdnSigner = await createCdnSigner(loadCdnConfigFromEnv(process.env), { resolver }); const kms = await buildKms(resolver); // Cross-replica realtime doorbell. With Postgres the default is // LISTEN/NOTIFY — required for multi-replica deployments (compose // --scale / Helm replicas), where in-process delivery would silently // hide other replicas' mutations from SSE subscribers. Opt out with // CLOUDPDF_REALTIME=in-process (single-replica Postgres only). const realtimeMode = (process.env['CLOUDPDF_REALTIME'] ?? '').toLowerCase(); const realtimeBus = dbCtx.dialect === 'postgres' && realtimeMode !== 'in-process' ? new PostgresRealtimeBus(process.env['CLOUDPDF_DB_URL']!, (err) => { console.error('[cloudpdf] realtime bus error:', err); }) : undefined; const trustProxy = readTrustProxyEnv(); const authFailureLimit = readAuthFailureLimitEnv(); const corsOrigins = readCorsOriginsEnv(); const enableRevocation = readEnableRevocationEnv(); const uploadProxyPolicy = readUploadProxyPolicyEnv(); const importPolicy = loadImportPolicyFromEnv(); const importConnections = loadImportConnectionsFromEnv(); let bundle: Awaited>; try { let recycleConfig: ReturnType; try { recycleConfig = resolveRecycleConfig(process.env, ENGINE_ISOLATION, readCgroupMemory); } catch (err) { fail(2, (err as Error).message); } for (const w of recycleConfig!.warnings) console.warn(`[cloudpdf] ${w}`); // Server modules: each named package's default export, mounted after // the core's routes. One that won't load or lacks config stops the boot. const modules = await loadModules(process.env['CLOUDPDF_MODULES']); bundle = await buildApp({ ...(modules.length > 0 ? { modules } : {}), // Engine recycling (opt-in; fail-fast validated above). ...(recycleConfig.enabled ? { recycle: recycleConfig.policy } : {}), // Engine shard dial (buildApp validates divisibility against the // resolved worker total; K > 1 requires host isolation). ...(engineShardsEnv() !== undefined ? { engineShards: engineShardsEnv() } : {}), // Admission tuning (defaults compute from the pool's slot count; // queue caps and timeouts are buildApp options). ...(schedulingEnv() ? { scheduling: schedulingEnv()! } : {}), // Encoding escape hatch: '0'/'false' reverts to raw rasters over // the engine boundary + API-side sharp for one release. encodeInEngine: process.env.CLOUDPDF_ENCODE_IN_ENGINE !== '0' && process.env.CLOUDPDF_ENCODE_IN_ENGINE !== 'false', license, ...(usageReporter ? { usageReporter } : {}), verifier: { mode: 'hs256', secret: JWT_SECRET }, ...(API_AUTH_TOKENS.length > 0 ? { apiAuthTokens: API_AUTH_TOKENS } : {}), ...(corsOrigins !== undefined ? { corsOrigins } : {}), ...(enableRevocation ? { enableRevocation: true } : {}), workerEntry: WORKER_ENTRY_URL, fonts: loadServerFontsFromEnv(), db: dbCtx.db, objectStore, cdnSigner, ...(kms ? { kms } : {}), cacheRoot: CACHE_ROOT, ...(SIGNING_ROOT ? { signingRoot: SIGNING_ROOT } : {}), ...(SIGNING_TTL_MS !== undefined ? { signingTtlMs: SIGNING_TTL_MS } : {}), ...(CACHE_MAX_BYTES !== undefined ? { cacheMaxBytes: CACHE_MAX_BYTES } : {}), ...(AUTO_PROVISION_TENANT ? { autoProvisionTenant: true } : {}), uploadProxyPolicy, importPolicy, importConnections, expectedMigrations: dbCtx.migrations, failOnPending: FAIL_ON_PENDING, ...(realtimeBus ? { realtimeBus } : {}), ...(trustProxy !== undefined ? { trustProxy } : {}), ...(authFailureLimit !== undefined ? { authFailureLimit } : {}), ...(SHUTDOWN_TIMEOUT_MS !== undefined ? { shutdownTimeoutMs: SHUTDOWN_TIMEOUT_MS } : {}), ...(SHUTDOWN_DRAIN_MS !== undefined ? { shutdownDrainMs: SHUTDOWN_DRAIN_MS } : {}), ...(process.env['CLOUDPDF_METRICS'] === '1' ? { metrics: true } : {}), engineIsolation: ENGINE_ISOLATION, engineHostEntry: ENGINE_HOST_ENTRY_URL, ...(quarantineConfig.options ? { quarantine: quarantineConfig.options } : {}), }); } catch (err) { // Config-shaped boot refusals (secret policy, migration drift) exit // with the documented "missing required config" code instead of a // stack trace. usageReporter?.stop(); await licenseRuntime.close(); await dbCtx.db.destroy(); fail(2, err instanceof Error ? err.message : String(err)); } const onSignal = async (sig: string) => { bundle.app.log.info({ sig }, 'received signal, shutting down'); try { await bundle.shutdown(); } finally { usageReporter?.stop(); try { await licenseRuntime.close(); } finally { try { await dbCtx.db.destroy(); } finally { process.exit(0); } } } }; process.on('SIGINT', () => void onSignal('SIGINT')); process.on('SIGTERM', () => void onSignal('SIGTERM')); await bundle.app.listen({ port: PORT, host: HOST }); usageReporter?.start(); bundle.app.log.info( { port: PORT, host: HOST, db: dbCtx.describe, storage: objectStore.info.kind, cdn: cdnSigner.info.kind, kms: kms ? 'on' : 'off', cacheRoot: CACHE_ROOT, ...(SIGNING_ROOT ? { signingRoot: SIGNING_ROOT } : {}), ...(SIGNING_TTL_MS !== undefined ? { signingTtlMs: SIGNING_TTL_MS } : {}), }, 'cloudpdf-server listening', ); } async function createObjectStoreOrExit(resolver: SecretResolver): Promise { try { return await createObjectStore(loadObjectStoreConfigFromEnv(process.env), { resolver }); } catch (err) { fail(2, err instanceof Error ? err.message : String(err)); } } function pad(s: string, width: number): string { return s.length >= width ? s : s + ' '.repeat(width - s.length); } // ------- entrypoint ------- async function main(): Promise { const args = process.argv.slice(2); if (args[0] === '--help' || args[0] === '-h' || args[0] === 'help') { printHelp(); return; } if (args.length === 0 || args[0] === 'serve') { await cmdServe(); return; } if (args[0] === 'migrate') { const sub = args[1]; const rest = args.slice(2); if (sub === 'status') return cmdMigrateStatus(); if (sub === 'up') return cmdMigrateUp(rest); if (sub === 'down') return cmdMigrateDown(rest); if (sub === 'validate') return cmdMigrateValidate(rest); fail(2, `unknown subcommand: migrate ${sub ?? '(missing)'}\nrun: cloudpdf-server --help`); } if (args[0] === 'quarantine') { return cmdQuarantine(args.slice(1)); } if (args[0] === 'db') { const sub = args[1]; if (sub === 'doctor') return cmdDbDoctor(); fail(2, `unknown subcommand: db ${sub ?? '(missing)'}\nrun: cloudpdf-server --help`); } if (args[0] === 'audit') { const sub = args[1]; const rest = args.slice(2); if (sub === 'export') return cmdAuditExport(rest); fail(2, `unknown subcommand: audit ${sub ?? '(missing)'}\nrun: cloudpdf-server --help`); } if (args[0] === 'license') { const sub = args[1]; const rest = args.slice(2); if (sub === 'request') return cmdLicenseRequest(rest); if (sub === 'install') return cmdLicenseInstall(rest); if (sub === 'status') return cmdLicenseStatus(); fail(2, `unknown subcommand: license ${sub ?? '(missing)'}\nrun: cloudpdf-server --help`); } fail(2, `unknown command: ${args[0]!}\nrun: cloudpdf-server --help`); } function readFlagValue(args: string[], name: string): string | undefined { const eq = args.find((arg) => arg.startsWith(`${name}=`)); if (eq) { return eq.slice(name.length + 1); } const index = args.indexOf(name); if (index < 0) { return undefined; } const value = args[index + 1]; if (!value || value.startsWith('--')) { fail(2, `${name} requires a value`); } return value; } function readOptionalNumberFlag(args: string[], name: string): number | undefined { const raw = readFlagValue(args, name); if (raw === undefined) { return undefined; } const value = Number(raw); if (!Number.isFinite(value) || value < 0) { fail(2, `${name} must be a non-negative number`); } return value; } function resolveAuditDay(value: string): string { if (value === 'yesterday') { return dayFromOffsetUtc(-1); } if (value === 'today') { return dayFromOffsetUtc(0); } if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) { fail(2, `--day must be YYYY-MM-DD, yesterday, or today (got ${value})`); } return value; } function dayFromOffsetUtc(offsetDays: number): string { const date = new Date(); date.setUTCDate(date.getUTCDate() + offsetDays); return date.toISOString().slice(0, 10); } main().catch((err) => { console.error('cloudpdf-server: failed:', err); process.exit(1); });