import { Buffer } from 'node:buffer'; import { EngineError, EngineErrorCode, DEFAULT_BUNDLE_LIMITS, checkSetGroup, wirePack, type AnnotationActor, type BundleLimits, type AnnotationDeleteResult, type AnnotationUpdateResult, type AnnotationDraft, type AnnotationPatch, type AnnotationResourceRole, type WireAnnotationResources, type AnnotationPosition, type AnnotationRef, type CollabTarget, type DocumentManifest, type DocumentProtection, type PdfPermissionFlags, type WorkerJobId, type AnnotationAppearanceExportInput, type AnnotationFlattenInput, type AnnotationImportBody, toPageRef, PermissionDenied, } from '@embedpdf/engine-core/runtime'; import { AnnotationDraftSchema, AnnotationPatchSchema, AnnotationAppearanceExportInputSchema, AnnotationFlattenInputSchema, AnnotationReorderBodySchema, decodeAnnotationAppearancesRenderToken, decodeAnnotationToken, decodeAnnotationsAllToken, AnnotationImportBodySchema, AnnotationResourceKeysSchema, AnnotationsExportRequestSchema, decodeAnnotationsExportToken, type AnnotationsExportToken, type TokenPin, } from '@embedpdf/engine-core/wire'; import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; import { abortSignalOf, parseOrInvalidArg, parseTokenOrInvalidArg, readAtPins, resolvePageKeyParam, setImmutableCache, setNoStore, type SchemaLike, objectNumberQuery, } from './_helpers'; import { sendBundle } from './_bundleExportResponse'; import { readBundleImportRequest } from './_bundleImportRequest'; import { renderAppearanceBatch, resolvePageForRead, type ReadScope } from './_appearanceBatch'; import { policyByRole, readMutationEnvelope, resourcesByRole, type MutationEnvelope, } from './_mutationEnvelope'; import { requireSharedDocRead } from './_planeGuard'; import { assertRefMatchesPage, refFromKey } from './annotation-route-helpers'; import { requireLayerCapability, requireLayerAnnotationWrite, requireLayerCollabAction, requireLayerDocAccessOnly, requireLayerResource, type RequestJwtContext, } from '../app/jwt-plugin'; import { SharpImageEncoder } from '../render/SharpImageEncoder'; import type { DerivedRenderService } from '../services/DerivedRenderService'; import type { DocumentService } from '../services/DocumentService'; import type { LayerService } from '../services/LayerService'; interface AnnotationRouteDeps { documentService: DocumentService; layerService: LayerService; imageEncoder: SharpImageEncoder; /** Encode appearance renders in the engine worker by default. * `false` = the `CLOUDPDF_ENCODE_IN_ENGINE=0` escape hatch. */ encodeInEngine?: boolean; /** Render-lattice policy plane (absent = legacy compute-only). */ derivedRenders?: DerivedRenderService; /** How large an exported or imported annotation bundle may be; the defaults otherwise. */ bundleLimits?: BundleLimits; } export async function registerAnnotationRoutes( app: FastifyInstance, deps: AnnotationRouteDeps, ): Promise { const { documentService, layerService, imageEncoder, derivedRenders } = deps; const encodeInEngine = deps.encodeInEngine ?? true; const bundleLimits = deps.bundleLimits ?? DEFAULT_BUNDLE_LIMITS; // ── Plane-scoped doc-level reads: a base's own annotations — // inline ones included — are simply visible through every // annotations-inheriting layer, so the list and appearance batches are // one CDN object served from the base worker session. Guarded by the // `annotations` plane (`requireSharedDocRead`); an annotation-writing // layer 404s here into the SDK's manifest-refresh rail and reads its // own layer-scoped view. ───────────────────────────────────────────── app.get('/v1/docs/:docId/annotations/pages/:pageKey/items@:token', async (req, reply) => { const { docId, pageKey, token } = req.params as { docId: string; pageKey: string; token: string; }; const ctx = await requireSharedDocRead(req, documentService, docId, 'page-annotations', [ 'annotations', ]); return readAnnotations({ documentService, reply, signal: abortSignalOf(reply), scope: { kind: 'base', ctx, docId }, pageObjectNumber: resolvePageKeyParam(pageKey), requested: parseTokenOrInvalidArg(decodeAnnotationToken, token, 'annotationVersion token'), }); }); app.get( '/v1/docs/:docId/annotations/pages/:pageKey/appearances@:token', { config: { compress: false } }, async (req, reply) => { const { docId, pageKey, token } = req.params as { docId: string; pageKey: string; token: string; }; const ctx = await requireSharedDocRead(req, documentService, docId, 'page-annotations', [ 'annotations', ]); return renderAppearanceBatch({ family: 'annotations', documentService, imageEncoder, encodeInEngine, ...(derivedRenders ? { derivedRenders } : {}), reply, signal: abortSignalOf(reply), scope: { kind: 'base', ctx, docId }, pageObjectNumber: resolvePageKeyParam(pageKey), tokenQuery: parseTokenOrInvalidArg( decodeAnnotationAppearancesRenderToken, token, 'appearance render token', ), query: req.query, }); }, ); app.get( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items@:token', async (req, reply) => { const { docId, layerName, pageKey, token } = req.params as { docId: string; layerName: string; pageKey: string; token: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource(req, docId, layerName, 'annotations-read', permissionFlags); return readAnnotations({ documentService, reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, pageObjectNumber: resolvePageKeyParam(pageKey), requested: parseTokenOrInvalidArg(decodeAnnotationToken, token, 'annotationVersion token'), }); }, ); app.get( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items', async (req, reply) => { const { docId, layerName, pageKey } = req.params as { docId: string; layerName: string; pageKey: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource(req, docId, layerName, 'annotations-read', permissionFlags); return readAnnotations({ documentService, reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, pageObjectNumber: resolvePageKeyParam(pageKey), }); }, ); // ── Whole-document bulk listing: one CDN-immutable object per // `annotationsVersion` pin, materialized by a single raw (no // page-load) sweep. The doc-level twin serves annotations-inheriting // layers from the base session; a diverged layer reads its own view. // The plain layer route is the public backend operation; the viewer // protocol continues to use the immutable version-addressed routes. ─ app.get('/v1/docs/:docId/annotations/items@:token', async (req, reply) => { const { docId, token } = req.params as { docId: string; token: string }; const ctx = await requireSharedDocRead(req, documentService, docId, 'annotations-all', [ 'annotations', ]); return readAnnotationsAll({ documentService, reply, signal: abortSignalOf(reply), scope: { kind: 'base', ctx, docId }, requested: parseTokenOrInvalidArg( decodeAnnotationsAllToken, token, 'annotationsVersion token', ), }); }); app.get('/v1/docs/:docId/layers/:layerName/annotations/items@:token', async (req, reply) => { const { docId, layerName, token } = req.params as { docId: string; layerName: string; token: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource( req, docId, layerName, 'layer-annotations-all', permissionFlags, ); return readAnnotationsAll({ documentService, reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, requested: parseTokenOrInvalidArg( decodeAnnotationsAllToken, token, 'annotationsVersion token', ), }); }); // ── Annotation export: a bundle as multipart at an annotation and a layout // pin (the bundle carries its pages' positions and boxes). It egresses // content, so it needs `doc.download` beside the annotation read. // Immutable per token, so the CDN can cache it; the doc-level twin // serves layers that inherit both planes. ─ app.get( '/v1/docs/:docId/annotations/export@:token', { config: { compress: false } }, async (req, reply) => { const { docId, token } = req.params as { docId: string; token: string }; const ctx = await requireSharedDocRead(req, documentService, docId, 'annotations-export', [ 'annotations', 'layout', ]); return exportAnnotations({ documentService, limits: bundleLimits, reply, signal: abortSignalOf(reply), scope: { kind: 'base', ctx, docId }, token: parseTokenOrInvalidArg( decodeAnnotationsExportToken, token, 'annotation export token', ), }); }, ); app.get( '/v1/docs/:docId/layers/:layerName/annotations/export@:token', { config: { compress: false } }, async (req, reply) => { const { docId, layerName, token } = req.params as { docId: string; layerName: string; token: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource( req, docId, layerName, 'layer-annotations-export', permissionFlags, ); return exportAnnotations({ documentService, limits: bundleLimits, reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, token: parseTokenOrInvalidArg( decodeAnnotationsExportToken, token, 'annotation export token', ), }); }, ); // An export whose selection a URL can't carry (a long ref list): the same // pins and the selection in the body, answered uncached. app.post( '/v1/docs/:docId/layers/:layerName/annotations/export', { config: { compress: false } }, async (req, reply) => { const { docId, layerName } = req.params as { docId: string; layerName: string }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource( req, docId, layerName, 'layer-annotations-export', permissionFlags, ); const request = parseOrInvalidArg>( AnnotationsExportRequestSchema as unknown as SchemaLike< Omit >, req.body, 'request body', ); return exportAnnotations({ documentService, limits: bundleLimits, reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, token: request, cache: 'no-store', }); }, ); app.get('/v1/docs/:docId/layers/:layerName/annotations/items', async (req, reply) => { const { docId, layerName } = req.params as { docId: string; layerName: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource( req, docId, layerName, 'layer-annotations-all', permissionFlags, ); return readAnnotationsAll({ documentService, reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, }); }); // Batch-rendered annotation appearance bitmaps for a page, returned as a // `multipart/form-data` body (one image part per annotation + a JSON // manifest). Sibling of `items` under the same `annotations-read` resource, // so it shares the `doc.annotate.read` gate and the CDN coverage — reading // an annotation lets you see its rendered appearance. `compress: false` // keeps the binary multipart body un-gzipped end to end. app.get( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/appearances@:token', { config: { compress: false } }, async (req, reply) => { const { docId, layerName, pageKey, token } = req.params as { docId: string; layerName: string; pageKey: string; token: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource(req, docId, layerName, 'annotations-read', permissionFlags); return renderAppearanceBatch({ family: 'annotations', documentService, imageEncoder, encodeInEngine, ...(derivedRenders ? { derivedRenders } : {}), reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, pageObjectNumber: resolvePageKeyParam(pageKey), tokenQuery: parseTokenOrInvalidArg( decodeAnnotationAppearancesRenderToken, token, 'appearance render token', ), query: req.query, }); }, ); app.get( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/appearances', { config: { compress: false } }, async (req, reply) => { const { docId, layerName, pageKey } = req.params as { docId: string; layerName: string; pageKey: string; }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerResource(req, docId, layerName, 'annotations-read', permissionFlags); return renderAppearanceBatch({ family: 'annotations', documentService, imageEncoder, encodeInEngine, ...(derivedRenders ? { derivedRenders } : {}), reply, signal: abortSignalOf(reply), scope: { kind: 'layer', ctx, docId, layerName }, pageObjectNumber: resolvePageKeyParam(pageKey), query: req.query, }); }, ); // A bundle's annotations, created as one change. The parts stream in // under the bundle limits; the `Idempotency-Key` header names the import, // so a retry returns what the first request committed. app.post('/v1/docs/:docId/layers/:layerName/annotations/import', async (req, reply) => { const { docId, layerName } = req.params as { docId: string; layerName: string }; const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const protection = await documentService.getProtection(accessCtx, docId, layerName); const limits = bundleLimits; const { body, resources } = await readBundleImportRequest(req, limits, { kind: 'annotation', bodySchema: AnnotationImportBodySchema as unknown as SchemaLike, }); const attribution = body.options.attribution ?? 'restore'; let ctx: ReturnType; if (attribution === 'restore') { // Restoring writes attribution that isn't the caller's, groups // included, so it takes the capabilities instead of per-group checks. requireLayerCapability( req, docId, layerName, 'doc.annotate.modify', permissionFlags, protection, ); ctx = requireLayerCapability( req, docId, layerName, 'doc.annotate.import', permissionFlags, protection, ); } else { // Each annotation is made as a create makes it, so each group the // items name takes the authority a create in it would, and nothing // more: a user who may create their own annotations may paste them. const groups = new Set(); for (const item of body.bundle.items as unknown as Array<{ data?: { groupId?: unknown }; }>) { const groupId = item?.data?.groupId; groups.add(typeof groupId === 'string' ? groupId : undefined); } // An empty bundle still takes the authority to create. if (groups.size === 0) groups.add(undefined); let checked: ReturnType | undefined; for (const groupId of groups) { const group = createGroupOf(accessCtx.jwt, { groupId } as AnnotationDraft); const target = targetForSelfCreate(accessCtx.jwt, group); checked = requireLayerCollabAction( req, docId, layerName, 'create', target, permissionFlags, protection, ); } ctx = checked!; } // The caller: whom `stamp` attributes to, whom `restore` records as `importedBy`. const actor = actorFromJwt(ctx.jwt, accessCtx.jwt.identity.groupId); setNoStore(reply); return layerService.importAnnotations( ctx, { docId, layerName, bundle: { ...body.bundle, resources }, ...(body.options.pages !== undefined ? { pages: body.options.pages } : {}), attribution, ...(actor ? { actor } : {}), limits, }, abortSignalOf(reply), ); }); app.post( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items', async (req, reply) => { const { docId, layerName, pageKey } = req.params as { docId: string; layerName: string; pageKey: string; }; const pageObjectNumber = resolvePageKeyParam(pageKey); const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const protection = await documentService.getProtection(accessCtx, docId, layerName); const envelope = await readMutationEnvelope(req, annotationBinaryPolicy); // The draft, and beside its fields the files it names by role. const { resources: named, ...data } = isRecord(envelope.body) ? envelope.body : {}; const draft = parseOrInvalidArg( AnnotationDraftSchema as unknown as SchemaLike, isRecord(envelope.body) ? data : envelope.body, 'request body', ); const resources = annotationResourcesOf(envelope, named); // Creation is a collab check against the caller's own identity // (no impersonation), in the group the annotation is created in: // the draft's, when it names one the caller may set, else the // caller's default. `:self`/`:all` trivially pass; `:group=X` // constrains that group to X. Under the narrowing model, // `doc.annotate.modify` covers create when no create-collab filter // is present. const groupId = createGroupOf(accessCtx.jwt, draft); const target = targetForSelfCreate(accessCtx.jwt, groupId); const ctx = requireLayerCollabAction( req, docId, layerName, 'create', target, permissionFlags, protection, ); const actor = actorFromJwt(ctx.jwt, groupId); const objectNumber = objectNumberQuery(req.query, 'objectNumber'); setNoStore(reply); return layerService.createAnnotation( ctx, { docId, layerName, pageObjectNumber, draft, actor, ...(resources ? { resources } : {}), ...(objectNumber !== undefined ? { objectNumber } : {}), }, abortSignalOf(reply), ); }, ); app.post( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items/reorder', async (req, reply) => { const { docId, layerName, pageKey } = req.params as { docId: string; layerName: string; pageKey: string; }; const pageObjectNumber = resolvePageKeyParam(pageKey); const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const protection = await documentService.getProtection(accessCtx, docId, layerName); // The worker checks each annotation it moves inside the write: a // reorder takes `doc.annotate.modify`. Widgets have their own order. const ctx = requireLayerAnnotationWrite(req, docId, layerName, permissionFlags, protection); const { refs, position } = parseOrInvalidArg<{ refs: AnnotationRef[]; position: AnnotationPosition; }>( AnnotationReorderBodySchema as unknown as SchemaLike<{ refs: AnnotationRef[]; position: AnnotationPosition; }>, req.body ?? {}, 'body', ); for (const ref of refs) assertRefMatchesPage(ref, pageObjectNumber); setNoStore(reply); return layerService.reorderAnnotations( ctx, { docId, layerName, pageObjectNumber, refs, position, authority: ctx.authority }, abortSignalOf(reply), ); }, ); // Selective flatten: `pages.flatten` for a chosen set of this page's // annotations — the whole-page verb's gates, one page's content and // annotation pins bumped, persisted like a page flatten. app.post( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items/flatten', async (req, reply) => { const { docId, layerName, pageKey } = req.params as { docId: string; layerName: string; pageKey: string; }; const pageObjectNumber = resolvePageKeyParam(pageKey); const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const protection = await documentService.getProtection(accessCtx, docId, layerName); const ctx = requireLayerCapability( req, docId, layerName, 'doc.pages.modify', permissionFlags, protection, ); requireLayerCapability( req, docId, layerName, 'doc.annotate.modify', permissionFlags, protection, ); const raw = (req.body ?? {}) as { refs?: unknown; usage?: unknown }; const body = parseOrInvalidArg( AnnotationFlattenInputSchema as unknown as SchemaLike, { refs: raw.refs, usage: raw.usage ?? 'display' }, 'request body', ); for (const ref of body.refs) assertRefMatchesPage(ref, pageObjectNumber); setNoStore(reply); return layerService.flattenAnnotations( ctx, { docId, layerName, pageObjectNumber, refs: body.refs, usage: body.usage }, abortSignalOf(reply), ); }, ); // The chosen annotations' appearances as one single-page PDF: a derived // read that egresses content, gated by `doc.download` like pages/extract. app.post( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items/appearance', async (req, reply) => { const { docId, layerName, pageKey } = req.params as { docId: string; layerName: string; pageKey: string; }; const pageObjectNumber = resolvePageKeyParam(pageKey); const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerCapability(req, docId, layerName, 'doc.download', permissionFlags); const body = parseOrInvalidArg( AnnotationAppearanceExportInputSchema as unknown as SchemaLike, req.body, 'request body', ); for (const ref of body.refs) assertRefMatchesPage(ref, pageObjectNumber); const bytes = await documentService.exportAnnotationAppearance( ctx, docId, layerName, pageObjectNumber, body.refs, abortSignalOf(reply), ); setNoStore(reply); reply.type('application/pdf'); return reply.send(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }, ); // An annotation's `appearance` resource: its drawing, as a one-page PDF. A // read that egresses content, gated by `doc.download` like the export above. app.get( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items/:annotationKey/resources/appearance', async (req, reply) => { const { docId, layerName, pageKey, annotationKey: annotKey, } = req.params as { docId: string; layerName: string; pageKey: string; annotationKey: string; }; const pageObjectNumber = resolvePageKeyParam(pageKey); const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const ctx = requireLayerCapability(req, docId, layerName, 'doc.download', permissionFlags); const bytes = await documentService.readAnnotationAppearance( ctx, docId, layerName, pageObjectNumber, refFromKey(annotKey, pageObjectNumber), abortSignalOf(reply), ); setNoStore(reply); reply.type('application/pdf'); return reply.send(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)); }, ); app.patch( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items/:annotationKey', async (req, reply) => { const { docId, layerName, pageKey, annotationKey: annotKey, } = req.params as { docId: string; layerName: string; pageKey: string; annotationKey: string; }; const pageObjectNumber = resolvePageKeyParam(pageKey); const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const protection = await documentService.getProtection(accessCtx, docId, layerName); const envelope = await readMutationEnvelope(req, annotationBinaryPolicy); const body = envelope.body as Record | null | undefined; const resources = annotationResourcesOf(envelope, body?.resources); const signal = abortSignalOf(reply); setNoStore(reply); return updateAnnotation( req, permissionFlags, protection, { docId, layerName, ref: refFromKey(annotKey, pageObjectNumber), patch: body?.patch, resources, }, signal, ); }, ); app.delete( '/v1/docs/:docId/layers/:layerName/annotations/pages/:pageKey/items/:annotationKey', async (req, reply) => { const { docId, layerName, pageKey, annotationKey: annotKey, } = req.params as { docId: string; layerName: string; pageKey: string; annotationKey: string; }; const pageObjectNumber = resolvePageKeyParam(pageKey); const accessCtx = requireLayerDocAccessOnly(req, docId, layerName); const permissionFlags = await documentService.getEffectivePermissionFlags( accessCtx, docId, layerName, ); const protection = await documentService.getProtection(accessCtx, docId, layerName); setNoStore(reply); return deleteAnnotation( req, permissionFlags, protection, { docId, layerName, ref: refFromKey(annotKey, pageObjectNumber) }, abortSignalOf(reply), ); }, ); /** * Update an annotation. The patch has to fit some kind here; the worker * checks it against the kind it leaves the target (its own, or a sibling * its `subtype` names), and the caller's authority against the target's * owner, inside the write. */ async function updateAnnotation( req: FastifyRequest, permissionFlags: PdfPermissionFlags, protection: DocumentProtection | null, input: { docId: string; layerName: string; ref: AnnotationRef; patch: unknown; resources: WireAnnotationResources | undefined; }, signal: AbortSignal, ): Promise { const { docId, layerName, ref, resources } = input; const ctx = requireLayerAnnotationWrite(req, docId, layerName, permissionFlags, protection); const patch = parseOrInvalidArg( AnnotationPatchSchema as unknown as SchemaLike, input.patch, 'body.patch', ); return layerService.updateAnnotation( ctx, { docId, layerName, ref, patch, authority: ctx.authority, ...(resources ? { resources } : {}), }, signal, ); } /** * Delete an annotation with its thread and popups. The worker checks the * caller's authority against each of them inside the write: all or * nothing. */ async function deleteAnnotation( req: FastifyRequest, permissionFlags: PdfPermissionFlags, protection: DocumentProtection | null, input: { docId: string; layerName: string; ref: AnnotationRef }, signal: AbortSignal, ): Promise { const ctx = requireLayerAnnotationWrite( req, input.docId, input.layerName, permissionFlags, protection, ); return layerService.deleteAnnotation(ctx, { ...input, authority: ctx.authority }, signal); } } // ---------------------------------------------------------------------- // Annotation identity helpers // // Small pure helpers for the identity a mutation carries: // - createGroupOf: the group a create lands in (set-group checked) // - targetForSelfCreate: build the CollabTarget for create checks // from JWT identity (no impersonation). // - actorFromJwt: build the worker actor for create from JWT // identity. The worker stamps /T, // /EMBD_Metadata/UserID,CreatedBy,UpdatedBy, // and /EMBD_Metadata/GroupID. // - buildUpdateActor: build the update actor (modification trail // + optional group reassignment gated by // :set-group). // ---------------------------------------------------------------------- /** * The group a new annotation is created in: the draft's `groupId` when it * names one, else the caller's default group. A group other than the * caller's own needs `annotations:set-group` authority for it, as a * reassignment on update does. */ function createGroupOf(jwt: RequestJwtContext, draft: AnnotationDraft): string | undefined { const groupId = (draft as { groupId?: string | null }).groupId ?? jwt.identity.groupId; if (groupId !== undefined && groupId !== jwt.identity.groupId) { if (!checkSetGroup('annotations', groupId, jwt.identity.groupId, jwt.scope)) { throw new PermissionDenied('annotations:set-group', `group=${groupId}`); } } return groupId; } /** * Build the CollabTarget for a create check. Targets the caller's own * identity — no impersonation — in the group the annotation is created * in. `:self`/`:all` pass trivially; `:group=X` is the meaningful filter. */ function targetForSelfCreate(jwt: RequestJwtContext, groupId: string | undefined): CollabTarget { const { userId } = jwt.identity; return { ...(userId !== undefined ? { userId } : {}), ...(groupId !== undefined ? { groupId } : {}), }; } /** * How an annotation's parts are checked, by the role the body gives them: * an `appearance` must be PNG, JPEG or PDF, and a `file` may be any bytes * (attaching any format is the point). */ const annotationBinaryPolicy = policyByRole({ file: 'any' }); /** The files an annotation write names by role, `resources: { appearance, file }`. */ function annotationResourcesOf( envelope: MutationEnvelope, named: unknown, ): WireAnnotationResources | undefined { if (named === undefined && !envelope.resources) return undefined; const keys = parseOrInvalidArg( AnnotationResourceKeysSchema as unknown as SchemaLike< Partial> >, named ?? {}, 'resources', ); const resources: WireAnnotationResources = {}; for (const [role, part] of Object.entries(resourcesByRole(envelope, keys))) { if (part) resources[role as AnnotationResourceRole] = part.bytes; } return resources; } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } /** * Build the CREATE actor from the caller's JWT identity. The worker * writes: * * /T ← actor.displayName * /EMBD_Metadata/UserID,CreatedBy,UpdatedBy ← actor.userId * /EMBD_Metadata/GroupID ← actor.groupId * * Returns `undefined` when the JWT carries no identity at all * (anonymous tenant tokens) — the worker still stamps /M but skips /T * and /EMBD_Metadata. */ function actorFromJwt( jwt: RequestJwtContext, groupId: string | undefined, ): AnnotationActor | undefined { const { userId, displayName } = jwt.identity; const actor: AnnotationActor = { ...(userId !== undefined ? { userId } : {}), ...(groupId !== undefined ? { groupId } : {}), ...(displayName !== undefined ? { displayName } : {}), }; return actor.userId || actor.groupId || actor.displayName ? actor : undefined; } async function readAnnotations(input: { documentService: DocumentService; reply: FastifyReply; signal: AbortSignal; scope: ReadScope; pageObjectNumber: number; requested?: { annotationVersion: number; pin: TokenPin }; }) { const scope = input.scope; const assertCurrent = async () => { const page = await resolvePageForRead(input); if ( input.requested !== undefined && input.requested.annotationVersion !== page.cache.annotationVersion ) { throw new EngineError( EngineErrorCode.NotFound, `${scope.kind === 'layer' ? 'layer ' : ''}annotation version ${ input.requested.annotationVersion } no longer current (current=${page.cache.annotationVersion}) for page ${ input.pageObjectNumber }`, ); } }; const read = async () => { if (scope.kind === 'layer') { await input.documentService.ensureLayerOnPool(scope.ctx, scope.docId, scope.layerName); } // Raw read (docPtr dictionary walk, no FPDF_LoadPage): wire-identical to // the full path today — no dispatched subtype reader uses the pagePtr — // and ~1000x cheaper per cold leaf materialization. If a pagePtr-dependent // reader ever lands, the local-vs-cloud conformance parity diff fails and // forces this choice back onto the table (safe-by-conformance). const build = (jobId: WorkerJobId) => wirePack({ kind: 'annotations.list' as const, effect: 'read' as const, jobId, docId: scope.docId, ...(scope.kind === 'layer' ? { layerName: scope.layerName } : {}), pages: [toPageRef(input.pageObjectNumber)], }); const result = await input.documentService.readOnPool( scope.ctx, scope.docId, scope.kind === 'layer' ? scope.layerName : undefined, build, input.signal, ); if (result.tag !== 'annotations.list') { throw new EngineError( EngineErrorCode.WireFormat, `unexpected ${scope.kind === 'layer' ? 'layer ' : ''}annotations.list payload: ${result.tag}`, ); } return result.list; }; const list = await readAtPins({ documentService: input.documentService, reply: input.reply, docId: scope.docId, layerName: scope.kind === 'layer' ? scope.layerName : undefined, assertCurrent, read, token: input.requested && { kind: 'annotations', pin: input.requested.pin }, }); input.requested === undefined ? setNoStore(input.reply) : setImmutableCache(input.reply); return list; } /** * One export job, read at the token's pins (see `readAtPins`): a stale pin * is a 404 the client answers by refreshing its manifest. The response is the bundle * without its bytes as the `body` part, then one `resource:` part per * resource. */ async function exportAnnotations(input: { documentService: DocumentService; limits: BundleLimits; reply: FastifyReply; signal: AbortSignal; scope: ReadScope; /** A POST carries its pins in its body, without an engine value or shape. */ token: Omit & { pin?: TokenPin }; /** A GET at its token is immutable; a POST is answered uncached. */ cache?: 'immutable' | 'no-store'; }) { const { scope, token } = input; const layerName = scope.kind === 'layer' ? scope.layerName : undefined; const assertCurrent = async () => { const manifest = layerName !== undefined ? await input.documentService.getLayerManifest(scope.ctx, scope.docId, layerName) : await input.documentService.getManifest(scope.ctx, scope.docId); const annotationsVersion = manifest.annotationsVersion ?? 1; const layoutVersion = manifest.layoutVersion ?? 1; if (token.annotationsVersion !== annotationsVersion || token.layoutVersion !== layoutVersion) { throw new EngineError( EngineErrorCode.NotFound, `annotation export at annotationsVersion ${token.annotationsVersion}, layoutVersion ${token.layoutVersion} no longer current (current: ${annotationsVersion}, ${layoutVersion})`, ); } }; const read = async () => { const build = (jobId: WorkerJobId) => wirePack({ kind: 'annotations.export' as const, effect: 'snapshot' as const, jobId, docId: scope.docId, ...(layerName !== undefined ? { layerName } : {}), selection: token.selection, limits: input.limits, }); const result = await input.documentService.readOnPool( scope.ctx, scope.docId, layerName, build, input.signal, ); if (result.tag !== 'annotations.export') { throw new EngineError( EngineErrorCode.WireFormat, `unexpected annotations.export payload: ${result.tag}`, ); } return result.bundle; }; const bundle = await readAtPins({ documentService: input.documentService, reply: input.reply, docId: scope.docId, layerName, assertCurrent, read, token: { kind: 'annotationsExport', pin: token.pin }, }); return sendBundle(input.reply, bundle, input.cache ?? 'immutable'); } /** * Whole-document bulk read: one `annotations.list` worker job (the raw * docPtr sweep, no per-page loads). A version-addressed read is read at its * pin (see `readAtPins`). The current-version read retries once if a * mutation races the sweep, then returns a retryable conflict rather than * mixing a snapshot with the wrong audit cursor. The response stamps the * pre-check manifest's `auditHead`, so replaying events with * `serverId > auditHead` over this body is exact. */ async function readAnnotationsAll(input: { documentService: DocumentService; reply: FastifyReply; signal: AbortSignal; scope: ReadScope; requested?: { annotationsVersion: number; pin: TokenPin }; }) { const scope = input.scope; const getManifest = () => scope.kind === 'layer' ? input.documentService.getLayerManifest(scope.ctx, scope.docId, scope.layerName) : input.documentService.getManifest(scope.ctx, scope.docId); const read = async () => { if (scope.kind === 'layer') { await input.documentService.ensureLayerOnPool(scope.ctx, scope.docId, scope.layerName); } const build = (jobId: WorkerJobId) => wirePack({ kind: 'annotations.list' as const, effect: 'read' as const, jobId, docId: scope.docId, ...(scope.kind === 'layer' ? { layerName: scope.layerName } : {}), }); const result = await input.documentService.readOnPool( scope.ctx, scope.docId, scope.kind === 'layer' ? scope.layerName : undefined, build, input.signal, ); if (result.tag !== 'annotations.list') { throw new EngineError( EngineErrorCode.WireFormat, `unexpected ${scope.kind === 'layer' ? 'layer ' : ''}annotations.list payload: ${ result.tag }`, ); } return result.list; }; const { requested } = input; if (requested !== undefined) { let auditHead: DocumentManifest['auditHead'] | undefined; let checked = false; const list = await readAtPins({ documentService: input.documentService, reply: input.reply, docId: scope.docId, layerName: scope.kind === 'layer' ? scope.layerName : undefined, assertCurrent: async () => { const manifest = await getManifest(); const current = manifest.annotationsVersion ?? 1; if (requested.annotationsVersion !== current) { throw new EngineError( EngineErrorCode.NotFound, `${scope.kind === 'layer' ? 'layer ' : ''}annotations version ${requested.annotationsVersion} no longer current (current=${current})`, ); } if (!checked) auditHead = manifest.auditHead; checked = true; }, read, token: { kind: 'annotationsAll', pin: requested.pin }, }); setImmutableCache(input.reply); return { ...list, auditHead }; } for (let attempt = 0; attempt < 2; attempt += 1) { const manifest = await getManifest(); const current = manifest.annotationsVersion ?? 1; const list = await read(); const fresh = await getManifest(); if ((fresh.annotationsVersion ?? 1) !== current) continue; setNoStore(input.reply); return { ...list, auditHead: manifest.auditHead }; } setNoStore(input.reply); throw new EngineError( EngineErrorCode.LayerVersionConflict, `${scope.kind === 'layer' ? 'layer ' : ''}annotations changed while reading; retry the request`, ); }