import { randomBytes } from 'node:crypto'; import { AdminImportSourceSchema, type AdminImportSource } from '@cloudpdf/contract'; import type { Kysely } from 'kysely'; import type { DerivedRenderService } from './DerivedRenderService'; import { DocumentSecurityProbe } from './DocumentSecurityProbe'; import type { BaseVersionsRepo } from '../db/repos/base_versions.repo'; import type { FoldersRepo } from '../db/repos/folders.repo'; import { DocumentImportsRepo, type DocumentImportRow, type ImportJobEnqueue, } from '../db/repos/document_imports.repo'; import { DocumentsRepo, type DocumentListOptions, type DocumentRow, } from '../db/repos/documents.repo'; import type { GrantsRepo } from '../db/repos/grants.repo'; import type { TenantUsageRepo } from '../db/repos/tenant_usage.repo'; import { TenantsRepo } from '../db/repos/tenants.repo'; import type { UploadTokenUsesRepo } from '../db/repos/upload_token_uses.repo'; import type { Database as Schema } from '../db/schema'; import type { ImportPolicy } from '../import/config/ImportPolicySchema'; import { createImportSource } from '../import/createImportSource'; import { ImportConnectionRegistry } from '../import/ImportConnectionRegistry'; import { ImportSourceError, type ImportSource, type ImportSourceOpen, } from '../import/ImportSource'; import { Semaphore } from '../import/Semaphore'; import type { UsageMeters } from '../licensing/UsageMeters'; import type { BaseFileCache, LocalFileHandle } from '../storage/BaseFileCache'; import { StorageKeys } from '../storage/keys'; import { ShaMismatchError, type ObjectBody, type ObjectStoreWithInfo, type PresignedUpload, } from '../storage/ObjectStore'; export type DedupMode = 'always-create' | 'reuse-existing'; export type UploadPreference = 'auto' | 'presigned' | 'proxy'; export type UploadProxyPolicy = 'fallback-only' | 'allowed' | 'disabled'; /** Integrity pins for `documents.importFrom`; enforced when present. */ export interface ImportExpected { sizeBytes?: number; sha256?: string; } export interface ImportInput { tenantId: string; sub: string; /** Which credential class authenticated the caller (from requireTenantAccess). */ via: 'api-token' | 'tenant-jwt'; /** Wire descriptor from the request body (v1: `{ kind: 'url' }`). */ source: AdminImportSource; expected?: ImportExpected | null; /** Defaults to the document id. */ name?: string; /** The folder to file it in; null or absent is the top level. */ folderId?: string | null; metadata?: Record | null; idempotencyKey?: string | null; dedupMode?: DedupMode; docId?: string | undefined; /** `sync` (default) holds the response; `async` enqueues a worker job. */ mode?: 'sync' | 'async'; } /** * `imported` — bytes were pulled, verified, and committed (sync). * `deduped` — an existing document satisfied the request without a * transfer (content dedup or idempotent replay). * `accepted` — async: the job is queued; poll the document. */ export type ImportResult = { status: 'imported' | 'deduped' | 'accepted'; doc: DocumentRow }; /** What a completed transfer resolved to — the worker's fenced-succeed payload. */ export interface ImportTransferOutcome extends ImportResult { status: 'imported'; resolvedRevision: string | null; sourceKind: string; sourceLocation: string; } export interface InitInput { tenantId: string; sub: string; contentLength: number; /** * Customer-supplied SHA-256 of the bytes they intend to upload. * Required so we can do a pre-flight dedup check (reuse-existing) * and pin the verify-on-commit target. The server still hashes the * bytes at commit time, so a lying customer never wins. */ contentSha256: string; /** Defaults to the document id. */ name?: string; /** The folder to file it in; null or absent is the top level. */ folderId?: string | null; metadata?: Record | null; idempotencyKey?: string | null; dedupMode?: DedupMode; /** * Customer-controlled doc id. If absent, server generates one. Used * for migration / tooling where the customer already has an id space. */ docId?: string; /** Presigned URL TTL. */ uploadTtlSec?: number; /** Preferred transfer path. `auto` keeps object storage off the origin. */ uploadPreference?: UploadPreference; /** * The upload token starting this document, when one is: the row * records its `jti`, and the token starts at most `maxFiles` documents. * `expiresAt` (epoch ms) is when the token runs out. */ uploadToken?: { jti: string; maxFiles: number; expiresAt: number }; } export type InitResult = | { status: 'created'; doc: DocumentRow } | { status: 'resumed'; doc: DocumentRow } | { status: 'deduped'; doc: DocumentRow }; export type InitUpload = | { kind: 'presigned'; presigned: PresignedUpload; /** The storage key the client is uploading to (informational). */ key: string; } | { kind: 'proxy'; /** Path on the API the client POSTs a multipart `file` to. */ url: string; key: string; }; export interface CommitInput { tenantId: string; docId: string; sha256: string; } export interface CommitResult { doc: DocumentRow; } export interface UploadProxyInput { tenantId: string; docId: string; body: ObjectBody; contentLength: number; } export interface DocumentLifecycleOptions { documents: DocumentsRepo; tenants: TenantsRepo; /** Needed to file documents in folders; without it, every document stays at the top level. */ folders?: FoldersRepo; storage: ObjectStoreWithInfo; /** * If true, the lifecycle service auto-provisions a tenant row on * first admin call. Useful for dev / single-tenant deploys. * Production deployments should disable this and require explicit * tenant provisioning. */ autoProvisionTenant?: boolean; securityProbe?: DocumentSecurityProbe; /** * Base-file cache shared with the security probe and render plane. * When present, commit verifies the uploaded bytes by materialising * them into this cache — one object-store read serves both the * sha verification and the probe that follows. Absent (admin-only * deploys), commit falls back to a streaming remote hash. */ fileCache?: Pick; /** When present, commit warms the document's thumbnail (fire-and-forget). */ derivedRenders?: DerivedRenderService; usageMeters?: UsageMeters; /** When present, fresh commits also move the per-tenant upload fact. */ tenantUsage?: TenantUsageRepo; /** When present, document delete revokes the document's grants. */ grants?: GrantsRepo; /** Upload tokens' uses; without it, init refuses upload tokens. */ uploadTokenUses?: UploadTokenUsesRepo; /** Controls whether origin-mediated uploads may be selected. */ uploadProxyPolicy?: UploadProxyPolicy; /** * Server-side pull policy for `documents.importFrom`. Absent = imports * disabled (the endpoint answers 403), which keeps direct service * construction (tests, admin-only deploys) closed by default; * `buildApp` supplies the schema defaults. */ importPolicy?: ImportPolicy; /** Operator-registered pull connections (the `connection` source kind). */ importConnections?: ImportConnectionRegistry; /** Import provenance/audit rows; absent = no provenance recorded. */ documentImports?: DocumentImportsRepo; /** The base version catalog (migration 030): a commit records version 1. */ baseVersions?: BaseVersionsRepo; /** * Raw database handle for multi-repo transactions: async import * enqueue must create the pending document and its job atomically. * Absent = mode:async is unavailable. */ db?: Kysely; } /** * Orchestrator over `documents.repo`, `tenants.repo`, and the * `ObjectStore`. Implements the three-step `init -> PUT -> commit` * flow plus delete cascade and download. * * Failure model: * - `init` - returns `status: 'deduped'` on a content-sha match (no * upload needed). Throws `EngineError(InvalidArg)` * if the customer supplied a stale idempotency key * pointing at a different content sha. * - `commit` - returns `null`/throws `Conflict` if the row is no * longer pending. Verifies sha by materialising the * upload into the base-file cache (one object-store * read, reused by the security probe); falls back to * a streaming `objectStore.getSha256(key)` when no * cache is wired. Mismatch -> marks failed + throws * `InvalidArg('sha_mismatch')`. * - `delete` - two-phase: flip to `deleting`, drop storage prefix, * remove DB row. A crash between phases leaves * `deleting` rows for the sweeper to retry. */ export class DocumentLifecycleService { private readonly documents: DocumentsRepo; private readonly tenants: TenantsRepo; private readonly folders?: FoldersRepo; private readonly storage: ObjectStoreWithInfo; private readonly autoProvisionTenant: boolean; private readonly securityProbe: DocumentSecurityProbe; private readonly fileCache?: Pick; private readonly derivedRenders?: DerivedRenderService; private readonly usageMeters?: UsageMeters; private readonly tenantUsage?: TenantUsageRepo; private readonly grants?: GrantsRepo; private readonly uploadTokenUses?: UploadTokenUsesRepo; private readonly uploadProxyPolicy: UploadProxyPolicy; private readonly importPolicy?: ImportPolicy; private readonly importConnections: ImportConnectionRegistry; private readonly documentImports?: DocumentImportsRepo; private readonly baseVersions?: BaseVersionsRepo; private readonly db?: Kysely; private readonly importGate: Semaphore; /** Single-flight per (tenant, idempotencyKey): concurrent retries share one transfer. */ private readonly inflightImports = new Map>(); constructor(opts: DocumentLifecycleOptions) { this.documents = opts.documents; this.tenants = opts.tenants; if (opts.folders) this.folders = opts.folders; this.storage = opts.storage; this.autoProvisionTenant = opts.autoProvisionTenant ?? false; this.securityProbe = opts.securityProbe ?? new DocumentSecurityProbe(); this.fileCache = opts.fileCache; this.derivedRenders = opts.derivedRenders; this.usageMeters = opts.usageMeters; this.tenantUsage = opts.tenantUsage; this.grants = opts.grants; this.uploadTokenUses = opts.uploadTokenUses; this.uploadProxyPolicy = opts.uploadProxyPolicy ?? 'fallback-only'; if (opts.importPolicy) this.importPolicy = opts.importPolicy; this.importConnections = opts.importConnections ?? new ImportConnectionRegistry(); if (opts.documentImports) this.documentImports = opts.documentImports; if (opts.baseVersions) this.baseVersions = opts.baseVersions; if (opts.db) this.db = opts.db; this.importGate = new Semaphore(opts.importPolicy?.maxConcurrent ?? 1); } async init(input: InitInput): Promise { if (this.autoProvisionTenant) { await this.tenants.ensure({ id: input.tenantId, autoProvisioned: true }); } const dedupMode: DedupMode = input.dedupMode ?? 'always-create'; if (dedupMode === 'reuse-existing' && input.contentSha256) { const existing = await this.documents.findByBaseSha(input.tenantId, input.contentSha256); if (existing) { return { status: 'deduped', doc: existing }; } } if (input.idempotencyKey) { const existing = await this.documents.findByIdempotencyKey( input.tenantId, input.idempotencyKey, ); if (existing) { this.assertSameUploadIntent(existing, input); // If the row is already committed, return `deduped` (no // upload). If pending, return `resumed` so the route hands // back a fresh upload URL to finish the half-finished work. if (existing.state === 'ready') { return { status: 'deduped', doc: existing }; } if (existing.state === 'failed') { throw conflict( `idempotency key ${input.idempotencyKey} belongs to failed document ${existing.id}`, ); } if (existing.state !== 'pending') { throw conflict( `idempotency key ${input.idempotencyKey} belongs to document ${existing.id} in state ${existing.state}`, ); } return { status: 'resumed', doc: existing }; } } const docId = input.docId ?? generateDocId(); if (docId.length < 2) { throw badRequest(`docId must be at least 2 characters: ${docId}`); } await this.requireFolder(input.tenantId, input.folderId); await this.claimUploadTokenUse(input); const created = await this.documents .createPending({ id: docId, tenantId: input.tenantId, name: input.name ?? docId, folderId: input.folderId ?? null, metadata: input.metadata ?? null, idempotencyKey: input.idempotencyKey ?? null, createdBy: input.sub, expectedSha256: input.contentSha256, expectedSizeBytes: input.contentLength, uploadTokenJti: input.uploadToken?.jti ?? null, }) .catch(async (err: unknown) => { if (input.uploadToken) await this.uploadTokenUses?.release(input.uploadToken.jti); throw err; }); // A concurrent request can win the idempotency-key insert between the // lookup and createPending. Validate the row returned from that race too. if (!created.created) this.assertSameUploadIntent(created.row, input); return { status: created.created ? 'created' : 'resumed', doc: created.row }; } /** * Takes one of the upload token's uses before its document is made, in * one statement, so no number of racing inits starts more than * `maxFiles` documents. */ private async claimUploadTokenUse(input: InitInput): Promise { if (!input.uploadToken) return; if (!this.uploadTokenUses) throw new Error('upload tokens need the upload-token uses repo'); const { jti, maxFiles, expiresAt } = input.uploadToken; const claimed = await this.uploadTokenUses.claim({ jti, tenantId: input.tenantId, maxFiles, expiresAt, }); if (!claimed) { throw forbiddenError( `this upload token uploads at most ${maxFiles} ${maxFiles === 1 ? 'file' : 'files'}`, ); } } private buildUploadKey(docId: string, tenantId: string): string { return StorageKeys.basePdf(tenantId, docId); } /** * Materialize the upload artifact (presigned PUT for object storage, * bounded origin proxy for the fallback). Called by the admin route * after `init`; the route owns the proxy URL space so the * service stays Fastify-agnostic. */ async issueUpload( docId: string, tenantId: string, contentLength: number, proxyUrlForDoc: (docId: string) => string, opts: { ttlSec?: number; preference?: UploadPreference } = {}, ): Promise { const doc = await this.documents.requireOwned(docId, tenantId); if (doc.state !== 'pending') { throw conflict(`document ${doc.id} is not pending (state=${doc.state})`); } const key = this.buildUploadKey(docId, tenantId); const ttl = opts.ttlSec ?? 900; const preference = opts.preference ?? 'auto'; const makePresigned = () => this.storage.presignUpload(key, ttl, { contentLength, contentType: 'application/pdf', }); let upload: InitUpload; if (preference === 'proxy') { if (this.uploadProxyPolicy === 'disabled') { throw badRequest('proxy uploads are disabled by this deployment'); } if (this.uploadProxyPolicy === 'fallback-only') { const available = await makePresigned(); if (available) { throw badRequest( 'proxy uploads are fallback-only; use the presigned upload returned by auto mode', ); } } upload = { kind: 'proxy', url: proxyUrlForDoc(docId), key }; } else { const presigned = await makePresigned(); if (presigned) { upload = { kind: 'presigned', presigned, key }; } else if (preference === 'presigned') { throw badRequest('presigned uploads are unavailable for this storage adapter'); } else if (this.uploadProxyPolicy === 'disabled') { throw badRequest( 'this storage adapter cannot issue presigned uploads and proxy uploads are disabled', ); } else { upload = { kind: 'proxy', url: proxyUrlForDoc(docId), key }; } } const expiresAt = upload.kind === 'presigned' ? upload.presigned.expiresAt : Date.now() + ttl * 1000; const persisted = await this.documents.setUploadIntent({ id: docId, tenantId, kind: upload.kind, expiresAt, }); if (!persisted) throw conflict(`document ${docId} state changed while issuing upload access`); return upload; } async uploadProxy(input: UploadProxyInput): Promise<{ sha256: string }> { const doc = await this.documents.requireOwned(input.docId, input.tenantId); if (doc.state !== 'pending') { throw conflict(`document ${doc.id} is not pending (state=${doc.state})`); } if (doc.uploadKind !== 'proxy') { throw conflict(`document ${doc.id} was not initialized for a proxy upload`); } if (doc.uploadExpiresAt !== null && doc.uploadExpiresAt < Date.now()) { throw conflict(`proxy upload access expired for document ${doc.id}; call init again`); } if (doc.expectedSizeBytes !== null && doc.expectedSizeBytes !== input.contentLength) { throw badRequest( `size_mismatch: init declared ${doc.expectedSizeBytes} bytes but proxy received ${input.contentLength}`, ); } const key = this.buildUploadKey(doc.id, doc.tenantId); return this.storage.put(key, input.body, { contentLength: input.contentLength }); } /** * `documents.importFrom` — the server-side pull. The same lifecycle as * init → PUT → commit with only the transfer phase swapped: the * server fetches the bytes from a caller-supplied source instead of * the client pushing them. Synchronous and bounded by policy * (`maxBytes` / `timeoutMs`); the doc row is the audit record, not * a job queue. * * Failure model: * - policy/content failures (bad source, size/sha mismatch, too * large, 404/denied at the source) are terminal: the row is * marked failed with a sanitized reason and the call maps to 400; * - transport failures (network, source 5xx, timeout, truncated * stream) are retryable: the row stays pending and the call maps * to 502 — retrying with the same idempotencyKey resumes the * same document. Abandoned pendings fall to the sweeper. */ async importFromSource(input: ImportInput): Promise { const policy = this.importPolicy; if (!policy || !policy.enabled) { throw forbiddenError('imports are disabled on this deployment'); } const pins: ResolvedImportPins = { expectedSha: input.expected?.sha256?.toLowerCase() ?? null, expectedSize: input.expected?.sizeBytes ?? null, }; if ((input.mode ?? 'sync') === 'async') this.assertAsyncEligible(input, pins); const dedupMode: DedupMode = input.dedupMode ?? 'always-create'; if (dedupMode === 'reuse-existing' && !pins.expectedSha) { throw badRequest( 'dedupMode=reuse-existing requires expected.sha256: without a declared hash the server cannot know what content to reuse before transferring', ); } if (this.autoProvisionTenant) { await this.tenants.ensure({ id: input.tenantId, autoProvisioned: true }); } if (pins.expectedSha && dedupMode === 'reuse-existing') { const existing = await this.documents.findByBaseSha(input.tenantId, pins.expectedSha); if (existing) return { status: 'deduped', doc: existing }; } if (!input.idempotencyKey) return this.importResolved(input, pins); // Single-flight: concurrent same-key imports share one transfer // instead of racing double egress at the same storage key. const gateKey = `${input.tenantId}:${input.idempotencyKey}`; const running = this.inflightImports.get(gateKey); if (running) return running; const attempt = this.importResolved(input, pins).finally(() => { this.inflightImports.delete(gateKey); }); this.inflightImports.set(gateKey, attempt); return attempt; } /** Resolve idempotent replay/resume, or create the pending row. */ private async importResolved( input: ImportInput, pins: ResolvedImportPins, ): Promise { if (input.idempotencyKey) { const existing = await this.documents.findByIdempotencyKey( input.tenantId, input.idempotencyKey, ); if (existing) return this.importOntoExisting(existing, input, pins); } await this.requireFolder(input.tenantId, input.folderId); if ((input.mode ?? 'sync') === 'async') return this.createQueuedImport(input, pins); const docId = input.docId ?? generateDocId(); if (docId.length < 2) { throw badRequest(`docId must be at least 2 characters: ${docId}`); } const created = await this.documents.createPending({ id: docId, tenantId: input.tenantId, name: input.name ?? docId, folderId: input.folderId ?? null, metadata: input.metadata ?? null, idempotencyKey: input.idempotencyKey ?? null, createdBy: input.sub, expectedSha256: pins.expectedSha, expectedSizeBytes: pins.expectedSize, }); // Same race as init: a concurrent same-key insert can win between // the lookup and createPending. Fold onto whatever row exists. if (!created.created) return this.importOntoExisting(created.row, input, pins); return this.runImportTransfer(created.row, input, pins); } /** An idempotency key led to an existing row — replay or resume it. */ private async importOntoExisting( existing: DocumentRow, input: ImportInput, pins: ResolvedImportPins, ): Promise { this.assertSameImportIntent(existing, input.idempotencyKey ?? null, pins); if (existing.state === 'ready') return { status: 'deduped', doc: existing }; if (existing.state !== 'pending') { throw conflict( `idempotency key ${input.idempotencyKey} belongs to document ${existing.id} in state ${existing.state}`, ); } if (existing.uploadKind === 'presigned' || existing.uploadKind === 'proxy') { throw conflict( `idempotency key ${input.idempotencyKey} belongs to an init-created upload; finish it via its ${existing.uploadKind} flow`, ); } if ((input.mode ?? 'sync') === 'async') { await this.enqueueJobFor(existing, input, pins); return { status: 'accepted', doc: existing }; } // A live async job owns this document's transfer — a concurrent // sync re-drive would double-pull the same storage key. const job = await this.documentImports?.findByDoc(existing.id, existing.tenantId); if (job && (job.state === 'queued' || job.state === 'running')) { throw conflict( `an async import is in progress for document ${existing.id}; poll the document instead`, ); } return this.runImportTransfer(existing, input, pins); } /** * Async eligibility, validated at request time so callers get their * 400 immediately: connection sources only (a presigned URL is a * perishable secret — it cannot sit in a durable job row), the full * authorization/fingerprint gate must pass now, and unpinnable * providers need a declared sha to fence retries to one content * identity. */ private assertAsyncEligible(input: ImportInput, pins: ResolvedImportPins): void { if (input.source.kind !== 'connection') { throw badRequest('mode=async requires a connection source; url sources are synchronous'); } try { createImportSource(input.source, { policy: this.importPolicy!, caller: { via: input.via, tenantId: input.tenantId }, connections: this.importConnections, deploymentStorage: this.storage.info, }); } catch (err) { if (ImportSourceError.is(err)) { const e = new Error(err.message) as Error & { code: string; status: number }; e.code = 'InvalidArg'; e.status = 400; throw e; } throw err; } const conn = this.importConnections.get(input.source.connectionId); if (conn?.kind === 'fs' && !pins.expectedSha) { throw badRequest( 'filesystem connections have no revisions to pin retries to; async imports from fs require expected.sha256', ); } } /** * Atomic doc+job creation — one transaction, so a crash can never * leave an idempotency-owned pending document without a runnable * job (3b requirement #4). */ private async createQueuedImport( input: ImportInput, pins: ResolvedImportPins, ): Promise { const db = this.db; if (!db || !this.documentImports) { throw new Error('async imports require the lifecycle db + documentImports options'); } const docId = input.docId ?? generateDocId(); if (docId.length < 2) { throw badRequest(`docId must be at least 2 characters: ${docId}`); } const outcome = await db.transaction().execute(async (trx) => { const docs = new DocumentsRepo(trx); const jobs = new DocumentImportsRepo(trx); const created = await docs.createPending({ id: docId, tenantId: input.tenantId, name: input.name ?? docId, folderId: input.folderId ?? null, metadata: input.metadata ?? null, idempotencyKey: input.idempotencyKey ?? null, createdBy: input.sub, expectedSha256: pins.expectedSha, expectedSizeBytes: pins.expectedSize, }); if (!created.created) return { kind: 'raced' as const, row: created.row }; await jobs.enqueue(this.jobEnqueueInput(created.row, input, pins)); return { kind: 'created' as const, row: created.row }; }); // Same-key race: fold onto whatever row won, like the sync path. if (outcome.kind === 'raced') return this.importOntoExisting(outcome.row, input, pins); return { status: 'accepted', doc: outcome.row }; } private async enqueueJobFor( doc: DocumentRow, input: ImportInput, pins: ResolvedImportPins, ): Promise { if (!this.documentImports) { throw new Error('async imports require the documentImports option'); } await this.documentImports.enqueue(this.jobEnqueueInput(doc, input, pins)); } private jobEnqueueInput( doc: DocumentRow, input: ImportInput, pins: ResolvedImportPins, ): ImportJobEnqueue { return { docId: doc.id, tenantId: doc.tenantId, ...wireProvenanceFields(input.source), expectedSha256: pins.expectedSha, expectedSizeBytes: pins.expectedSize, requestedBy: input.sub, via: input.via, sourceJson: JSON.stringify(input.source), }; } /** * Worker entry: run one queued job's transfer. The job row is the * provenance and the fence — the worker owns every job transition, * so the transfer runs with provenance writes disabled and reports * its outcome back for a fenced succeed/fail. Retries are pinned to * one content identity: the requested revision, else the revision * captured on the first successful open (3b requirement #6). */ async executeQueuedTransfer( doc: DocumentRow, job: DocumentImportRow, hooks: { onOpened?: (resolvedRevision: string | null) => Promise } = {}, ): Promise { if (!job.sourceJson) { throw badRequest(`import job for document ${doc.id} carries no source descriptor`); } const parsed = AdminImportSourceSchema.safeParse(JSON.parse(job.sourceJson)); if (!parsed.success || parsed.data.kind !== 'connection') { throw badRequest(`import job for document ${doc.id} carries an unusable source descriptor`); } const revision = parsed.data.revision ?? job.resolvedRevision ?? undefined; const source: AdminImportSource = { ...parsed.data, ...(revision ? { revision } : {}) }; const input: ImportInput = { tenantId: job.tenantId, sub: job.requestedBy ?? 'import-worker', via: job.via === 'tenant-jwt' ? 'tenant-jwt' : 'api-token', source, mode: 'sync', }; const pins: ResolvedImportPins = { expectedSha: job.expectedSha256, expectedSize: job.expectedSizeBytes, }; return this.runImportTransfer(doc, input, pins, { provenance: false, ...(hooks.onOpened ? { onOpened: hooks.onOpened } : {}), }); } /** The transfer itself: open the source, stream into storage, commit. */ private async runImportTransfer( doc: DocumentRow, input: ImportInput, pins: ResolvedImportPins, opts: ImportTransferOpts = {}, ): Promise { const policy = this.importPolicy!; const provenance = opts.provenance ?? true; const release = await this.importGate.acquire(); const abort = new AbortController(); const timer = setTimeout(() => abort.abort(), policy.timeoutMs); timer.unref?.(); try { const marked = await this.documents.setUploadIntent({ id: doc.id, tenantId: doc.tenantId, kind: 'pull', expiresAt: Date.now() + policy.timeoutMs, }); if (!marked) throw conflict(`document ${doc.id} state changed while starting import`); // Provenance from the wire descriptor — recorded even when // source construction/authorization fails a moment later. Async // transfers skip this: the claim already owns the job row. if (provenance) { await this.documentImports?.recordAttemptStart({ docId: doc.id, tenantId: doc.tenantId, ...wireProvenanceFields(input.source), expectedSha256: pins.expectedSha, expectedSizeBytes: pins.expectedSize, requestedBy: input.sub, via: input.via, }); } let source!: ImportSource; let opened: ImportSourceOpen; try { source = createImportSource(input.source, { policy, caller: { via: input.via, tenantId: doc.tenantId }, connections: this.importConnections, deploymentStorage: this.storage.info, }); opened = await source.open({ signal: abort.signal }); } catch (err) { throw await this.importFailure(doc, err, provenance); } try { // Report the served revision before any bytes flow — async // jobs persist it (fenced) so retries pin to this identity. await opts.onOpened?.(opened.resolvedRevision ?? null); if (opened.contentLength > policy.maxBytes) { throw new ImportSourceError( 'too_large', `source declares ${opened.contentLength} bytes; this deployment caps imports at ${policy.maxBytes}`, false, ); } if (pins.expectedSize !== null && pins.expectedSize !== opened.contentLength) { throw new ImportSourceError( 'unsupported', `size_mismatch: expected.sizeBytes declared ${pins.expectedSize} but the source declares ${opened.contentLength}`, false, ); } // Fail fast on quota before paying for the transfer; commit // re-asserts both meters authoritatively. await this.usageMeters?.assertUploadAllowed(); await this.usageMeters?.assertStorageAllowed(opened.contentLength); } catch (err) { opened.body.destroy(); throw await this.importFailure(doc, err, provenance); } const key = this.buildUploadKey(doc.id, doc.tenantId); const onAbort = (): void => { opened.body.destroy(new Error('import timed out')); }; abort.signal.addEventListener('abort', onAbort, { once: true }); let observedSha: string; try { const putRes = await this.storage.put(key, opened.body, { contentLength: opened.contentLength, }); observedSha = putRes.sha256; } catch (err) { // Truncated/over-long streams and connection resets land here. // The streaming put is atomic (no visible partial object), so // the row can stay pending for a same-key retry. throw await this.importFailure( doc, new ImportSourceError('upstream', `transfer failed: ${sanitizeImportDetail(err)}`, true), provenance, ); } finally { abort.signal.removeEventListener('abort', onAbort); } if (pins.expectedSha && observedSha !== pins.expectedSha) { await this.documents.markFailed(doc.id, doc.tenantId, 'sha_mismatch'); if (provenance) { await this.documentImports ?.recordFailure( doc.id, doc.tenantId, 'sha_mismatch: declared expected.sha256 does not match the source bytes', ) .catch(() => undefined); } await this.storage.delete(key); throw badRequest( `sha_mismatch: expected.sha256 declared ${pins.expectedSha} but the source bytes hash to ${observedSha}`, ); } // From here the existing commit path owns verification, the // security probe, metering, and thumbnail warming — the import // pathway adds no verification machinery of its own. let committed: CommitResult; try { committed = await this.commit({ tenantId: doc.tenantId, docId: doc.id, sha256: observedSha, }); } catch (err) { if (provenance) { await this.documentImports ?.recordFailure(doc.id, doc.tenantId, sanitizeImportDetail(err)) .catch(() => undefined); } throw err; } if (provenance) { await this.documentImports?.recordSuccess(doc.id, doc.tenantId, { resolvedRevision: opened.resolvedRevision ?? null, sourceKind: source.info.kind, sourceLocation: source.info.location, }); } return { status: 'imported', doc: committed.doc, resolvedRevision: opened.resolvedRevision ?? null, sourceKind: source.info.kind, sourceLocation: source.info.location, }; } finally { clearTimeout(timer); release(); } } /** * Map a transfer-stage failure onto the row + an HTTP-shaped error. * Terminal failures mark the row failed (sanitized reason — never a * URL query string); retryable ones leave it pending for a same-key * resume and surface as 502. */ private async importFailure(doc: DocumentRow, err: unknown, provenance = true): Promise { if (ImportSourceError.is(err)) { if (provenance) { await this.documentImports ?.recordFailure(doc.id, doc.tenantId, `import_${err.code}: ${err.message}`) .catch(() => undefined); } if (!err.retryable) { await this.documents.markFailed( doc.id, doc.tenantId, `import_${err.code}: ${err.message}`.slice(0, 500), ); } const mapped = new Error(err.message) as Error & { code: string; status: number }; if (err.retryable) { mapped.code = 'UpstreamError'; mapped.status = 502; } else { mapped.code = 'InvalidArg'; mapped.status = 400; } return mapped; } return err instanceof Error ? err : new Error(String(err)); } /** * Import-flavoured intent check. Unlike init (which requires the * sha upfront), imports may omit pins — so mismatches are enforced * only when both sides declare a value. */ private assertSameImportIntent( existing: DocumentRow, idempotencyKey: string | null, pins: ResolvedImportPins, ): void { const knownSha = existing.expectedSha256 ?? existing.baseSha; if (pins.expectedSha && knownSha && pins.expectedSha !== knownSha) { throw conflict(`idempotency key ${idempotencyKey} was already used for different content`); } const knownSize = existing.expectedSizeBytes ?? existing.storageSizeBytes; if (pins.expectedSize !== null && knownSize !== null && pins.expectedSize !== knownSize) { throw conflict( `idempotency key ${idempotencyKey} was already used for a different byte length`, ); } } async commit(input: CommitInput): Promise { const doc = await this.documents.requireOwned(input.docId, input.tenantId); if (doc.state === 'ready') { // Idempotent commit: if the existing base_sha matches, return // the doc unchanged; otherwise this is a programmer error. The // event dedupe reports counted: false here, so the tenant fact // never double-moves. if (doc.baseSha === input.sha256) { const recorded = await this.usageMeters?.recordUpload(doc.id, doc.createdAt); if (recorded?.counted) await this.tenantUsage?.recordUpload(doc.tenantId); return { doc }; } throw conflict(`document ${doc.id} already committed with different base_sha`); } if (doc.state !== 'pending') { throw conflict(`document ${doc.id} is not pending (state=${doc.state})`); } if (doc.expectedSha256 !== null && doc.expectedSha256 !== input.sha256) { throw conflict(`commit SHA does not match the SHA pinned at init for document ${doc.id}`); } const key = this.buildUploadKey(doc.id, doc.tenantId); const stat = await this.storage.stat(key); if (!stat) { // Caller skipped the PUT. await this.documents.markFailed(doc.id, doc.tenantId, 'missing_upload'); throw badRequest(`no bytes found at ${key}; PUT before commit`); } if (doc.expectedSizeBytes !== null && stat.size !== doc.expectedSizeBytes) { await this.documents.markFailed(doc.id, doc.tenantId, 'size_mismatch'); await this.storage.delete(key); throw badRequest( `size_mismatch: init declared ${doc.expectedSizeBytes} bytes but storage contains ${stat.size}`, ); } const declaredSha = doc.expectedSha256 ?? input.sha256; if (!/^[0-9a-f]{64}$/.test(declaredSha)) { await this.documents.markFailed(doc.id, doc.tenantId, 'sha_mismatch'); await this.storage.delete(key); throw badRequest('sha_mismatch: declared sha256 must be 64 lowercase hex chars'); } // Verify the uploaded bytes with a single object-store read. // `fileCache.acquire` materialises the object into the base-file // cache and hashes it on the way down (ShaMismatchError when the // bytes don't hash to `declaredSha`); the security probe below then // reuses that warm entry instead of downloading a second time. let baseHandle: LocalFileHandle | null = null; try { if (this.fileCache) { try { baseHandle = await this.fileCache.acquire({ sha: declaredSha, key }); } catch (err) { if (err instanceof ShaMismatchError) { await this.documents.markFailed(doc.id, doc.tenantId, 'sha_mismatch'); // Also remove the bad bytes so a retry isn't reading stale data. await this.storage.delete(key); throw badRequest( `sha_mismatch: init declared ${err.expected} but server observed ${err.actual}`, ); } throw err; } } if (!baseHandle || baseHandle.sourceKey !== key) { // No cache wired, or the content-addressed cache already held // these bytes materialised from a different object's key — a // hit proves nothing about what is stored at our key, so hash // the remote object directly (streaming, constant memory). const observedSha = await this.storage.getSha256(key); if (!observedSha) { await this.documents.markFailed(doc.id, doc.tenantId, 'sha_unavailable'); throw new Error('object store could not produce SHA-256 for the uploaded bytes'); } if (observedSha !== declaredSha) { await this.documents.markFailed(doc.id, doc.tenantId, 'sha_mismatch'); // Also remove the bad bytes so a retry isn't reading stale data. await this.storage.delete(key); throw badRequest( `sha_mismatch: init declared ${declaredSha} but server observed ${observedSha}`, ); } } const probe = await this.securityProbe.probe({ key, expectedSha: declaredSha, }); // Meter only a newly committed document. The ready/idempotent return at // the top of this method never reaches this path. await this.usageMeters?.assertUploadAllowed(); await this.usageMeters?.assertStorageAllowed(stat.size); const updated = await this.documents.commit({ id: doc.id, tenantId: doc.tenantId, baseSha: declaredSha, storageSizeBytes: stat.size, security: probe.security, }); if (!updated) { throw conflict(`document ${doc.id} state changed during commit`); } // Version 1 of the base catalog: the upload is the immutable base // every later signature descends from. Idempotent on the sha. await this.baseVersions?.insertInitial({ tenantId: doc.tenantId, docId: doc.id, sha256: declaredSha, byteLength: stat.size, createdAt: updated.createdAt, }); const recorded = await this.usageMeters?.recordUpload(updated.id, updated.createdAt); if (recorded?.counted) await this.tenantUsage?.recordUpload(updated.tenantId); // Thumbnail lifecycle: user-password documents get no // derived artifact — a thumbnail is content disclosure, and the lock // tile is the correct render. Everything else warms fire-and-forget: // the read-through path is the correctness path, warming is latency. if (probe.security.encryptionRequiresPassword === true) { await this.documents.setThumbnail(doc.id, doc.tenantId, 'locked'); } else if (this.derivedRenders) { void this.derivedRenders .warmDocumentThumbnail({ tenantId: doc.tenantId, docId: doc.id, baseSha: declaredSha, baseKey: key, }) .catch(() => undefined); // warm records `failed` itself } return { doc: updated }; } finally { baseHandle?.release(); } } private assertSameUploadIntent(existing: DocumentRow, input: InitInput): void { const expectedSha = existing.expectedSha256 ?? existing.baseSha; const expectedSize = existing.expectedSizeBytes ?? existing.storageSizeBytes; if (expectedSha !== null && expectedSha !== input.contentSha256) { throw conflict( `idempotency key ${input.idempotencyKey} was already used for different content`, ); } if (expectedSize !== null && expectedSize !== input.contentLength) { throw conflict( `idempotency key ${input.idempotencyKey} was already used for a different byte length`, ); } } async list(tenantId: string, opts: DocumentListOptions = {}): Promise { await this.requireFolder(tenantId, opts.folderId); return this.documents.listForTenant(tenantId, opts); } /** NotFound for a folder that does not exist, Forbidden for another tenant's. */ private async requireFolder( tenantId: string, folderId: string | null | undefined, ): Promise { if (folderId === null || folderId === undefined) return; if (!this.folders) throw new Error('filing documents in folders needs the folders repo'); await this.folders.requireOwned(folderId, tenantId); } async get(tenantId: string, docId: string): Promise { return this.documents.requireOwned(docId, tenantId); } /** * A document the upload token `jti` started, in its tenant. Any other * document is `NotFound`, as if it didn't exist: the token mustn't * learn about documents it didn't make. */ async requireStartedByUploadToken( tenantId: string, docId: string, jti: string, ): Promise { const doc = await this.documents.findById(docId); if (!doc || doc.tenantId !== tenantId || doc.uploadTokenJti !== jti) { throw notFound(`document not found: ${docId}`); } return doc; } /** Throws `NotFound` for a document that is gone or being deleted, `Forbidden` across tenants. */ async rename(tenantId: string, docId: string, name: string): Promise { await this.documents.requireOwned(docId, tenantId); const renamed = await this.documents.rename(docId, tenantId, name); if (!renamed) throw notFound(`document not found: ${docId}`); return renamed; } async download(tenantId: string, docId: string): Promise { const doc = await this.documents.requireOwned(docId, tenantId); if (doc.state !== 'ready') { throw conflict(`document ${doc.id} is not ready (state=${doc.state})`); } const key = this.buildUploadKey(doc.id, doc.tenantId); const bytes = await this.storage.get(key); if (!bytes) { throw new Error(`document ${doc.id} bytes missing from storage at ${key}`); } return bytes; } async delete(tenantId: string, docId: string): Promise { // Tenant isolation gate first. We deliberately distinguish: // - row exists & belongs to this tenant: proceed with cascade // - row exists & belongs to a different tenant: 403 (caught // by requireOwned) // - row doesn't exist anywhere: 204 (idempotent) const row = await this.documents.findById(docId); if (!row) return; if (row.tenantId !== tenantId) { const err = new Error(`document does not belong to tenant: ${docId}`) as Error & { code: string; }; err.code = 'Forbidden'; throw err; } const begun = await this.documents.beginDelete(docId, tenantId); if (!begun) { // Race: another caller advanced it. Still consider the cascade // our responsibility — fall through to storage cleanup so a // double-delete still leaves nothing behind. } const prefix = StorageKeys.docRoot(tenantId, docId); await this.storage.deletePrefix(prefix); // Grants die with the document — explicitly, not via FK cascade, // because SQLite deployments may run without foreign_keys on and a // dangling grant would be a stored 404, not a security hole (the // exchange re-checks the document), but still a wart in listings. await this.grants?.deleteByDoc(docId, tenantId); // Import provenance dies with the document. await this.documentImports?.deleteByDoc(docId, tenantId); await this.documents.finalizeDelete(docId, tenantId); } /** * Finish deletes that were begun, such as every document of a deleted * folder: the stored files, grants, import provenance and row of * each, a few at a time. Each document is attempted; the first failure * is rethrown at the end, and {@link sweepDeleting} retries it later. */ async finishDeletes(tenantId: string, docIds: ReadonlyArray): Promise { let failure: unknown; let next = 0; const worker = async () => { while (next < docIds.length) { const docId = docIds[next++]!; try { await this.delete(tenantId, docId); } catch (err) { failure ??= err; } } }; await Promise.all(Array.from({ length: FINISH_DELETES_CONCURRENCY }, worker)); if (failure !== undefined) throw failure; } /** * Finish documents left `deleting` for longer than `olderThanMs`, up to * {@link SWEEP_DELETING_BATCH} a sweep. Safe on every replica at once: * finishing a delete twice leaves the same nothing behind. */ async sweepDeleting(opts: { olderThanMs: number }): Promise { const stale = await this.documents.listStaleDeleting(opts.olderThanMs, SWEEP_DELETING_BATCH); let failure: unknown; for (const doc of stale) { try { await this.delete(doc.tenantId, doc.id); } catch (err) { failure ??= err; } } if (failure !== undefined) throw failure; return stale.length; } /** * Sweep stale `pending` rows + their (possibly orphaned) bytes. * Returns the count of swept documents. Safe to call from a * scheduled task in `buildApp`. */ async sweepStalePending(opts: { olderThanMs: number }): Promise { const stale = await this.documents.listStalePending(opts.olderThanMs); let swept = 0; for (const doc of stale) { // A queued/running async job owns its pending document — the // lease/backoff machinery retires it, never the sweeper. const job = await this.documentImports?.findByDoc(doc.id, doc.tenantId); if (job && (job.state === 'queued' || job.state === 'running')) continue; await this.delete(doc.tenantId, doc.id); swept++; } return swept; } } /** Deletes finished at once per {@link DocumentLifecycleService.finishDeletes} call. */ const FINISH_DELETES_CONCURRENCY = 4; /** Documents one sweep finishes; the next sweep takes the rest. */ const SWEEP_DELETING_BATCH = 200; function generateDocId(): string { // 12 bytes -> 24 hex chars. Fits the 2-char shard naturally. return `doc_${randomBytes(12).toString('hex')}`; } interface ResolvedImportPins { expectedSha: string | null; expectedSize: number | null; } interface ImportTransferOpts { /** false = an async job row owns provenance + fencing; skip unfenced writes. */ provenance?: boolean; /** Invoked after a successful open with the served revision (null when none). */ onOpened?: (resolvedRevision: string | null) => Promise; } function forbiddenError(message: string): Error { const e = new Error(message) as Error & { code: string; status: number }; e.code = 'Forbidden'; e.status = 403; return e; } /** * Provenance fields derivable from the wire descriptor alone — * available even when source construction fails. Success enriches * kind/location with the resolved adapter identity. */ function wireProvenanceFields(source: AdminImportSource): { sourceKind: string; connectionId: string | null; sourceLocation: string; requestedRevision: string | null; } { if (source.kind === 'url') { let location = 'url:invalid'; try { const u = new URL(source.url); location = `${u.origin}${u.pathname}`; } catch { // keep the sentinel — never record a raw (possibly signed) URL } return { sourceKind: 'url', connectionId: null, sourceLocation: location, requestedRevision: null, }; } return { sourceKind: 'connection', connectionId: source.connectionId, sourceLocation: `connection:${source.connectionId}/${source.key}`, requestedRevision: source.revision ?? null, }; } /** Strip anything query-shaped so presigned credentials can't leak into reasons. */ export function sanitizeImportDetail(err: unknown): string { const msg = err instanceof Error ? err.message : String(err); return msg.replace(/\?\S*/g, '?[redacted]').slice(0, 300); } function badRequest(message: string): Error { const e = new Error(message) as Error & { code: string; status: number }; e.code = 'InvalidArg'; e.status = 400; return e; } function notFound(message: string): Error { const e = new Error(message) as Error & { code: string; status: number }; e.code = 'NotFound'; e.status = 404; return e; } function conflict(message: string): Error { const e = new Error(message) as Error & { code: string; status: number }; e.code = 'Conflict'; e.status = 409; return e; }