import { AdminDocumentCommitRequestSchema, AdminDocumentImportRequestSchema, AdminDocumentInitRequestSchema, AdminDocumentUpdateRequestSchema, adminOperations, adminWirePaths, type AdminDocumentCommitRequest, type AdminDocumentImportRequest, type AdminDocumentInitRequest, type AdminDocumentUpdateRequest, type AdminOperation, type DocumentListSort, type ListOrder, type AdminDocumentRecord, type AdminInitUpload, } from '@cloudpdf/contract'; import { permissionFlagsOf, type PdfPermissionFlags } from '@embedpdf/engine-core/runtime'; import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import { decodeSortedListCursor, encodeSortedListCursor } from './_cursor'; import { formatIssues } from './_issues'; import { folderIdOfPlace, placeOfFolderId, ROOT_PLACE } from './_place'; import { requireTenantAccess, requireTenantContentAccess, requireUploadAccess, type UploadAccessContext, } from '../../app/jwt-plugin'; import { listPositionOf } from '../../db/repos/documents.repo'; import type { DocumentLifecycleService, InitUpload } from '../../services/DocumentLifecycleService'; import type { ObjectStore } from '../../storage/ObjectStore'; import { errorBody } from '../_helpers'; import { isoTime } from '../../time'; export interface AdminDocumentsRouteDeps { lifecycle: DocumentLifecycleService; /** Serves warmed thumbnail artifacts. Absent = 404 on the route. */ storage?: ObjectStore; } /** * Tenant document routes, mounted under `/v1/tenants/:tenantId/documents`. * * The flow customers walk through: * 1. POST /v1/tenants/:tenantId/documents/init * body: { sizeBytes, contentSha256, name?, metadata?, idempotencyKey?, dedupMode?, docId? } * -> { id, state, status: 'created'|'resumed'|'deduped', upload?: { ... } } * * 2. (If not deduped:) PUT the bytes to `upload.url` (presigned) or * POST multipart to `.../documents/:docId/upload-proxy` when the * deployment selected the bounded origin fallback. * * 3. POST .../documents/:docId/commit * body: { sha256 } * -> { id, state, baseSha256, ... } * * Or, replacing all three when the bytes already live in the * customer's own storage — the server-side pull: * POST /v1/tenants/:tenantId/documents/import * body: { source: { kind: 'url', url }, expected?, ... } * -> { status: 'imported'|'deduped'|'accepted', document } * * Listing / deleting / downloading are flat REST against the tenant documents collection. */ export async function registerAdminDocumentsRoutes( app: FastifyInstance, deps: AdminDocumentsRouteDeps, ): Promise { const { lifecycle, storage } = deps; /** * Every route mounts from its registry entry: method, path, scope, * and accepted credentials come from `adminOperations`, so the * contract is executed rather than merely described. Handlers own * behavior only. */ const mount = ( op: AdminOperation, handler: (req: FastifyRequest, reply: FastifyReply) => unknown, ): void => { app.route({ method: op.method, url: op.path, handler }); }; const initOp = adminOperations['documents.init']; mount(initOp, async (req, reply) => { const { tenantId } = req.params as { tenantId: string }; const ctx = requireUploadAccess(req, tenantId, initOp.scope); const body = parseInitBody(req); // An upload token decides where the file goes and what it carries. const filing = ctx.via === 'upload-jwt' ? uploadTokenFiling(ctx, body) : { folderId: folderIdOfPlace(body.folderId ?? ROOT_PLACE), metadata: body.metadata ?? null, }; const result = await lifecycle.init({ tenantId: ctx.tenantId, sub: ctx.sub, contentLength: body.sizeBytes, contentSha256: body.contentSha256, name: body.name, folderId: filing.folderId, metadata: filing.metadata, idempotencyKey: body.idempotencyKey ?? null, dedupMode: body.dedupMode, docId: body.docId, uploadTtlSec: body.uploadTtlSeconds, uploadPreference: body.uploadPreference, ...(ctx.via === 'upload-jwt' ? { uploadToken: { jti: ctx.jti, maxFiles: ctx.upload.max_files, expiresAt: ctx.expiresAt, }, } : {}), }); if (result.status === 'deduped') { return reply.send({ status: result.status, document: docPublic(result.doc), }); } // Stable proxy-upload URL: SDKs use it exactly // as returned (no string interpolation on its side). const upload = await lifecycle.issueUpload( result.doc.id, ctx.tenantId, body.sizeBytes, (docId) => adminWirePaths.documentUploadProxy(tenantId, docId), { ttlSec: body.uploadTtlSeconds, preference: body.uploadPreference }, ); return reply.send({ status: result.status, document: docPublic(result.doc), upload: uploadPublic(upload), }); }); const commitOp = adminOperations['documents.commit']; mount(commitOp, async (req, reply) => { const { tenantId, docId: id } = req.params as { tenantId: string; docId: string }; const ctx = requireUploadAccess(req, tenantId, commitOp.scope); const body = parseCommitBody(req); if (ctx.via === 'upload-jwt') { await lifecycle.requireStartedByUploadToken(ctx.tenantId, id, ctx.jti); } const result = await lifecycle.commit({ tenantId: ctx.tenantId, docId: id, sha256: body.sha256, }); return reply.send({ document: docPublic(result.doc) }); }); const uploadProxyOp = adminOperations['documents.uploadProxy']; mount(uploadProxyOp, async (req, reply) => { const { tenantId, docId: id } = req.params as { tenantId: string; docId: string }; const ctx = requireUploadAccess(req, tenantId, uploadProxyOp.scope); if (ctx.via === 'upload-jwt') { await lifecycle.requireStartedByUploadToken(ctx.tenantId, id, ctx.jti); } // Proxy uploads are deliberately multipart-only. That shape is portable // across Fern's generators and, unlike the previous implementation, we // compare the PDF part's length rather than the multipart envelope's // Content-Length. if (!req.isMultipart()) { throw makeError('InvalidArg', 400, 'expected multipart with a file field'); } const data = await req.file(); if (!data || data.fieldname !== 'file') { throw makeError('InvalidArg', 400, 'expected multipart with a file field'); } const buf = await data.toBuffer(); const bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); const { sha256 } = await lifecycle.uploadProxy({ tenantId: ctx.tenantId, docId: id, body: bytes, contentLength: bytes.byteLength, }); return reply.send({ sha256 }); }); const importOp = adminOperations['documents.importFrom']; mount(importOp, async (req, reply) => { const { tenantId } = req.params as { tenantId: string }; const ctx = requireTenantAccess(req, tenantId, importOp.scope); const body = parseImportBody(req); const result = await lifecycle.importFromSource({ tenantId: ctx.tenantId, sub: ctx.sub, via: ctx.via, source: body.source, expected: body.expected ?? null, name: body.name, folderId: folderIdOfPlace(body.folderId ?? ROOT_PLACE), metadata: body.metadata ?? null, idempotencyKey: body.idempotencyKey ?? null, dedupMode: body.dedupMode, docId: body.docId, mode: body.mode, }); return reply .code(result.status === 'accepted' ? 202 : 200) .send({ status: result.status, document: docPublic(result.doc) }); }); const listOp = adminOperations['documents.list']; mount(listOp, async (req, reply) => { const { tenantId } = req.params as { tenantId: string }; const ctx = requireTenantAccess(req, tenantId, listOp.scope); const parsed = listOp.query.safeParse(req.query ?? {}); if (!parsed.success) { throw makeError('InvalidArg', 400, formatIssues(parsed.error.issues)); } const { limit, cursor, state, q, sort, folderId } = parsed.data; const order = parsed.data.order ?? readingOrderOf(sort); const after = cursor === undefined ? undefined : decodeSortedListCursor(cursor, { sort, order, keyType: sort === 'name' ? 'string' : 'number', }); // limit+1 probes for a next page without a count query. const rows = await lifecycle.list(ctx.tenantId, { limit: limit + 1, state, nameContains: q, folderId: folderId === undefined ? undefined : folderIdOfPlace(folderId), sort, order, after, }); const page = rows.slice(0, limit); const last = page[page.length - 1]; const nextCursor = rows.length > limit && last ? encodeSortedListCursor({ sort, order, ...listPositionOf(last, sort) }) : null; return reply.send({ documents: page.map(docPublic), nextCursor }); }); const getOp = adminOperations['documents.get']; mount(getOp, async (req, reply) => { const { tenantId, docId: id } = req.params as { tenantId: string; docId: string }; const ctx = requireTenantAccess(req, tenantId, getOp.scope); const doc = await lifecycle.get(ctx.tenantId, id); return reply.send({ document: docPublic(doc) }); }); const updateOp = adminOperations['documents.update']; mount(updateOp, async (req, reply) => { const { tenantId, docId: id } = req.params as { tenantId: string; docId: string }; const ctx = requireTenantAccess(req, tenantId, updateOp.scope); const body = parseUpdateBody(req); const doc = await lifecycle.rename(ctx.tenantId, id, body.name); return reply.send({ document: docPublic(doc) }); }); const downloadOp = adminOperations['documents.download']; mount(downloadOp, async (req, reply) => { const { tenantId, docId: id } = req.params as { tenantId: string; docId: string }; const ctx = await requireTenantContentAccess(req, tenantId, 'doc.download', () => permissionFlagsOfDocument(lifecycle, tenantId, id), ); const bytes = await lifecycle.download(ctx.tenantId, id); return reply .type('application/pdf') .header('Content-Length', String(bytes.byteLength)) .send(Buffer.from(bytes)); }); const deleteOp = adminOperations['documents.delete']; mount(deleteOp, async (req, reply) => { const { tenantId, docId: id } = req.params as { tenantId: string; docId: string }; const ctx = requireTenantAccess(req, tenantId, deleteOp.scope); await lifecycle.delete(ctx.tenantId, id); return reply.code(204).send(); }); /** * The dashboard-tile artifact: serves the warmed base-tier render * by its stored key — no token grammar, no page knowledge needed by the * dashboard. 404 with the state while `pending`/`locked`/`failed` (the * doc-plane render routes remain the read-through repair path). */ const thumbnailOp = adminOperations['documents.thumbnail']; mount(thumbnailOp, async (req, reply) => { const { tenantId, docId: id } = req.params as { tenantId: string; docId: string }; const ctx = await requireTenantContentAccess(req, tenantId, 'doc.render', () => permissionFlagsOfDocument(lifecycle, tenantId, id), ); const doc = await lifecycle.get(ctx.tenantId, id); if (!storage || doc.thumbnailState !== 'ready' || !doc.thumbnailKey) { return reply.code(404).send( errorBody('ThumbnailNotReady', 'thumbnail is not ready to serve', { state: doc.thumbnailState, }), ); } const bytes = await storage.get(doc.thumbnailKey); if (!bytes) { return reply .code(404) .send( errorBody('ThumbnailNotReady', 'thumbnail is not ready to serve', { state: 'pending' }), ); } return reply .type(doc.thumbnailKey.endsWith('.png') ? 'image/png' : 'image/webp') .header('Cache-Control', 'private, max-age=60') .send(Buffer.from(bytes)); }); } /** * Where an upload token's document goes and what it carries: the * token's folder and metadata, never the request's. Refuses what could * reach a document the token didn't make (a chosen id, a retry key, an * existing file), and a file larger than the token takes. */ function uploadTokenFiling( ctx: UploadAccessContext, body: AdminDocumentInitRequest, ): { folderId: string | null; metadata: Record | null } { if (body.docId !== undefined) { throw makeError('InvalidArg', 400, 'an upload token cannot choose the document id'); } if (body.idempotencyKey !== undefined) { throw makeError('InvalidArg', 400, 'an upload token cannot use an idempotencyKey'); } if (body.dedupMode === 'reuse-existing') { throw makeError('InvalidArg', 400, 'an upload token always makes a new document'); } const { max_bytes: maxBytes } = ctx.upload; if (maxBytes !== undefined && body.sizeBytes > maxBytes) { throw makeError( 'InvalidArg', 400, `the file is ${body.sizeBytes} bytes; this upload token takes at most ${maxBytes}`, ); } return { folderId: ctx.upload.folder_id, metadata: ctx.upload.metadata ?? null }; } function parseInitBody(req: FastifyRequest): AdminDocumentInitRequest { const result = AdminDocumentInitRequestSchema.safeParse(req.body); if (!result.success) { throw makeError('InvalidArg', 400, formatIssues(result.error.issues)); } return { ...result.data, contentSha256: result.data.contentSha256.toLowerCase(), }; } function parseCommitBody(req: FastifyRequest): AdminDocumentCommitRequest { const result = AdminDocumentCommitRequestSchema.safeParse(req.body); if (!result.success) { throw makeError('InvalidArg', 400, formatIssues(result.error.issues)); } return { ...result.data, sha256: result.data.sha256.toLowerCase(), }; } /** The document's PDF permission bits, which `pdf.permissions` in a scope expands against. */ async function permissionFlagsOfDocument( lifecycle: DocumentLifecycleService, tenantId: string, docId: string, ): Promise { const doc = await lifecycle.get(tenantId, docId); return permissionFlagsOf(doc.security.pdfPermissionsBits ?? null); } function parseUpdateBody(req: FastifyRequest): AdminDocumentUpdateRequest { const result = AdminDocumentUpdateRequestSchema.safeParse(req.body); if (!result.success) { throw makeError('InvalidArg', 400, formatIssues(result.error.issues)); } return result.data; } /** A to Z for names; newest and largest first for creation time and size. */ function readingOrderOf(sort: DocumentListSort): ListOrder { return sort === 'name' ? 'asc' : 'desc'; } function parseImportBody(req: FastifyRequest): AdminDocumentImportRequest { const result = AdminDocumentImportRequestSchema.safeParse(req.body); if (!result.success) { throw makeError('InvalidArg', 400, formatIssues(result.error.issues)); } const expected = result.data.expected; return { ...result.data, ...(expected?.sha256 ? { expected: { ...expected, sha256: expected.sha256.toLowerCase() } } : {}), }; } function docPublic(d: { id: string; tenantId: string; name: string; folderId: string | null; state: AdminDocumentRecord['state']; baseSha: string | null; storageSizeBytes: number | null; metadata: Record | null; idempotencyKey: string | null; failureReason: string | null; thumbnailState: AdminDocumentRecord['thumbnailState']; thumbnailKey: string | null; createdAt: number; updatedAt: number; createdBy: string | null; }): AdminDocumentRecord { return { id: d.id, tenantId: d.tenantId, name: d.name, folderId: placeOfFolderId(d.folderId), state: d.state, baseSha256: d.baseSha, sizeBytes: d.storageSizeBytes, metadata: d.metadata, idempotencyKey: d.idempotencyKey, failureReason: d.failureReason, // Dashboard tile contract: the URL is valid the // whole time — `pending` just means a fetch pays the read-through. thumbnailState: d.thumbnailState, thumbnailUrl: d.thumbnailState === 'ready' ? adminWirePaths.documentThumbnail(d.tenantId, d.id) : null, createdAt: isoTime(d.createdAt), updatedAt: isoTime(d.updatedAt), createdBy: d.createdBy, }; } function uploadPublic(upload: InitUpload): AdminInitUpload { return upload.kind === 'presigned' ? { ...upload, presigned: { ...upload.presigned, expiresAt: isoTime(upload.presigned.expiresAt) }, } : upload; } function makeError(code: string, status: number, message: string): Error { const e = new Error(message) as Error & { code: string; status: number }; e.code = code; e.status = status; return e; }