import { TextDecoder } from 'node:util'; import { adminOperations, adminWirePaths } from '@cloudpdf/contract'; import { DEFAULT_BUNDLE_LIMITS, EngineError, EngineErrorCode, type BundleLimits, formatObjectNumberRanges, isEngineErrorCode, } from '@embedpdf/engine-core/runtime'; import compress from '@fastify/compress'; import cors from '@fastify/cors'; import multipart from '@fastify/multipart'; import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify'; import { sql, type Kysely } from 'kysely'; import { registerApiVersion } from './api-version'; import type { AuthFailureLimiterOptions } from './auth-failure-limiter'; import { DrainCoordinator } from './drain'; import { createEngineCounters, type EngineCounters } from './engine-counters'; import { registerJwtAuth, requireApiToken } from './jwt-plugin'; import { registerMetrics } from './metrics'; import { assertProductionSecret, requiresProductionSecrets, resolveSecret } from './secret-policy'; import { DbJwksCacheStore } from '../auth/JwksCacheStore'; import { signDevToken, type JwtClaims, type JwtVerifierConfig, type JwksCacheStore, type RevocationCheck, type SignDevTokenInput, } from '../auth/JwtVerifier'; import { PermissionRegistry } from '../auth/permission-registry'; import { RevokedJtisGuard } from '../auth/RevokedJtisGuard'; import { SuspendedTenantsGuard } from '../auth/SuspendedTenantsGuard'; import { TenantFeaturesGuard } from '../auth/TenantFeaturesGuard'; import { VisitorHandles } from '../auth/visitor-handle'; import { NoneCdnSigner } from '../cdn/adapters/NoneCdnSigner'; import type { CdnSigner } from '../cdn/CdnSigner'; import { validate as validateMigrations, type MigrationSource } from '../db/migrator/runner'; import { BaseVersionsRepo } from '../db/repos/base_versions.repo'; import { DocumentImportsRepo } from '../db/repos/document_imports.repo'; import { DocumentSigningsRepo } from '../db/repos/document_signings.repo'; import { DocumentsRepo } from '../db/repos/documents.repo'; import { FoldersRepo } from '../db/repos/folders.repo'; import { GrantVisitorsRepo } from '../db/repos/grant_visitors.repo'; import { GrantsRepo } from '../db/repos/grants.repo'; import { DocumentPagesRepo, LayerPagesRepo, LayersRepo } from '../db/repos/page_state.repo'; import { PdfPasswordSessionsRepo } from '../db/repos/pdf_password_sessions.repo'; import { PdfPasswordVerificationsRepo } from '../db/repos/pdf_password_verifications.repo'; import { SecurityEventsRepo } from '../db/repos/security-events.repo'; import { TenantUsageRepo } from '../db/repos/tenant_usage.repo'; import { TenantsRepo } from '../db/repos/tenants.repo'; import { UploadTokenUsesRepo } from '../db/repos/upload_token_uses.repo'; import type { Database as Schema } from '../db/schema'; import type { ImportConnection } from '../import/config/ImportConnectionSchema'; import { defaultImportPolicy, type ImportPolicy } from '../import/config/ImportPolicySchema'; import { ImportConnectionRegistry } from '../import/ImportConnectionRegistry'; import { ImportWorker } from '../import/ImportWorker'; import type { ConnectedUsageReporter } from '../licensing/ConnectedUsageReporter'; import type { LicenseGate } from '../licensing/LicenseRuntime'; import { licenseRuntimeOf, type CloudPdfLicenseRuntime } from '../licensing/public'; import { UsageMeters } from '../licensing/UsageMeters'; import { declareModules, moduleManifests, moduleMeterNames, mountModules } from '../modules/host'; import type { HostedModule } from '../modules/protocol'; import { InProcessRealtimeBus, type RealtimeBus } from '../realtime/RealtimeBus'; import { SharpImageEncoder } from '../render/SharpImageEncoder'; import { IMMUTABLE_CACHE_PRIVATE, IMMUTABLE_CACHE_SHARED, errorBody } from '../routes/_helpers'; import { registerAccessRoutes } from '../routes/access'; import { registerAdminDocumentsRoutes } from '../routes/admin/documents'; import { registerAdminFoldersRoutes } from '../routes/admin/folders'; import { registerAdminGrantsRoutes } from '../routes/admin/grants'; import { registerAdminLayersRoutes } from '../routes/admin/layers'; import { registerAdminTenantsRoutes } from '../routes/admin/tenants'; import { registerAdminTokensRoutes } from '../routes/admin/tokens'; import { registerAnnotationRoutes } from '../routes/annotations'; import { registerAttachmentRoutes } from '../routes/attachments'; import { registerChangeRoutes } from '../routes/changes'; import { registerDocsRoutes } from '../routes/docs'; import { registerEventsRoutes } from '../routes/events'; import { registerFontRoutes } from '../routes/fonts'; import { registerFormRoutes } from '../routes/forms'; import { registerGrantSessionRoutes } from '../routes/grant-sessions'; import { registerMetadataRoutes } from '../routes/metadata'; import { registerObjectNumberRoutes } from '../routes/object-numbers'; import { registerOutlineRoutes } from '../routes/outline'; import { registerPageRoutes } from '../routes/pages'; import { registerRedactionRoutes } from '../routes/redactions'; import { registerSearchRoutes } from '../routes/search'; import { registerSignatureRoutes } from '../routes/signatures'; import { readCgroupMemory } from '../runtime/cgroup-memory'; import { EngineHostClient } from '../runtime/EngineHostClient'; import type { EnginePool } from '../runtime/EnginePool'; import { EngineRecycler, type EngineRecyclePolicy } from '../runtime/EngineRecycler'; import { QuarantiningEnginePool } from '../runtime/QuarantiningEnginePool'; import { EngineBusyError, SchedulingEnginePool, type EngineSchedulingConfig, } from '../runtime/SchedulingEnginePool'; import { ShardedEnginePool } from '../runtime/ShardedEnginePool'; import { defaultSigningRoot } from '../runtime/signing-paths'; import { resolvePoolSize } from '../runtime/WorkerThreadPool'; import { WorkerThreadPool, type ServerFontDescriptor } from '../runtime/WorkerThreadPool'; import type { KmsKeyring } from '../security'; import { CrashJournal, DocumentQuarantinedError } from '../services/CrashJournal'; import { deleteStoredLayer } from '../services/deleteStoredLayer'; import { DerivedRenderService } from '../services/DerivedRenderService'; import { DocumentLifecycleService, type UploadProxyPolicy, } from '../services/DocumentLifecycleService'; import { FolderService } from '../services/FolderService'; import { DocumentSecurityProbe } from '../services/DocumentSecurityProbe'; import { DocumentService } from '../services/DocumentService'; import { EventLogService } from '../services/EventLogService'; import { deleteVisitor, sweepIdleVisitors } from '../services/grantVisitors'; import { LayerService } from '../services/LayerService'; import { LayerStateService } from '../services/LayerStateService'; import { ObjectNumberService } from '../services/ObjectNumberService'; import { ServerFonts } from '../services/ServerFonts'; import { BaseFileCache } from '../storage/BaseFileCache'; import type { ObjectStoreWithInfo } from '../storage/ObjectStore'; /** A route as the app mounted it: its method(s) and its URL pattern. */ export interface MountedRoute { readonly method: string; readonly url: string; } export interface BuildAppOptions { /** * The deployment's license: the runtime `createLicenseRuntime` made, and * nothing else. Any other object stops the build. */ license: CloudPdfLicenseRuntime; /** * The installed plugins, as server modules (`CLOUDPDF_MODULES` in the CLI), * in order. Their permissions are the plugin permissions this server knows: * tokens carry any well-formed plugin permission, but only these take * effect, and only these can be granted. A module that adds routes needs * the document plane (`workerEntry`, `db` and `objectStore`); one that only * declares permissions doesn't. */ modules?: ReadonlyArray; /** Where module config (`CLOUDPDF__*`) is read. Defaults to `process.env`. */ moduleEnv?: Readonly>; /** Connected-only reporting diagnostics; never constructed in air-gap mode. */ usageReporter?: Pick; /** * Cross-replica mutation doorbell. Defaults to in-process delivery — * complete for single-replica deployments (the SQLite profile) and tests. * Multi-replica Postgres deployments must pass a `PostgresRealtimeBus` * (the production entrypoint does this by default when the driver is * postgres) or replicas will not see each other's mutations. */ realtimeBus?: RealtimeBus; /** * JWT verifier config. Use `{ mode: 'hs256', secret }` for Tiny/dev * deployments, or RS/ES/JWKS modes for production IdP integration. */ verifier: JwtVerifierConfig; /** * Static API auth tokens (the deployment's root credential, valid on * every surface). A list so rotation is overlap-then-retire. Empty or * absent disables the credential entirely. Production licenses require * every configured token to be a random secret of at least 32 bytes. */ apiAuthTokens?: ReadonlyArray; /** * If true and `db` is supplied, wire a `RevokedJtisGuard` into the * verifier so revoked `jti`s are rejected at request time. Off by * default to keep dev tests cheap. */ enableRevocation?: boolean; /** * If true and `db` + `verifier.mode === 'jwks'`, plug the * persistent `jwks_cache` table into the JWKS verifier so the * cache survives restarts. */ enableJwksPersistence?: boolean; poolSize?: number; /** * The deployment's fonts, registered on every worker thread at startup. * Server-owned font policy: cloud clients cannot configure fonts, so the * server decides which fonts text can be written in and which fallback * fonts cover missing glyphs (page render + annotation appearance * generation), and which go to browsers (`serve`). Each is a file path that * PDFium range-reads on demand — large CJK fallback fonts cost a file * handle, not resident RAM. A font that fails to load fails worker startup. */ fonts?: ReadonlyArray; /** * URL of the worker_thread entry script. The package's main entry exports * `defaultWorkerEntryUrl` which works in both dev (tsx -> src/) and after * a Vite build (ESM dist/). Pass that unless you have a custom worker. */ /** * Set to `null` (or omit) to skip worker_thread initialisation. Use * this for admin-only deployments where no engine reads happen * through this Fastify process. The admin routes don't depend on * the pool. */ workerEntry: URL | string | null; /** Override Fastify body limit. Defaults to 50 MiB. */ bodyLimit?: number; /** * How large an annotation bundle may be, exported or imported, and how much * a copy inside a document may carry. Defaults to `DEFAULT_BUNDLE_LIMITS`. */ bundleLimits?: BundleLimits; /** Origin-mediated upload policy. Defaults to `fallback-only`. */ uploadProxyPolicy?: UploadProxyPolicy; /** * Server-side pull policy for `documents.importFrom`. Defaults to the * schema defaults (enabled, https-only, public networks, 128 MiB). * Pass `{ ...defaultImportPolicy(), enabled: false }` to disable. */ importPolicy?: ImportPolicy; /** * Operator-registered import connections (the `connection` source * kind). Validated at construction — duplicate ids and invalid * scope/credential combinations refuse to boot. */ importConnections?: ReadonlyArray; /** Async import worker idle-poll interval; tests shrink it. Default 1s. */ importWorkerPollMs?: number; /** * Fastify `trustProxy` passthrough. Required for `request.ip` (and thus * the auth-failure limiter) to see real client addresses when the server * runs behind a load balancer / reverse proxy: `true` trusts * `X-Forwarded-For` from the direct peer, a number trusts that many hops, * a string/array trusts specific proxy addresses or CIDRs. Leave unset * when clients connect directly. */ trustProxy?: boolean | number | string | string[]; /** * Per-IP throttle on authentication failures (never successful traffic). * Defaults to 30 failures / 60s per IP; pass `false` to disable when an * edge layer (WAF / ingress) already rate-limits. See `JwtPluginOptions`. */ authFailureLimit?: Partial | false; /** * CORS for browser-direct deployments. `'*'` reflects any request * origin — acceptable because CORS here is transport permission, not * authorization: bearer tokens are the security boundary, and the * per-credential `origins` claim (plus per-grant allowlists) carries * the actual origin policy, which a static server-wide list cannot * express. Pass an explicit list to pin instead. Absent = CORS off * (today's behavior: same-origin or proxy-fronted deployments). */ corsOrigins?: '*' | ReadonlyArray; /** * Optional Kysely DB handle. When supplied together with `objectStore`, * the tenant/deployment admin surfaces are registered. Engine-only * deployments can omit both. */ db?: Kysely; objectStore?: ObjectStoreWithInfo; /** * Optional envelope keyring for features that need short-lived * encrypted server state (for example encrypted PDF password * sessions in the CDN phase). Presently stored on the app bundle * so future services can consume it without changing boot wiring. */ kms?: KmsKeyring; /** * Optional CDN signer. When omitted, the access route falls back to * a built-in `NoneCdnSigner` (origin reads only, no signing). Wire * a real signer to enable per-caller signed URLs / cookies and * surface them via the /access response. */ cdnSigner?: CdnSigner; /** * HMAC secret for password verification cache rows. The cache stores an * HMAC proof of the document password — non-reversible only while this * secret stays secret and strong, so production-license deployments must * set it (>= 32 random bytes; env `CLOUDPDF_PASSWORD_VERIFICATION_HMAC_SECRET`) * and buildApp refuses to boot otherwise. Development licenses fall back * to a local-only constant. */ pdfPasswordVerificationHmacSecret?: string; pdfPasswordVerificationTtlMs?: number; /** * Server-side key material for encrypted password sessions: signs renewal * grants and feeds the final-key derivation. Same production rule as the * verification secret (>= 32 random bytes; env * `CLOUDPDF_PASSWORD_SESSION_SERVER_SECRET`, id via `..._SECRET_ID`). */ pdfPasswordSessionServerSecret?: string | Buffer; pdfPasswordSessionServerSecretId?: string; pdfPasswordSessionTtlMs?: number; pdfPasswordSessionRenewalTtlMs?: number; /** * If true and an admin call arrives for a tenant that doesn't have a * `tenants` row, lazily create one. Convenient for dev / single-tenant * deploys; production deployments should leave this off and provision * explicitly. */ autoProvisionTenant?: boolean; /** * Interval for the background sweeper that GCs `pending` rows older * than `pendingTtlMs`. Set to 0 to disable. Defaults to 60_000 ms. */ sweepIntervalMs?: number; /** How long a layer's worker session may go unasked before the sweeper closes it. Default 10 minutes. */ layerSessionIdleMs?: number; /** Most layer sessions one document keeps open; opening one more closes the least recently asked-for. Default 32. */ maxLayerSessionsPerDoc?: number; /** Max age of a `pending` doc before it's considered abandoned. */ pendingTtlMs?: number; /** * How long a document may stay `deleting` before the sweeper finishes the * delete itself. A live delete finishes well within it. Default 1 minute. */ deletingGraceMs?: number; /** * When supplied (with `db`, `objectStore`, and a worker pool), * enables the cloud `/v1/docs/...` routes via the * `DocumentService` orchestrator. The required pieces are: * * - `cacheRoot` absolute path the BaseFileCache uses * - `cacheMaxBytes` disk budget (default 4 GiB) * - `maxDocsPerSlot` worker pool slot capacity (default 64) * * Disable by leaving `cacheRoot` unset. */ cacheRoot?: string; /** * Where signing candidates are written between prepare and the upload * of their tail, and rebuilt for completion. Shared by this process and * the engine workers (same machine); defaults to `defaultSigningRoot()`. */ signingRoot?: string; /** How long a prepared signing may wait for its CMS (default 15 minutes). */ signingTtlMs?: number; cacheMaxBytes?: number; maxDocsPerSlot?: number; /** * Migration set this build expects to be applied. When supplied * (alongside `db`), buildApp runs `validate()` at boot and refuses * to start if the DB has drift (checksum mismatch on an applied * migration, or a migration applied in DB but missing in code). * * Set `failOnPending: true` to also refuse to start when pending * migrations exist — recommended for production where operators * run `migrate up` explicitly before rolling out new pods. */ expectedMigrations?: ReadonlyArray; /** Treat pending migrations as drift at boot. Defaults to false. */ failOnPending?: boolean; /** * The render lattice: canonical full-page * `viewport.width` points whose renders are durable derived artifacts — * the bounded quantity is output pixels, never zoom. `maxRenderPixels` * is the worker-side allocation budget every server render carries. * `enforce: true` rejects off-lattice versioned full-page tokens with * 400 (flip on once clients ship `snapFullPageViewport`); rect targets * are exempt (the future tile policy's jurisdiction). Default false = * off-lattice renders are computed but never persisted. * `appearanceScales` is the annotation-appearance scale lattice * (default `[1, 2, 4]`) — enforced the same way on versioned * appearance tokens. */ renderLattice?: { widths?: number[]; appearanceScales?: number[]; maxRenderPixels?: number; enforce?: boolean; }; /** * Budget for `app.close()` inside `shutdown()` before teardown * proceeds anyway (default 30s). Keep it below the supervisor's kill * deadline (Kubernetes `terminationGracePeriodSeconds`, `docker stop` * timeout) so pool + cache teardown always runs before SIGKILL. */ shutdownTimeoutMs?: number; /** * Settle window between failing readiness (+ ending SSE streams) and * closing the listener (default 0). For probe-driven balancers that * must observe `/readyz` 503 before the socket starts refusing; * Kubernetes deployments use a preStop sleep instead. */ shutdownDrainMs?: number; /** * Expose a Prometheus `/metrics` endpoint (`CLOUDPDF_METRICS=1`). * Unauthenticated when enabled — scrape it inside the private * network/cluster, like any /metrics. */ metrics?: boolean; /** * Engine plane placement. `inline` (default): PDFium worker threads in * this process — a native crash costs the process. `host`: a * supervised child process — a native crash costs one engine respawn * (in-flight engine calls reject `RuntimeUnavailable`), never the API. */ engineIsolation?: 'inline' | 'host'; /** * Entry script for the engine-host child (host mode). The CLI passes * its dist URL; tests pass the TS source (with `engineHostExecArgv` * carrying a loader). Required when `engineIsolation: 'host'`. */ engineHostEntry?: URL | string; /** Encode renders inside the engine worker so only * compressed images cross the engine boundary (default true). `false` * is the one-release escape hatch (`CLOUDPDF_ENCODE_IN_ENGINE=0`): * raw rasters over the boundary + API-side sharp, exactly the * previous API-side encoding pipeline. */ encodeInEngine?: boolean; /** Admission control (lanes + bounded queues + shed). Defaults are * computed from the pool's slot count; `false` disables the decorator * entirely (raw-pool tests). */ scheduling?: EngineSchedulingConfig | false; /** Engine recycling policy — opt-in (absent = telemetry only, no * recycler). Host isolation required; validated at boot by * `resolveRecycleConfig` in the bin. */ recycle?: EngineRecyclePolicy; /** Engine shard count (host isolation only). Default 1 = * today's exact object graph; K > 1 requires the resolved worker * total to divide evenly (M % K === 0, validated here). */ engineShards?: number; /** Extra execArgv for the forked engine host (tests: ['--import','tsx']). */ engineHostExecArgv?: string[]; /** * How long the engine host may be down before `/readyz` fails * (default 10s). A sub-second respawn must never flap the pod out of * its load balancer — readiness reacts to persistent engine * unavailability only; the health detail is always in the body. */ engineUnreadyAfterMs?: number; /** * Crash-journal posture (host mode + db only). Observe-only by * default: every engine-host death and its suspects are journaled and * quarantine decisions are computed and persisted — but nothing is * refused until `enforce` is set. */ quarantine?: { enforce?: boolean; ttlHours?: number }; } export interface AppBundle { app: FastifyInstance; /** The installed plugins' permissions, from their modules (empty without any). */ permissions: PermissionRegistry; /** Every route the app mounted, in the order it mounted them. */ routes: readonly MountedRoute[]; /** Present only when `workerEntry` was supplied. */ pool?: EnginePool; /** Present only when `db` + `objectStore` were configured. */ lifecycle?: DocumentLifecycleService; /** The derived-artifact plane for renders (cacheRoot + pool + db). */ derivedRenders?: DerivedRenderService; /** Present only when `enableRevocation: true` with a `db`. */ revokedJtisGuard?: RevokedJtisGuard; /** Present whenever a `db` is configured; tests use it to clear the TTL cache. */ suspendedTenantsGuard?: SuspendedTenantsGuard; /** Present whenever a `db` is configured: the tenants' features, which gate module routes. */ tenantFeaturesGuard?: TenantFeaturesGuard; /** Present only when `cacheRoot` is set (+ pool + db). */ documentService?: DocumentService; /** Write-side lazy layer materialization service. */ layerService?: LayerService; /** The base-file cache backing `documentService`. */ baseFileCache?: BaseFileCache; /** Security substrate keyring, when configured by the caller. */ kms?: KmsKeyring; /** Present in host mode with a db: the engine crash journal. */ crashJournal?: CrashJournal; /** * Host mode only: the raw EngineHostClient (bundle.pool may be the * quarantine decorator). Drills and boundary tests need its * `hostPid()`/`engineBuildId()`. */ engineHost?: EngineHostClient; /** All engine shards (host mode; length = engineShards, [engineHost] at K=1). */ engineHosts?: EngineHostClient[]; /** Admission-control decorator (present unless `scheduling: false`). */ engineScheduler?: SchedulingEnginePool; /** Operational counters used by metrics and tests. */ engineCounters?: EngineCounters; /** * Flip `/readyz` to 503 and end every live SSE stream without closing * the listener. `shutdown()` calls this first; exposed for operators * and tests that need the drain state without the teardown. */ beginDrain: () => void; shutdown: () => Promise; } /** * @license FCL-1.0-ALv2 * * Warning: The server-construction and request-gating code 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. * * Build the Fastify app with JWT auth, admin routes, and the cloud * document routes when their adapters are configured. Caller is * responsible for `app.listen()`. */ /** Engine-shard validation runs before any machinery (license gate included) * boots, so a bad shard config fails instantly with only this message. * Called by both public and testing entries. */ /** What the app is built from: the options, with the license already resolved to its gate. */ type LicensedAppOptions = Omit & { licenseGate: LicenseGate }; function validateShardOptions(opts: Omit): void { const shardCount = opts.engineShards ?? 1; if (!Number.isInteger(shardCount) || shardCount < 1) { throw new Error(`buildApp: engineShards must be an integer ≥ 1, got ${shardCount}`); } if (shardCount > 1) { if (opts.engineIsolation !== 'host') { throw new Error("buildApp: engineShards > 1 requires engineIsolation 'host'"); } const totalWorkers = resolvePoolSize(opts.poolSize); if (shardCount > totalWorkers || totalWorkers % shardCount !== 0) { const valid = Array.from({ length: totalWorkers }, (_, i) => i + 1).filter( (k) => totalWorkers % k === 0, ); throw new Error( `buildApp: engineShards=${shardCount} needs the worker total (${totalWorkers}) to divide evenly — ` + `valid shard counts here: ${valid.join(', ')} (unweighted routing cannot honor uneven capacity)`, ); } } } export async function buildApp(opts: BuildAppOptions): Promise { validateShardOptions(opts); const { license, ...options } = opts; return buildAppUnchecked({ ...options, licenseGate: licenseRuntimeOf(license) }); } /** * Internal test-only construction seam: builds with any gate. Not exported by * the npm package, nor named in its types. */ export async function buildAppForTesting(opts: LicensedAppOptions): Promise { // The isolation matrix: CLOUDPDF_TEST_ISOLATION=host runs the whole // suite against the child-process engine host (same tests, same // assertions — byte-identical results is the acceptance bar). const engineIsolation = opts.engineIsolation ?? (process.env['CLOUDPDF_TEST_ISOLATION'] === 'host' ? 'host' : 'inline'); const testShards = process.env['CLOUDPDF_TEST_SHARDS']; const engineShards = opts.engineShards ?? (testShards !== undefined ? Number(testShards) : undefined); // Matrix-leg pragmatics: most fixtures pin poolSize 1, which cannot // divide across K > 1 — round the worker total up to a multiple of K // so the alternate-topology leg boots (an intentional distortion: // the leg tests K-topology behavior, not exact worker counts). const poolSize = engineShards !== undefined && engineShards > 1 && opts.engineIsolation !== 'inline' ? Math.ceil((opts.poolSize ?? engineShards) / engineShards) * engineShards : opts.poolSize; // Teardown must fit inside the runner's hook budget, with margin. The // production default (30s) exists so real in-flight traffic can finish // before a supervisor's kill deadline — but it happens to equal // vitest's `hookTimeout`, so a single stuck connection at teardown // burns the whole budget and the hook fails with "Hook timed out in // 30000ms" instead of costing a blink. Proven: one never-finishing // request makes `shutdown()` take exactly 30.0s. Tests have no // supervisor and no long-running traffic, so bound it hard here; // a fixture that genuinely needs longer passes its own value. const shutdownTimeoutMs = opts.shutdownTimeoutMs ?? 2_000; if (engineIsolation === 'host') { return buildAppUnchecked({ ...opts, engineIsolation, shutdownTimeoutMs, ...(engineShards !== undefined ? { engineShards } : {}), ...(poolSize !== undefined ? { poolSize } : {}), engineHostEntry: opts.engineHostEntry ?? new URL('../runtime/engine-host-entry.ts', import.meta.url), engineHostExecArgv: opts.engineHostExecArgv ?? ['--import', 'tsx'], }); } return buildAppUnchecked({ ...opts, engineIsolation, shutdownTimeoutMs }); } async function buildAppUnchecked(opts: LicensedAppOptions): Promise { validateShardOptions(opts); // The cross-replica doorbell exists for the whole app lifetime: mutation // signals for SSE, revocation pushes for the auth guard + open streams. const realtimeBus = opts.realtimeBus ?? new InProcessRealtimeBus(); // Operational counters are created unconditionally (cheap plain numbers); // /metrics surfaces them when enabled. const engineCounters = createEngineCounters(); // Secret hygiene is license-keyed: development keys + the test gate keep // zero-config dev fallbacks; every other license refuses to boot on // missing / publicly-known / short secrets (fail closed). const enforceProductionSecrets = requiresProductionSecrets(opts.licenseGate.getStatus()); // The installed plugins' permissions, from their modules: checked and // registered before anything starts, so a module's mistake stops the boot. const permissions = new PermissionRegistry(); const declaredModules = declareModules( opts.modules ?? [], permissions, opts.moduleEnv ?? process.env, ); const app = Fastify({ logger: { level: process.env['LOG_LEVEL'] ?? 'info', }, ...(opts.trustProxy !== undefined ? { trustProxy: trustedProxies(opts.trustProxy) } : {}), bodyLimit: opts.bodyLimit ?? 50 * 1024 * 1024, // Use Fastify's default (`fast-querystring`) which yields a flat // Record — `?viewport.kind=width` parses as // `{ "viewport.kind": "width" }`, not `{ viewport: { kind: "width" } }`. // The render wire format depends on this: dotted keys are reassembled // into nested objects by `unflatten()` in the route handler. Do not // switch to `qs` or another nesting parser — it would silently pre-nest // these keys and break the wire-roundtrip property. // // Bump the router's default `maxParamLength` (find-my-way's hard cap is // 100 chars by default) so render tokens like // `render@annotationVersion=N,background=X,contentVersion=N,format=webp,…` // can exceed that ceiling without 404-ing at the router. The token // codec separately enforces a 512-char limit, so this stays bounded. maxParamLength: 512, }); registerApiVersion(app); const routes: MountedRoute[] = []; app.addHook('onRoute', (route) => { for (const method of [route.method].flat()) routes.push({ method, url: route.url }); }); // A CDN in front of the engine: shared caches may keep versioned reads, // and /head asks for /access before the first cacheable read. const cdnFronted = (opts.cdnSigner?.info.kind ?? 'none') !== 'none'; app.decorate('immutableCache', cdnFronted ? IMMUTABLE_CACHE_SHARED : IMMUTABLE_CACHE_PRIVATE); const usageMeters = opts.db ? new UsageMeters(opts.db, opts.licenseGate) : undefined; app.addHook('onRequest', async (request, reply) => { const pathname = request.url.split('?', 1)[0] ?? request.url; if (pathname === '/healthz' || pathname === '/readyz' || pathname === '/v1/license/status') { return; } // Operational telemetry must stay scrapeable in restricted mode — // observing a deployment is not protected functionality. if (opts.metrics === true && pathname === '/metrics') { return; } const license = opts.licenseGate.getStatus(); if (license.code !== 'VALID' && license.code !== 'VALID_TEST_LICENSE') { reply.header('X-CloudPDF-License-Status', license.code); } if ( license.access === 'none' || (license.access === 'restricted' && !isReadOnlyLicenseRequest(request.method, pathname)) ) { return reply .code(403) .send(errorBody('LicenseInvalid', license.message, { licenseCode: license.code })); } }); app.addHook('onClose', async () => { await realtimeBus.close(); }); // CORS before the auth hook so preflights (which carry no // Authorization) are answered instead of 401'd. `credentials` stays // false: the bearer rides an explicit header, never cookies. if (opts.corsOrigins !== undefined) { await app.register(cors, { origin: opts.corsOrigins === '*' ? true : [...opts.corsOrigins], methods: ['GET', 'POST', 'PATCH', 'DELETE'], allowedHeaders: [ 'authorization', 'content-type', 'x-engine-session-id', 'last-event-id', // Names a change a retry must not repeat. 'idempotency-key', // Asks a write to top the editing session's object numbers up. 'embedpdf-reserve-object-numbers', // Document affinity: SDKs may send the document routing key; the server // never parses it, but the preflight must allow it. 'x-cloudpdf-doc', // The version the client speaks. 'embedpdf-version', ], // Response headers cross-origin JS may read (nothing is safelisted // beyond the basics): the backpressure hint + the advisory // dimension headers clients already consume. exposedHeaders: [ 'retry-after', 'x-embedpdf-image-width', 'x-embedpdf-image-height', 'x-embedpdf-appearance-count', // The object numbers a write handed the editing session. 'embedpdf-object-numbers', // This server's engine value, on an answer to a URL that named another. 'embedpdf-engine', // The version this server is. 'embedpdf-server-version', ], credentials: false, maxAge: 86_400, }); } await app.register(compress, { global: true, threshold: 1024, encodings: ['br', 'gzip', 'deflate'], }); await app.register(multipart, { limits: { fileSize: opts.bodyLimit ?? 50 * 1024 * 1024 }, }); // Raw PDF parsers are retained for document APIs that accept binary // payloads. Upload proxy itself is multipart-only for SDK portability. app.addContentTypeParser( 'application/pdf', { parseAs: 'buffer', bodyLimit: opts.bodyLimit ?? 50 * 1024 * 1024 }, (_req, body, done) => done(null, body), ); app.addContentTypeParser( 'application/octet-stream', { parseAs: 'buffer', bodyLimit: opts.bodyLimit ?? 50 * 1024 * 1024 }, (_req, body, done) => done(null, body), ); // Fastify's stock JSON parser rejects a bodyless request that still // advertises `Content-Type: application/json` (FST_ERR_CTP_EMPTY_JSON_BODY). // Real clients send exactly that shape on bodyless calls — the Fern // PHP/Go/Ruby SDKs stamp the header unconditionally, as do axios // instances with default headers and `curl -H` scripts — so treat an // empty body as no body. Non-empty bodies still go through the default // parser (keeping secure-json-parse's prototype-poisoning protection), // and handlers that require a body still 400 on `undefined` via their // zod parsing. const defaultJsonParser = app.getDefaultJsonParser('error', 'error'); app.addContentTypeParser( 'application/json', { parseAs: 'string', bodyLimit: opts.bodyLimit ?? 50 * 1024 * 1024 }, (req, body, done) => { if (body === '' || body == null) { done(null, undefined); return; } defaultJsonParser(req, body, done); }, ); // Optional revocation + JWKS persistence guards. Both are no-ops // unless explicitly enabled — admin-only tests / dev runs don't // need them and they require a DB. let revokedJtisGuard: RevokedJtisGuard | undefined; let revocation: RevocationCheck | undefined; if (opts.enableRevocation && opts.db) { revokedJtisGuard = new RevokedJtisGuard({ db: opts.db, realtime: realtimeBus }); revocation = revokedJtisGuard; } let jwksCacheStore: JwksCacheStore | undefined; if (opts.enableJwksPersistence && opts.db) { jwksCacheStore = new DbJwksCacheStore(opts.db); } // Tenant suspension gate: consulted by the auth hook for every JWT // and by the grant exchange. API-token requests never touch it. const suspendedTenantsGuard = opts.db ? new SuspendedTenantsGuard({ db: opts.db }) : undefined; // Tenant features: which modules a tenant may use, asked on every // module route. Like suspension, the operator's switch. const tenantFeaturesGuard = opts.db ? new TenantFeaturesGuard({ db: opts.db }) : undefined; // What each tenant used, per UTC day: the core's meters and modules'. const tenantUsage = opts.db ? new TenantUsageRepo(opts.db) : undefined; // The deployment can sign iff it verifies with the shared secret — // the one condition gating every minting surface: tokens.issue, the // grant routes, and the public exchange. Asymmetric/JWKS // deployments verify only; their backends mint with their own keys. const verifierForSigning = opts.verifier; const signer = verifierForSigning.mode === 'hs256' ? (input: SignDevTokenInput) => signDevToken(verifierForSigning.secret, input) : undefined; // Grant visitors' handles are signed by the same authority. const visitorHandles = verifierForSigning.mode === 'hs256' ? new VisitorHandles(verifierForSigning.secret) : undefined; // Inject the revocation + cache store into whichever mode the // caller picked. We don't overwrite if they're already set. const verifierConfig = { ...opts.verifier, revocation: opts.verifier.revocation ?? revocation, ...(opts.verifier.mode === 'jwks' && !opts.verifier.cacheStore ? { cacheStore: jwksCacheStore } : {}), } as JwtVerifierConfig; if (enforceProductionSecrets && verifierConfig.mode === 'hs256') { assertProductionSecret(verifierConfig.secret, { name: 'JWT HS256 secret', envVar: 'CLOUDPDF_JWT_SECRET', option: 'verifier.secret', }); } const apiAuthTokens = (opts.apiAuthTokens ?? []).filter((token) => token.length > 0); if (enforceProductionSecrets) { for (const [index, token] of apiAuthTokens.entries()) { assertProductionSecret(token, { name: `API authentication token ${index + 1}`, envVar: 'CLOUDPDF_API_AUTH_TOKENS', option: `apiAuthTokens[${index}]`, }); } } await registerJwtAuth(app, { verifier: verifierConfig, ...(apiAuthTokens.length > 0 ? { apiAuthTokens } : {}), ...(opts.authFailureLimit !== undefined ? { authFailureLimit: opts.authFailureLimit } : {}), ...(suspendedTenantsGuard ? { suspendedTenants: suspendedTenantsGuard } : {}), // The exchange is the one public v1 surface: the grant row is the // authorization, and the route carries its own limiters. /metrics // joins it when enabled (network-level protection, like any // Prometheus target). ...((): { publicPaths?: string[] } => { const publicPaths = [ ...(signer && opts.db && opts.objectStore ? [adminWirePaths.grantSessions] : []), ...(opts.metrics === true ? ['/metrics'] : []), ]; return publicPaths.length > 0 ? { publicPaths } : {}; })(), }); // `documentService` is allocated below, but the pool's onEvict // hook needs to reference it. Use a forward-binding closure: // `evictForward` defers to whatever lives in `documentService` at // call time. Without this, we'd need to construct the pool twice // or expose a mutable setter on the service — both worse. let documentService: DocumentService | undefined; const evictForward = (evt: { docId: string; baseSha: string; slot: number }): void => { documentService?.onPoolEvict(evt); }; let pool: EnginePool | undefined; let schedulingPool: SchedulingEnginePool | undefined; let engineRecycler: EngineRecycler | undefined; const queueWaitObserver: { current: ((lane: 'interactive' | 'background', waitMs: number) => void) | null; } = { current: null }; let crashJournal: CrashJournal | undefined; let engineHost: EngineHostClient | undefined; let engineHosts: EngineHostClient[] = []; let engineSharded: ShardedEnginePool | undefined; const shardRestarts: number[] = []; let engineRestartCount = 0; const signingRoot = opts.signingRoot ?? defaultSigningRoot(); if (opts.workerEntry) { if (opts.engineIsolation === 'host') { if (!opts.engineHostEntry) { throw new Error("buildApp: engineIsolation 'host' requires engineHostEntry"); } crashJournal = opts.db ? new CrashJournal({ db: opts.db, enforce: opts.quarantine?.enforce ?? false, ...(opts.quarantine?.ttlHours !== undefined ? { ttlMs: opts.quarantine.ttlHours * 60 * 60 * 1_000 } : {}), log: (level, msg, meta) => app.log[level]({ ...meta }, msg), }) : undefined; const shardCount = opts.engineShards ?? 1; if (shardCount === 1) { // K = 1 is today'S exact object graph — no composite exists. pool = await EngineHostClient.create({ hostEntry: opts.engineHostEntry, boot: { workerEntry: String(opts.workerEntry), ...(opts.poolSize !== undefined ? { poolSize: opts.poolSize } : {}), ...(opts.maxDocsPerSlot !== undefined ? { maxDocsPerSlot: opts.maxDocsPerSlot } : {}), fonts: opts.fonts ?? [], signingRoot, }, onEvict: evictForward, // Forget everything on host death: durable writes make the lazy // rebuild from durable truth safe; the generation fence closes the // mid-commit window (DocumentService.advanceLayerSession). onHostRestart: () => { engineRestartCount += 1; documentService?.onHostRestart(); }, // Fire-and-forget by design: journaling must never delay respawn. ...(crashJournal ? { onHostCrash: (evt: Parameters[0]) => void crashJournal!.recordCrash(evt), } : {}), ...(opts.engineHostExecArgv ? { execArgv: opts.engineHostExecArgv } : {}), }); engineHost = pool as EngineHostClient; engineHosts = [engineHost]; } else { // Sharding: the parent resolves the worker total once and splits it — // children never self-resolve (the size env is not whitelisted, // and K independent cpu-defaults would multiply the fleet). const totalWorkers = resolvePoolSize(opts.poolSize); const perShard = totalWorkers / shardCount; for (let i = 0; i < shardCount; i++) shardRestarts.push(0); engineSharded = await ShardedEnginePool.create({ count: shardCount, spawn: (shard, hooks) => EngineHostClient.create({ hostEntry: opts.engineHostEntry!, boot: { workerEntry: String(opts.workerEntry), poolSize: perShard, ...(opts.maxDocsPerSlot !== undefined ? { maxDocsPerSlot: opts.maxDocsPerSlot } : {}), fonts: opts.fonts ?? [], signingRoot, }, onEvict: hooks.onEvict, onHostRestart: hooks.onHostRestart, ...(crashJournal ? { onHostCrash: hooks.onHostCrash } : {}), ...(opts.engineHostExecArgv ? { execArgv: opts.engineHostExecArgv } : {}), }), onEvict: (evt) => evictForward(evt), // Fire-and-forget by design; the journal is shard-agnostic // (a shard is an intra-process replica). onHostCrash: (evt) => { if (crashJournal) void crashJournal.recordCrash(evt); }, onHostRestart: (scope, shard) => { engineRestartCount += 1; shardRestarts[shard] += 1; app.log.warn( { shard, residents: scope.docIds.size }, 'engine shard restarted (scoped forget)', ); documentService?.onHostRestart(scope); }, }); engineHosts = engineSharded.hosts(); engineHost = engineHosts[0]!; pool = engineSharded; } if (crashJournal) { pool = new QuarantiningEnginePool(pool, crashJournal, () => engineHost!.engineBuildId()); } } else { pool = await WorkerThreadPool.create({ size: opts.poolSize, workerEntry: opts.workerEntry, maxDocsPerSlot: opts.maxDocsPerSlot, onEvict: evictForward, fonts: opts.fonts, signingRoot, }); } // Admission control wraps outermost in both isolation modes: lanes // and shed decisions happen before quarantine checks or dispatch. // `scheduling: false` disables (tests that assert raw pool behavior). if (opts.scheduling !== false) { const userHook = opts.scheduling ? opts.scheduling.onQueueWait : undefined; const scheduler = new SchedulingEnginePool(pool, { ...(opts.scheduling ?? {}), onQueueWait: (lane, waitMs) => { queueWaitObserver.current?.(lane, waitMs); userHook?.(lane, waitMs); }, }); schedulingPool = scheduler; pool = scheduler; } if (opts.recycle && !engineHost) { throw new Error( "buildApp: `recycle` requires engineIsolation 'host' — there is no child process to recycle inline", ); } if (opts.recycle && engineHost) { engineRecycler = new EngineRecycler( () => engineHosts, () => readCgroupMemory(), opts.recycle, (d) => app.log.info({ reason: d.reason, graceful: d.graceful }, 'engine host recycled'), (err) => app.log.warn({ err }, 'engine recycler tick failed'), ); engineRecycler.start(); } } const drainCoordinator = new DrainCoordinator(); // Readiness = "safe to route traffic here": not draining, and the // database answers. License-restricted mode stays ready on purpose — // a lapsed license degrades to read-only; it must never restart-loop // or pull the deployment out of every balancer. The object store is // deliberately not probed: a transient bucket blip must not amputate // the whole fleet's endpoints. The DB result is cached briefly so // probe storms (N replicas × N balancers) cost ~one ping per window — // including while the DB is down. const DB_READY_TTL_MS = 5_000; const DB_READY_TIMEOUT_MS = 2_000; let dbReadyCache = { at: 0, ok: true }; const dbReady = async (): Promise => { if (!opts.db) return true; if (Date.now() - dbReadyCache.at < DB_READY_TTL_MS) return dbReadyCache.ok; const ping = sql`SELECT 1`.execute(opts.db).then( () => true, () => false, ); let timer: NodeJS.Timeout | undefined; const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(false), DB_READY_TIMEOUT_MS); timer.unref?.(); }); const ok = await Promise.race([ping, timeout]); if (timer) clearTimeout(timer); dbReadyCache = { at: Date.now(), ok }; return ok; }; if (opts.metrics === true) { const cgroupReadable = readCgroupMemory() !== null; registerMetrics(app, { pool, licenseGate: opts.licenseGate, counters: engineCounters, ...(engineHost ? { engineRestarts: () => engineRestartCount } : {}), ...(engineHost ? { engineMemory: () => (engineSharded ? engineSharded.memory() : engineHost!.memory()) } : {}), ...(engineHost ? { engineRecycles: () => { const total: Record = {}; for (const h of engineHosts) { for (const [reason, n] of Object.entries(h.recycleStats())) { total[reason] = (total[reason] ?? 0) + n; } } return total; }, } : {}), ...(engineSharded ? { shards: () => engineHosts.map((h, shard) => ({ shard, up: h.health().state === 'ready', restarts: shardRestarts[shard] ?? 0, recycles: h.recycleStats(), })), } : {}), ...(crashJournal ? { crashJournal } : {}), ...(cgroupReadable ? { cgroup: () => readCgroupMemory() } : {}), ...(schedulingPool ? { scheduling: () => schedulingPool!.schedulingStats() } : {}), ...(schedulingPool ? { queueWaitObserver } : {}), }); } app.get('/healthz', async () => ({ status: 'ok' })); const engineUnreadyAfterMs = opts.engineUnreadyAfterMs ?? 10_000; app.get('/readyz', async (_req, reply) => { const license = opts.licenseGate.getStatus(); const engine = pool?.health() ?? null; if (drainCoordinator.isDraining) { return reply.code(503).send({ license, engine, status: 'draining' }); } if (!(await dbReady())) { return reply.code(503).send({ license, engine, status: 'unready', reasons: ['database'] }); } // Engine readiness with a persistence threshold: a sub-second host // respawn must not amputate the pod from every balancer. if (engine && engine.state !== 'ready' && (engine.downSinceMs ?? 0) >= engineUnreadyAfterMs) { return reply.code(503).send({ license, engine, status: 'unready', reasons: ['engine'] }); } return { license, engine, status: 'ok' }; }); app.get('/v1/license/status', async () => opts.licenseGate.getStatus()); // Deployment surface: API token only — license state, reporting, and // meters are deployment-global, so no tenant credential may read them. const licenseStatusOp = adminOperations['deployment.licenseStatus']; app.route({ method: licenseStatusOp.method, url: licenseStatusOp.path, handler: async (request) => { requireApiToken(request); return { license: opts.licenseGate.getStatus(), reporting: opts.usageReporter ? await opts.usageReporter.status() : null, usage: usageMeters ? await usageMeters.snapshot() : null, }; }, }); const modules = moduleManifests(declaredModules, permissions); const modulesOp = adminOperations['deployment.modules']; app.route({ method: modulesOp.method, url: modulesOp.path, handler: async (request) => { requireApiToken(request); return { modules }; }, }); // Drift detection at boot. Production deployments should supply // `expectedMigrations` — if the DB has a checksum mismatch or an // applied migration vanished from code, we refuse to serve traffic // rather than silently running on an unexpected schema. This is the // safety net for "someone edited a migration and force-rolled it". if (opts.db && opts.expectedMigrations && opts.expectedMigrations.length > 0) { const issues = await validateMigrations(opts.db, opts.expectedMigrations, { treatPendingAsDrift: opts.failOnPending ?? false, }); if (issues.length > 0) { const lines = issues.map((i) => ` - [${i.kind}] ${i.message}`).join('\n'); throw new Error(`buildApp: migration drift detected, refusing to start:\n${lines}`); } } let lifecycle: DocumentLifecycleService | undefined; let importWorker: ImportWorker | undefined; let layerService: LayerService | undefined; let derivedRenders: DerivedRenderService | undefined; let serverFonts: ServerFonts | undefined; let sweeperTimer: NodeJS.Timeout | undefined; let baseFileCache: BaseFileCache | undefined; if (opts.db && opts.objectStore) { if (opts.cacheRoot && pool) { baseFileCache = new BaseFileCache({ root: opts.cacheRoot, maxBytes: opts.cacheMaxBytes ?? 4 * 1024 * 1024 * 1024, store: opts.objectStore, // Failed materialises were once completely silent (callers // like the security probe swallow them by design) — always // give them a log line. onEvent: (e) => { if (e.kind === 'materialize-error') { app.log.warn({ sha: e.sha, error: e.error }, 'base file cache: materialize failed'); } }, }); // One-shot boot sweep: a crash during a prior materialise can // leave `.partial.*` files behind. Better to clean them up // here than to surface bogus disk-usage stats to ops. await baseFileCache.sweepPartials(); } // The derived-artifact plane for renders. // Needs a worker + the base-file cache — admin-only deploys skip it. if (baseFileCache && pool) { serverFonts ??= new ServerFonts(pool); derivedRenders = new DerivedRenderService({ storage: opts.objectStore, ...(opts.renderLattice?.widths ? { widths: opts.renderLattice.widths } : {}), ...(opts.renderLattice?.appearanceScales ? { appearanceScales: opts.renderLattice.appearanceScales } : {}), ...(opts.renderLattice?.maxRenderPixels !== undefined ? { maxRenderPixels: opts.renderLattice.maxRenderPixels } : {}), ...(opts.renderLattice?.enforce !== undefined ? { enforce: opts.renderLattice.enforce } : {}), cache: baseFileCache, pool, encoder: new SharpImageEncoder(), ...(opts.encodeInEngine !== undefined ? { encodeInEngine: opts.encodeInEngine } : {}), documents: new DocumentsRepo(opts.db), serverFonts, onWarmError: (err, ctx) => app.log.warn({ err, ...ctx }, 'thumbnail warm failed; thumbnailState=failed'), }); } const importPolicy = opts.importPolicy ?? defaultImportPolicy(); const documentImportsRepo = new DocumentImportsRepo(opts.db); lifecycle = new DocumentLifecycleService({ documents: new DocumentsRepo(opts.db), tenants: new TenantsRepo(opts.db), folders: new FoldersRepo(opts.db), uploadTokenUses: new UploadTokenUsesRepo(opts.db), storage: opts.objectStore, autoProvisionTenant: opts.autoProvisionTenant ?? false, uploadProxyPolicy: opts.uploadProxyPolicy ?? 'fallback-only', importPolicy: importPolicy, importConnections: new ImportConnectionRegistry(opts.importConnections ?? []), documentImports: documentImportsRepo, baseVersions: new BaseVersionsRepo(opts.db), db: opts.db, securityProbe: new DocumentSecurityProbe({ cache: baseFileCache, pool, onError: (err, ctx) => app.log.warn({ err, ...ctx }, 'security probe failed; recording unknown security state'), }), ...(baseFileCache ? { fileCache: baseFileCache } : {}), ...(derivedRenders ? { derivedRenders } : {}), ...(usageMeters ? { usageMeters } : {}), tenantUsage: tenantUsage!, grants: new GrantsRepo(opts.db), }); await registerAdminDocumentsRoutes(app, { lifecycle, storage: opts.objectStore, }); await registerAdminFoldersRoutes(app, { folders: new FolderService({ db: opts.db, tenants: new TenantsRepo(opts.db), autoProvisionTenant: opts.autoProvisionTenant ?? false, finishDeletes: (tenantId, docIds) => { lifecycle! .finishDeletes(tenantId, docIds) .catch((err) => app.log.error( { err, tenantId }, 'finishing a folder delete failed; the sweeper retries', ), ); }, }), }); const storedLayers = { db: opts.db, storage: opts.objectStore, documents: new DocumentsRepo(opts.db), }; // The layer service exists only where the engine runs; it is made below. const deleteLayer = (tenantId: string, input: { docId: string; layerName: string }) => layerService ? layerService.deleteLayer(tenantId, input) : deleteStoredLayer(storedLayers, tenantId, input); await registerAdminLayersRoutes(app, { deleteLayer, layers: new LayersRepo(opts.db), documents: new DocumentsRepo(opts.db), grants: new GrantsRepo(opts.db), }); // The async-import claim loop: in-process (like the sweeper), one // per replica, safe under multi-replica via fenced leased claims. if (importPolicy.enabled) { importWorker = new ImportWorker({ jobs: documentImportsRepo, documents: new DocumentsRepo(opts.db), lifecycle, storage: opts.objectStore, policy: importPolicy, ...(opts.importWorkerPollMs !== undefined ? { pollMs: opts.importWorkerPollMs } : {}), onError: (err, ctx) => app.log.warn({ err, ...ctx }, 'import worker error'), }); importWorker.start(); } await registerAdminTenantsRoutes(app, { tenants: new TenantsRepo(opts.db), storage: opts.objectStore, securityEvents: new SecurityEventsRepo(opts.db), suspendedTenants: suspendedTenantsGuard!, tenantFeatures: tenantFeaturesGuard!, tenantUsage: tenantUsage!, modules: declaredModules.map(({ module }) => module.id), moduleMeters: moduleMeterNames(declaredModules), }); // Issue mounts only when the deployment can sign (HS256 — the // verifier secret doubles as signing material); revoke only when // revocation is enabled. Both write security_events. await registerAdminTokensRoutes(app, { ...(revokedJtisGuard ? { guard: revokedJtisGuard } : {}), ...(signer ? { sign: signer } : {}), documents: new DocumentsRepo(opts.db), folders: new FoldersRepo(opts.db), securityEvents: new SecurityEventsRepo(opts.db), permissions, }); // The grant family (grant lifecycle + public exchange) exists only // where minting does — same condition as tokens.issue, because a // grant is a standing mint capability. if (signer && visitorHandles) { const grants = new GrantsRepo(opts.db); await registerAdminGrantsRoutes(app, { grants: grants, permissions, documents: new DocumentsRepo(opts.db), layers: new LayersRepo(opts.db), visitors: new GrantVisitorsRepo(opts.db), deleteVisitor: (visitor) => deleteVisitor({ db: opts.db!, deleteLayer }, visitor), securityEvents: new SecurityEventsRepo(opts.db), }); await registerGrantSessionRoutes(app, { sign: signer, grants: grants, documents: new DocumentsRepo(opts.db), layers: new LayersRepo(opts.db), visitors: new GrantVisitorsRepo(opts.db), handles: visitorHandles, deleteLayer, suspendedTenants: suspendedTenantsGuard!, ...(usageMeters ? { usageMeters } : {}), tenantUsage: tenantUsage!, }); } // API-token requests reach the doc plane as a synthesized // tenant-mode principal for the doc'S own tenant — recovered from // the document row, which is an addressing lookup (storage keys and // services are tenant-keyed), not an authorization decision: the // API token is already root. Every existing guard then takes its // tenant branch unchanged. `/v1/access` + `/v1/warm` stay JWT-only: // they are viewer-session bootstrap (view metering, exp-bound CDN // grants), and a root credential has no session to establish. // // `X-Document-Password` (base64) rides only API-token requests — // backends supply encrypted-doc passwords per call; viewers keep // the KMS session flow via /v1/access. const documentsForApiAuth = new DocumentsRepo(opts.db); app.addHook('preHandler', async (req, reply) => { const passwordHeader = req.headers['x-document-password']; if (!req.apiAuth) { if (passwordHeader !== undefined) { return reply .code(403) .send( errorBody( 'Forbidden', 'X-Document-Password requires the api token; viewers unlock via /v1/access', ), ); } return; } const pathname = req.url.split('?', 1)[0] ?? req.url; if (pathname === '/v1/access' || pathname === '/v1/warm') { return reply .code(403) .send( errorBody( 'Forbidden', 'the api token cannot establish viewer sessions; mint a doc token instead', ), ); } const docId = (req.params as { docId?: string } | undefined)?.docId; if (!docId || !pathname.startsWith('/v1/docs/')) return; const row = await documentsForApiAuth.findById(docId); if (!row) { return reply.code(404).send(errorBody('NotFound', `document does not exist: ${docId}`)); } const now = Math.floor(Date.now() / 1000); req.tenant = { id: row.tenantId, sub: 'api-token', claims: { sub: 'api-token', tenant_id: row.tenantId, scope: ['*'], iat: now, // Far-future exp: the SSE auth-expiring event never fires for // the root credential — its lifetime is env rotation, not a // JWT clock. exp: now + 10 * 365 * 24 * 60 * 60, } as JwtClaims, }; if (passwordHeader !== undefined) { const decoded = decodeBase64Header(passwordHeader); if (decoded === null) { return reply .code(400) .send( errorBody( 'InvalidArg', 'X-Document-Password must be a single base64-encoded UTF-8 value', ), ); } req.docPassword = decoded; } }); // Wire the doc-scoped routes when the operator has chosen a cache // root. Requires the worker pool — admin-only deploys (no // `workerEntry`) serve only the admin surface and skip the cloud // open surface entirely. if (baseFileCache && pool) { const layerStateService = new LayerStateService({ documentPages: new DocumentPagesRepo(opts.db), layers: new LayersRepo(opts.db), layerPages: new LayerPagesRepo(opts.db), documents: new DocumentsRepo(opts.db), baseVersions: new BaseVersionsRepo(opts.db), }); const eventLog = new EventLogService({ storage: opts.objectStore }); // Object numbers handed to editing sessions; a write that handed some // out says so in its response. const objectNumbers = new ObjectNumberService({ db: opts.db }); app.addHook('onSend', async (req, reply, payload) => { const issued = req.editRequest?.issued; if (issued && issued.length > 0 && reply.statusCode < 300) { reply.header('EmbedPDF-Object-Numbers', formatObjectNumberRanges(issued)); } return payload; }); const passwordSessionServerSecret = { id: opts.pdfPasswordSessionServerSecretId ?? process.env['CLOUDPDF_PASSWORD_SESSION_SERVER_SECRET_ID'] ?? 'dev-v1', // Only enforced when KMS (and thus password-session persistence) // is actually enabled — the secret is unused otherwise. secret: resolveSecret({ explicit: opts.pdfPasswordSessionServerSecret, env: process.env, requirement: { name: 'PDF password-session server secret', envVar: 'CLOUDPDF_PASSWORD_SESSION_SERVER_SECRET', option: 'pdfPasswordSessionServerSecret', }, devFallback: 'cloudpdf-dev-password-session-secret', enforce: enforceProductionSecrets && opts.kms !== undefined, }), }; // CDN-signaling rule for /head: non-`none` adapters need /access // to be called before the first cacheable read so the SDK has // the signed URLs/cookies. The default (`none`) keeps /head // saying "no access needed" so public grants stay cheap. const cdnAccessRequired = cdnFronted; const passwordSessionsRepo = opts.kms ? new PdfPasswordSessionsRepo(opts.db, { keyring: opts.kms, serverSecrets: [passwordSessionServerSecret], }) : undefined; documentService = new DocumentService({ documents: new DocumentsRepo(opts.db), baseVersions: new BaseVersionsRepo(opts.db), counters: engineCounters, cache: baseFileCache, storage: opts.objectStore, pool, layerState: layerStateService, cdnAccessRequired, serverFonts: (serverFonts ??= new ServerFonts(pool)), ...(opts.layerSessionIdleMs !== undefined ? { layerSessionIdleMs: opts.layerSessionIdleMs } : {}), ...(opts.maxLayerSessionsPerDoc !== undefined ? { maxLayerSessionsPerDoc: opts.maxLayerSessionsPerDoc } : {}), passwordVerifications: new PdfPasswordVerificationsRepo(opts.db, { // The proof rows are HMACs over real document passwords: on a // production license a strong secret is mandatory, or a leaked DB // becomes an offline dictionary attack on customer PDFs. hmacSecret: resolveSecret({ explicit: opts.pdfPasswordVerificationHmacSecret, env: process.env, requirement: { name: 'PDF password verification HMAC secret', envVar: 'CLOUDPDF_PASSWORD_VERIFICATION_HMAC_SECRET', option: 'pdfPasswordVerificationHmacSecret', }, devFallback: 'cloudpdf-dev-password-verification-secret', enforce: enforceProductionSecrets, }) as string, ttlMs: opts.pdfPasswordVerificationTtlMs, }), ...(passwordSessionsRepo ? { passwordSessions: passwordSessionsRepo, passwordSessionServerSecret, passwordSessionTtlMs: opts.pdfPasswordSessionTtlMs, passwordSessionRenewalTtlMs: opts.pdfPasswordSessionRenewalTtlMs, } : {}), }); layerService = new LayerService({ db: opts.db, documents: new DocumentsRepo(opts.db), counters: engineCounters, layerState: layerStateService, eventLog, documentService, pool, storage: opts.objectStore, realtime: realtimeBus, signings: new DocumentSigningsRepo(opts.db), signingRoot, ...(opts.signingTtlMs !== undefined ? { signingTtlMs: opts.signingTtlMs } : {}), objectNumbers, }); await registerAccessRoutes(app, { service: documentService, permissions, layers: layerService, cdnSigner: opts.cdnSigner ?? new NoneCdnSigner(), ...(derivedRenders ? { derivedRenders } : {}), ...(usageMeters ? { usageMeters } : {}), tenantUsage: tenantUsage!, bundleLimits: opts.bundleLimits ?? DEFAULT_BUNDLE_LIMITS, }); await registerObjectNumberRoutes(app, { documentService, layerService }); await registerChangeRoutes(app, { documentService, layerService, ...(opts.bundleLimits ? { bundleLimits: opts.bundleLimits } : {}), }); await registerDocsRoutes(app, { service: documentService, ...(signer ? { sign: signer } : {}), }); await registerMetadataRoutes(app, { service: documentService, layerService }); await registerOutlineRoutes(app, { service: documentService }); await registerFontRoutes(app, { service: documentService }); await registerSignatureRoutes(app, { service: documentService, layerService }); await registerPageRoutes(app, { documentService, layerService, imageEncoder: new SharpImageEncoder(), ...(opts.encodeInEngine !== undefined ? { encodeInEngine: opts.encodeInEngine } : {}), ...(derivedRenders ? { derivedRenders } : {}), }); await registerRedactionRoutes(app, { documentService, layerService }); await registerEventsRoutes(app, { db: opts.db, documentService, layerService, realtimeBus, drain: drainCoordinator, ...(revokedJtisGuard ? { revocation: revokedJtisGuard } : {}), }); await registerAnnotationRoutes(app, { documentService, layerService, imageEncoder: new SharpImageEncoder(), ...(opts.encodeInEngine !== undefined ? { encodeInEngine: opts.encodeInEngine } : {}), ...(derivedRenders ? { derivedRenders } : {}), ...(opts.bundleLimits ? { bundleLimits: opts.bundleLimits } : {}), }); await registerFormRoutes(app, { documentService, layerService, imageEncoder: new SharpImageEncoder(), ...(opts.encodeInEngine !== undefined ? { encodeInEngine: opts.encodeInEngine } : {}), ...(derivedRenders ? { derivedRenders } : {}), ...(opts.bundleLimits ? { bundleLimits: opts.bundleLimits } : {}), }); await registerAttachmentRoutes(app, { documentService }); await registerSearchRoutes(app, { documentService, }); } const sweepIntervalMs = opts.sweepIntervalMs ?? 60_000; const pendingTtlMs = opts.pendingTtlMs ?? 60 * 60 * 1000; // 1h default const deletingGraceMs = opts.deletingGraceMs ?? 60_000; if (sweepIntervalMs > 0) { sweeperTimer = setInterval(() => { lifecycle! .sweepStalePending({ olderThanMs: pendingTtlMs }) .catch((err) => app.log.error({ err }, 'sweepStalePending failed')); lifecycle! .sweepDeleting({ olderThanMs: deletingGraceMs }) .catch((err) => app.log.error({ err }, 'sweepDeleting failed')); layerService ?.expireSignings(Date.now()) .catch((err) => app.log.error({ err }, 'expireSignings failed')); layerService ?.sweepChanges(Date.now()) .catch((err) => app.log.error({ err }, 'sweepChanges failed')); layerService ?.sweepObjectNumbers() .catch((err) => app.log.error({ err }, 'sweepObjectNumbers failed')); sweepIdleVisitors({ db: opts.db!, deleteLayer }, Date.now()).catch((err) => app.log.error({ err }, 'sweepIdleVisitors failed'), ); documentService ?.closeIdleLayerSessions(Date.now()) .catch((err) => app.log.error({ err }, 'closeIdleLayerSessions failed')); tenantUsage?.sweepOnceKeys().catch((err) => app.log.error({ err }, 'sweepOnceKeys failed')); }, sweepIntervalMs); sweeperTimer.unref(); } } // After the core's routes: a module adds to the server, never in its place. await mountModules(app, declaredModules, { permissions, ...(documentService ? { documentService } : {}), ...(tenantFeaturesGuard ? { tenantFeatures: tenantFeaturesGuard } : {}), ...(tenantUsage ? { tenantUsage } : {}), ...(derivedRenders ? { derivedRenders } : {}), ...(signer ? { sign: signer } : {}), }); app.setErrorHandler(handleAppError); const shutdownTimeoutMs = opts.shutdownTimeoutMs ?? 30_000; const shutdownDrainMs = opts.shutdownDrainMs ?? 0; const shutdown = async () => { engineRecycler?.stop(); // 1. Fail readiness and end every live SSE stream. Hijacked streams // are invisible to app.close() — with heartbeats keeping their // sockets alive, one connected viewer would otherwise hold // shutdown open until the supervisor SIGKILLs, skipping the pool // and cache teardown below on every deploy. drainCoordinator.begin(); // 2. Optional settle window for probe-driven balancers that need to // observe the 503 before the socket refuses (Kubernetes covers // this externally with endpoint removal + preStop). if (shutdownDrainMs > 0) { await new Promise((resolve) => setTimeout(resolve, shutdownDrainMs)); } if (sweeperTimer) clearInterval(sweeperTimer); await importWorker?.stop(); try { // 3. Bounded: in-flight HTTP gets shutdownTimeoutMs to finish and // then teardown proceeds anyway — cleanup must run before the // supervisor's kill deadline, not after it. let timer: NodeJS.Timeout | undefined; const timedOut = new Promise<'timeout'>((resolve) => { timer = setTimeout(() => resolve('timeout'), shutdownTimeoutMs); timer.unref?.(); }); const closed = app.close().then( () => 'closed' as const, (err: unknown) => { app.log.error({ err }, 'app.close failed during shutdown; continuing teardown'); return 'closed' as const; }, ); const outcome = await Promise.race([closed, timedOut]); if (timer) clearTimeout(timer); if (outcome === 'timeout') { app.log.error( { shutdownTimeoutMs }, 'app.close did not finish within the shutdown budget; continuing teardown', ); } } finally { try { if (pool) await pool.destroy(); } finally { documentService?.releaseAllBaseHandles(); if (baseFileCache) await baseFileCache.destroy(); } } }; return { app, permissions, routes, pool, lifecycle, revokedJtisGuard, suspendedTenantsGuard, tenantFeaturesGuard, documentService, layerService, derivedRenders, baseFileCache, kms: opts.kms, ...(crashJournal ? { crashJournal } : {}), ...(engineHost ? { engineHost } : {}), engineCounters, ...(schedulingPool ? { engineScheduler: schedulingPool } : {}), ...(engineHosts.length > 0 ? { engineHosts } : {}), beginDrain: () => drainCoordinator.begin(), shutdown, }; } /** * Preserve the distinction between an expected client rejection and a server * failure while ensuring that handled 5xx responses do not disappear from * the structured logs. Fastify will still write its normal `request * completed` record; the additional error record carries the error itself * and inherits the request logger's reqId. */ export function handleAppError(err: unknown, req: FastifyRequest, reply: FastifyReply): void { if (err instanceof EngineBusyError) { // Honest backpressure: retry cheaply instead of hanging. A shed // interactive job is the overload signal (background sheds are // swallowed by their callers by design). logHandledServerError(req, err, 503); reply.header('Retry-After', '2'); reply.code(503).send(errorBody(err.code, err.message)); return; } if (err instanceof DocumentQuarantinedError) { reply.code(422).send(errorBody(err.code, err.message)); return; } if (EngineError.is(err) && (err as EngineError).code === EngineErrorCode.DocNotOpen) { // Server-side override of the generic mapping: DocNotOpen reaching // HTTP is always pool state (post-retry: the engine respawned more // than once inside one request) — a transient 503, never a 404 // (real document-absence surfaces as NotFound from the DB layer). logHandledServerError(req, err, 503); reply.header('Retry-After', '2'); reply.code(503).send(errorBody('EngineRestarting', err.message)); return; } if (EngineError.is(err)) { const engineErr = err as EngineError; const code = mapToHttp(engineErr.code); logHandledServerError(req, engineErr, code); reply.code(code).send(errorBody(engineErr.code, engineErr.message, engineErr.details)); return; } const e = err as Error & { code?: string; status?: number; statusCode?: number; details?: Record; }; if (e.status && typeof e.status === 'number') { logHandledServerError(req, e, e.status); if (!isEngineErrorCode(e.code)) { // Every code a response carries is in the one list; one that isn't is // a bug, and the status says what went wrong meanwhile. req.log.error({ err: e, code: e.code }, 'error code is not in EngineErrorCode'); } const code = isEngineErrorCode(e.code) ? e.code : codeForStatus(e.status); reply.code(e.status).send(errorBody(code, e.message, e.details)); return; } // Fastify's own errors (body parsing, payload limits, validation) carry // `statusCode`, not `status`, and codes of their own (`FST_ERR_…`). Pass // 4xx through as the client errors they are, with the status's code; 5xx // still falls to the unhandled branch below so it gets logged. if (typeof e.statusCode === 'number' && e.statusCode >= 400 && e.statusCode < 500) { reply.code(e.statusCode).send(errorBody(codeForStatus(e.statusCode), e.message)); return; } if (e.code === 'NotFound') { reply.code(404).send(errorBody('NotFound', e.message)); return; } if (e.code === 'Forbidden') { reply.code(403).send(errorBody('Forbidden', e.message)); return; } req.log.error({ err: e, statusCode: 500 }, 'unhandled error'); reply.code(500).send(errorBody('Unknown', e.message)); } /** The code for an error that names none from the list, by its status. */ function codeForStatus(status: number): EngineErrorCode { if (status === 400) return EngineErrorCode.InvalidArg; if (status === 401) return EngineErrorCode.Unauthenticated; if (status === 403) return EngineErrorCode.Forbidden; if (status === 404) return EngineErrorCode.NotFound; if (status === 409) return EngineErrorCode.Conflict; if (status === 413) return EngineErrorCode.PayloadTooLarge; if (status === 429) return EngineErrorCode.TooManyRequests; return status < 500 ? EngineErrorCode.InvalidArg : EngineErrorCode.Unknown; } function logHandledServerError(req: FastifyRequest, err: unknown, statusCode: number): void { if (statusCode >= 500) { req.log.error({ err, statusCode }, 'request failed'); } } /** * Strict base64 decode for the `X-Document-Password` header: single, * bounded value only, with valid optional padding and a canonical * round-trip (rejects garbage that Buffer's lenient decoder would * silently mangle). */ const MAX_DOCUMENT_PASSWORD_HEADER_LENGTH = 4_096; function removeBase64Padding(value: string): string | null { let end = value.length; while (end > 0 && value.charCodeAt(end - 1) === 0x3d) end--; const paddingLength = value.length - end; if (paddingLength > 2) return null; const unpadded = value.slice(0, end); if (unpadded.includes('=')) return null; // Unpadded base64 is accepted. If the caller includes padding, it must // have exactly the length required by the final four-character block. const remainder = unpadded.length % 4; if (remainder === 1) return null; const requiredPadding = remainder === 0 ? 0 : 4 - remainder; if (paddingLength !== 0 && paddingLength !== requiredPadding) return null; return unpadded; } function decodeBase64Header(value: string | string[]): string | null { if ( Array.isArray(value) || value.length === 0 || value.length > MAX_DOCUMENT_PASSWORD_HEADER_LENGTH ) { return null; } const canonicalInput = removeBase64Padding(value); if (canonicalInput === null) return null; const buf = Buffer.from(canonicalInput, 'base64'); if (buf.length === 0) return null; if (removeBase64Padding(buf.toString('base64')) !== canonicalInput) return null; try { return new TextDecoder('utf-8', { fatal: true }).decode(buf); } catch { return null; } } /** * `trustProxy` as Fastify takes it. A hop count goes in as the check it stands * for: Fastify reads a bare number as no proxy to trust. */ function trustedProxies( trustProxy: NonNullable, ): boolean | string | string[] | ((address: string, hop: number) => boolean) { if (typeof trustProxy !== 'number') return trustProxy; return (_address, hop) => hop < trustProxy; } function isReadOnlyLicenseRequest(method: string, pathname: string): boolean { if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return true; // These POST endpoints calculate or mint read access, but do not change the // customer's document contents. They remain available so an expired or // suspended license can never hold existing data hostage. The grant // exchange belongs here for the same reason: it mints read sessions // for documents already given out. return ( method === 'POST' && (pathname === '/v1/access' || pathname === '/v1/warm' || pathname === '/v1/grant-sessions') ); } function mapToHttp(code: string): number { switch (code) { case EngineErrorCode.InvalidArg: case EngineErrorCode.WireFormat: return 400; case EngineErrorCode.Unauthenticated: return 401; case EngineErrorCode.Forbidden: case EngineErrorCode.VisitorIdentityRequired: return 403; // Signing: a pending candidate, a moved fence, or a layer behind the // head are all conflicts the client resolves by re-preparing; a dead // signing (expired/aborted) is gone for good; a refused CMS is the // caller's input. A change the document's own signatures refuse is a // conflict with its state, not a matter of the caller's authority. case EngineErrorCode.LayerVersionConflict: case EngineErrorCode.SigningPending: case EngineErrorCode.SigningVersionMismatch: case EngineErrorCode.ProtectedDocument: case EngineErrorCode.ObjectNumberUnavailable: case EngineErrorCode.LayerFull: return 409; case EngineErrorCode.NotFound: case EngineErrorCode.DocNotOpen: return 404; case EngineErrorCode.SigningExpired: case EngineErrorCode.LayerDeleted: return 410; case EngineErrorCode.PayloadTooLarge: return 413; case EngineErrorCode.DocOpenFailed: case EngineErrorCode.DocPasswordRequired: case EngineErrorCode.DocPasswordIncorrect: case EngineErrorCode.MalformedPdf: case EngineErrorCode.SignatureRefused: return 422; case EngineErrorCode.Aborted: return 499; case EngineErrorCode.NotImplemented: return 501; default: return 500; } }