import type { DocCapability } from '@embedpdf/engine-core/runtime'; import { closed, IsoDateTimeSchema, ChangeRequestSchema, ChangeResponseSchema, PageScaleInputSchema, PageScaleResultSchema, PageMeasurementViewportListSchema, } from '@embedpdf/engine-core/wire'; import { AnnotationCreateResultSchema, AnnotationDeleteResultSchema, AnnotationFlattenResultSchema, AnnotationListSchema, AnnotationReorderBodySchema, AnnotationReorderResultSchema, AnnotationUpdateResultSchema, DocumentHeadSchema, DocumentManifestSchema, CustomMetadataSchema, DocumentMetadataSchema, DocumentOutlineSchema, ErrorResponseSchema, FormResetBodySchema, FormWidgetDeleteResultSchema, FormWidgetUpdateBodySchema, FormWidgetUpdateResultSchema, FormWidgetsReorderBodySchema, FormWidgetsReorderResultSchema, FormCalculationsReorderBodySchema, FormCalculationsReorderResultSchema, FormResetResultSchema, FormSetValueResultSchema, FormSnapshotSchema, FontListSchema, FontProgramInfoSchema, FontResolutionSchema, FontResolveRequestSchema, IdentityInputSchema, IdentitySchema, PageFlattenResultSchema, PageNameResultSchema, RedactionApplyResultSchema, RedactionApplyScopeInputSchema, PageTextSnapshotSchema, ChangeAnalysisSchema, LayerVersionsSchema, SignatureCancelResultSchema, SignatureCompleteBodySchema, SignatureCompleteResultSchema, SignaturePreparedWireSchema, SignatureSnapshotSchema, ValidationInfoAddBodySchema, ValidationInfoAddResultSchema, ValidationInfoWireSchema, AttachmentListSchema, wireTemplates, } from '@embedpdf/engine-core/wire'; import { z } from 'zod'; const sha256Hex = /^[0-9a-f]{64}$/i; const docIdPattern = /^[A-Za-z0-9_-]+$/; /** * A point in time a request gives: ISO 8601 with its offset (`Z` or * `±HH:mm`), as every response says one. Without an offset the moment would * depend on the server's zone, so it's refused. */ const InstantInputSchema = z.string().datetime({ offset: true }); /** * Tenant ids share the doc-id charset: URL-safe by construction, since * they appear in every tenant-scoped path (and therefore in logs — do * not put PII in tenant ids). */ export const tenantIdPattern = /^[A-Za-z0-9_-]+$/; /** * A web origin pattern: scheme + host (+ optional port), no path. One * leading `*.` label is allowed and matches one or more subdomain * labels (`https://*.acme.com` covers `docs.acme.com`, never bare * `acme.com` and never `evilacme.com`). */ const originPattern = /^https?:\/\/(\*\.)?[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*(:\d{1,5})?$/; const originPatternArray = z .array( z .string() .max(262) .regex( originPattern, 'must be a web origin like https://example.com (optionally one leading *. wildcard label, optional port, no path)', ), ) .min(1) .max(32); /** * A grant's id: `grt_` + 24 url-safe random chars. Grants made before the rename are `shr_…` * and keep working. */ const grantIdPattern = /^(grt|shr)_[A-Za-z0-9_-]{24}$/; /** What a grant is called in the dashboard, for example "Website" or "Sent to Acme". */ const grantNameSchema = z.string().trim().min(1).max(100); /** A query-string flag, `true` or `false`. */ const queryFlag = z.preprocess( (value) => (value === 'true' ? true : value === 'false' ? false : value), z.boolean(), ); /** * Wire paths. The URL carries the full resource identity — tenant * resources live under `/v1/tenants/{tenantId}/…` — and the auth model * is one rule: the API token is valid everywhere; a JWT is valid * exactly under the subtree of the resource it names. */ export const adminWirePaths = { tenants: '/v1/tenants', tenant: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}`, documents: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents`, documentsInit: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents/init`, documentsImport: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents/import`, document: (tenantId: string, docId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents/${encodeURIComponent(docId)}`, documentCommit: (tenantId: string, docId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents/${encodeURIComponent(docId)}/commit`, documentUploadProxy: (tenantId: string, docId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents/${encodeURIComponent(docId)}/upload-proxy`, documentDownload: (tenantId: string, docId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents/${encodeURIComponent(docId)}/download`, /** The warmed dashboard-tile artifact. Returns 404 while `pending`/`locked`. */ documentThumbnail: (tenantId: string, docId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/documents/${encodeURIComponent(docId)}/thumbnail`, folders: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/folders`, folder: (tenantId: string, folderId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/folders/${encodeURIComponent(folderId)}`, folderMoveInto: (tenantId: string, folderId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/folders/${encodeURIComponent(folderId)}/move-into`, tokenIssue: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/tokens`, tokenRevoke: (tenantId: string, jti: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/tokens/${encodeURIComponent(jti)}/revoke`, grants: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/grants`, grant: (tenantId: string, grantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/grants/${encodeURIComponent(grantId)}`, tenantUsage: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/usage`, tenantSuspend: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/suspend`, tenantResume: (tenantId: string) => `/v1/tenants/${encodeURIComponent(tenantId)}/resume`, /** * The public grant-session exchange. Deliberately outside any tenant * subtree: the caller holds only a grant's id and does not know the * tenant — the grant row resolves it server-side. */ grantSessions: '/v1/grant-sessions', /** Deployment-global singletons: API-token only, no tenant context. */ deploymentLicenseStatus: '/v1/deployment/license/status', deploymentModules: '/v1/deployment/modules', } as const; export const DedupModeSchema = z .enum(['always-create', 'reuse-existing']) .describe( 'always-create (default) creates a new document every time. reuse-existing returns a document that already holds the same content instead of storing it twice.', ); export type DedupMode = z.infer; export const UploadPreferenceSchema = z.enum(['auto', 'presigned', 'proxy']); export type UploadPreference = z.infer; export const DocumentStateSchema = closed(z.enum(['pending', 'ready', 'failed', 'deleting'])); export type DocumentState = z.infer; /** Any text a person can read: no control characters, no leading or trailing whitespace. */ const readableNamePattern = // eslint-disable-next-line no-control-regex -- excluding control characters is its job /^[^\s\u0000-\u001F\u007F](?:[^\u0000-\u001F\u007F]*[^\s\u0000-\u001F\u007F])?$/u; export const DocumentNameSchema = z .string() .min(1) .max(255) .regex(readableNamePattern) .describe( 'What people call the document: shown in dashboards, searched and sorted by. 1 to 255 characters, no control characters, no leading or trailing whitespace. Names need not be unique.', ); const folderIdPattern = /^fld_[0-9a-f]{24}$/; /** A folder id, or `root` for the top level, which has no folder of its own. */ const folderPlacePattern = /^(root|fld_[0-9a-f]{24})$/; export const FolderPlaceSchema = z .string() .regex(folderPlacePattern) .describe('A folder id, or root for the top level.'); export const FolderNameSchema = z .string() .min(1) .max(255) .regex(readableNamePattern) .describe( "What people call the folder: 1 to 255 characters, no control characters, no leading or trailing whitespace, and unique among the folder's siblings, ignoring case.", ); export const AdminDocumentRecordSchema = z.object({ id: z.string(), tenantId: z.string(), name: z.string(), folderId: z.string().describe('The folder the document is in, or root.'), state: DocumentStateSchema, baseSha256: z.string().nullable(), /** The size of the PDF, in bytes; null until its upload is committed. */ sizeBytes: z.number().int().nullable(), metadata: z.record(z.string(), z.unknown()).nullable(), idempotencyKey: z.string().nullable(), failureReason: z.string().nullable(), /** Dashboard tile lifecycle. */ thumbnailState: closed(z.enum(['pending', 'ready', 'locked', 'failed'])), /** Where to fetch the tile once `thumbnailState` is `ready`; null before. */ thumbnailUrl: z.string().nullable(), createdAt: IsoDateTimeSchema, updatedAt: IsoDateTimeSchema, createdBy: z.string().nullable(), }); export type AdminDocumentRecord = z.infer; export const AdminDocumentInitRequestSchema = z.object({ sizeBytes: z.number().int().min(1), contentSha256: z.string().regex(sha256Hex), /** Defaults to the document id. */ name: DocumentNameSchema.optional(), /** Defaults to root. */ folderId: FolderPlaceSchema.optional(), metadata: z.record(z.string(), z.unknown()).optional(), idempotencyKey: z.string().optional(), dedupMode: DedupModeSchema.optional(), docId: z.string().regex(docIdPattern).optional(), uploadTtlSeconds: z.number().int().min(60).max(3600).optional(), uploadPreference: UploadPreferenceSchema.optional(), }); export type AdminDocumentInitRequest = z.infer; export const AdminPresignedUploadSchema = z.object({ url: z.string(), headers: z.record(z.string(), z.string()), method: closed(z.literal('PUT')), /** When the URL stops taking the upload. */ expiresAt: IsoDateTimeSchema, }); export type AdminPresignedUpload = z.infer; export const AdminInitUploadSchema = closed( z.discriminatedUnion('kind', [ z.object({ kind: z.literal('presigned'), presigned: AdminPresignedUploadSchema, key: z.string(), }), z.object({ kind: z.literal('proxy'), url: z.string(), key: z.string(), }), ]), ); export type AdminInitUpload = z.infer; export const AdminDocumentInitResponseSchema = closed( z.discriminatedUnion('status', [ z.object({ status: z.literal('created'), document: AdminDocumentRecordSchema, upload: AdminInitUploadSchema, }), z.object({ status: z.literal('resumed'), document: AdminDocumentRecordSchema, upload: AdminInitUploadSchema, }), z.object({ status: z.literal('deduped'), document: AdminDocumentRecordSchema, }), ]), ); export type AdminDocumentInitResponse = z.infer; export const AdminDocumentCommitRequestSchema = z.object({ sha256: z.string().regex(sha256Hex), }); export type AdminDocumentCommitRequest = z.infer; export const AdminDocumentCommitResponseSchema = z.object({ document: AdminDocumentRecordSchema, }); export type AdminDocumentCommitResponse = z.infer; /** UTF-8 byte length — provider key limits are byte rules, not JS code units. */ const utf8ByteLength = (s: string): number => new TextEncoder().encode(s).length; /** * A server-side pull source for `documents.importFrom`. The discriminator * distinguishes authorization models, not storage vendors: * * - `url` — the caller supplies authority: a presigned * S3/GCS/Azure/R2/MinIO GET, or any HTTPS endpoint the * deployment's import policy allows. The URL is a capability: * treat it as a secret. Servers never echo its query string back * in errors, logs, or stored failure reasons. * - `connection` — the operator pre-registered authority: the * request names a connection and a key; which provider backs it * (S3, GCS, Azure Blob, filesystem, ...) is deployment * configuration, never wire surface. `revision` is opaque here * and provider-interpreted (S3 VersionId, GCS generation, Azure * version id); unsupported providers reject it. * * Key validation at this layer is deliberately generic (byte length, * no NUL); provider-exact rules live in the server's source adapters, * which know which backend a connection names. */ export const AdminImportSourceSchema = z .discriminatedUnion('kind', [ z .object({ kind: z.literal('url'), url: z .string() .url() .max(8192) .describe( 'The URL to fetch. Must be allowed by the deployment import policy (scheme, network range, size) and must declare a length.', ), }) .describe( 'The caller supplies the authority: a presigned S3/GCS/Azure/R2/MinIO GET, or any HTTPS endpoint the deployment import policy allows. The URL is a capability — treat it as a secret. CloudPDF never echoes its query string back in errors, logs, or stored failure reasons.', ), z .object({ kind: z.literal('connection'), connectionId: z .string() .min(1) .max(128) .describe('The operator-registered storage connection to read from.'), key: z .string() .min(1) .refine((k) => !k.includes('\0'), 'key must not contain NUL') .refine((k) => utf8ByteLength(k) <= 1024, 'key must be at most 1024 UTF-8 bytes') .describe( "The object key to read, inside the connection's configured scope. At most 1024 UTF-8 bytes.", ), revision: z .string() .min(1) .max(1024) .optional() .describe( 'Pins a specific version of the object. Provider-interpreted (S3 VersionId, GCS generation, Azure version id); providers without versioning reject it.', ), }) .describe( 'The operator pre-registered the authority: the request names a connection and a key inside it. Which provider backs the connection (S3, GCS, Azure Blob, filesystem, ...) is deployment configuration, never wire surface.', ), ]) .describe( 'Where CloudPDF pulls the bytes from. The two shapes differ in who supplies the authority to read, not in which storage vendor holds the file.', ); export type AdminImportSource = z.infer; export const AdminDocumentImportRequestSchema = z.object({ source: AdminImportSourceSchema, /** * Optional integrity pins, enforced when present: `sizeBytes` * against the source's declared Content-Length before the transfer, * `sha256` against the server-observed digest after it. When absent * the server-observed values become authoritative. * `dedupMode=reuse-existing` requires `sha256` — without a declared * hash the server cannot know what content to reuse. */ expected: z .object({ sizeBytes: z .number() .int() .min(1) .optional() .describe("Checked against the source's declared Content-Length before the transfer."), sha256: z .string() .regex(sha256Hex) .optional() .describe( 'Checked against the server-observed digest after the transfer. Required when dedupMode is reuse-existing.', ), }) .optional() .describe( 'Integrity pins, enforced when present. When absent, the server-observed values become authoritative.', ), /** Defaults to the document id. */ name: DocumentNameSchema.optional(), /** Defaults to root. */ folderId: FolderPlaceSchema.optional(), metadata: z.record(z.string(), z.unknown()).optional(), idempotencyKey: z .string() .optional() .describe( 'Retrying with the same key resumes the same document rather than importing a second copy — including after a 502.', ), dedupMode: DedupModeSchema.optional(), docId: z.string().regex(docIdPattern).optional(), /** * `sync` (default) holds the response open for the whole transfer. * `async` accepts the request (202, document `pending`), transfers * in the background, and the caller polls the document. Async * requires a `connection` source (URLs are secrets and expire, so * they cannot sit in a durable job); filesystem connections * additionally require `expected.sha256`, since they have no * revisions to pin retries to. */ mode: z .enum(['sync', 'async']) .optional() .describe( 'sync (default) holds the response open for the whole transfer. async answers 202 with the document pending and transfers in the background; it requires a connection source, and filesystem connections additionally require expected.sha256.', ), }); export type AdminDocumentImportRequest = z.infer; export const AdminDocumentImportResponseSchema = z.object({ /** * `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 (HTTP 202); poll the * document until `ready` or `failed`. */ status: closed(z.enum(['imported', 'deduped', 'accepted'])), document: AdminDocumentRecordSchema, }); export type AdminDocumentImportResponse = z.infer; export const AdminDocumentResponseSchema = z.object({ document: AdminDocumentRecordSchema, }); export type AdminDocumentResponse = z.infer; export const AdminDocumentUpdateRequestSchema = z.object({ name: DocumentNameSchema, }); export type AdminDocumentUpdateRequest = z.infer; export const ADMIN_DOCUMENT_LIST_DEFAULT_LIMIT = 100; export const ADMIN_DOCUMENT_LIST_MAX_LIMIT = 200; export const DocumentListSortSchema = z .enum(['createdAt', 'name', 'size']) .describe('createdAt (default), name (ignoring case), or size (stored bytes; 0 while pending).'); export type DocumentListSort = z.infer; export const ListOrderSchema = z .enum(['asc', 'desc']) .describe( 'Defaults to the reading order of the sort: A to Z for name, newest and largest first otherwise.', ); export type ListOrder = z.infer; /** * Query parameters for `documents.list`. `limit` arrives as a string on * the wire, hence the coercion; values outside [1, max] are a validation * error, not a silent clamp. `cursor` is an opaque continuation token * from a previous page's `nextCursor` — clients must not parse it, and it * only continues the `sort` and `order` it was made with. */ export const AdminDocumentListQuerySchema = z.object({ limit: z.coerce .number() .int() .min(1) .max(ADMIN_DOCUMENT_LIST_MAX_LIMIT) .default(ADMIN_DOCUMENT_LIST_DEFAULT_LIMIT), cursor: z.string().min(1).optional(), state: DocumentStateSchema.describe( 'Only documents in this state. Without it, every state except deleting.', ).optional(), q: z .string() .min(1) .max(255) .describe('Only documents whose name contains this text, ignoring case.') .optional(), folderId: FolderPlaceSchema.describe( 'Only documents directly in this folder (root: the top level). Without it, documents in every folder.', ).optional(), sort: DocumentListSortSchema.default('createdAt'), order: ListOrderSchema.optional(), }); export type AdminDocumentListQuery = z.infer; export const AdminDocumentListResponseSchema = z.object({ documents: z.array(AdminDocumentRecordSchema), /** Opaque cursor for the next page; `null` on the last page. */ nextCursor: z.string().nullable(), }); export type AdminDocumentListResponse = z.infer; export const FolderRecordSchema = z.object({ id: z.string(), tenantId: z.string(), parentId: z.string().describe('The folder it is in, or root.'), name: z.string(), createdAt: IsoDateTimeSchema, updatedAt: IsoDateTimeSchema, createdBy: z.string().nullable(), }); export type FolderRecord = z.infer; export const FolderResponseSchema = z.object({ folder: FolderRecordSchema, }); export type FolderResponse = z.infer; export const FolderGetResponseSchema = z.object({ folder: FolderRecordSchema, path: z .array(z.object({ id: z.string(), name: z.string() })) .describe( 'The folders above this one, from the top level down. Neither root nor the folder itself.', ), }); export type FolderGetResponse = z.infer; export const FolderCreateRequestSchema = z.object({ name: FolderNameSchema, /** Defaults to root. */ parentId: FolderPlaceSchema.optional(), }); export type FolderCreateRequest = z.infer; export const FolderUpdateRequestSchema = z.object({ name: FolderNameSchema, }); export type FolderUpdateRequest = z.infer; /** Query parameters for `folders.list`, which orders folders by name. */ export const FolderListQuerySchema = z.object({ limit: z.coerce .number() .int() .min(1) .max(ADMIN_DOCUMENT_LIST_MAX_LIMIT) .default(ADMIN_DOCUMENT_LIST_DEFAULT_LIMIT), cursor: z.string().min(1).optional(), parentId: FolderPlaceSchema.describe( 'Only the folders directly in this folder (root: the top level). Without it, every folder.', ).optional(), }); export type FolderListQuery = z.infer; export const FolderListResponseSchema = z.object({ folders: z.array(FolderRecordSchema), /** Opaque cursor for the next page; `null` on the last page. */ nextCursor: z.string().nullable(), }); export type FolderListResponse = z.infer; export const FolderDeleteQuerySchema = z.object({ recursive: queryFlag .describe('true deletes everything in the folder too. Never the default.') .optional(), }); export type FolderDeleteQuery = z.infer; export const FOLDER_MOVE_MAX_IDS = 1000; export const FolderMoveIntoRequestSchema = z.object({ docIds: z.array(z.string().regex(docIdPattern)).max(FOLDER_MOVE_MAX_IDS).optional(), folderIds: z.array(z.string().regex(folderIdPattern)).max(FOLDER_MOVE_MAX_IDS).optional(), }); export type FolderMoveIntoRequest = z.infer; export const AdminUploadProxyResponseSchema = z.object({ sha256: z.string().regex(sha256Hex), }); export type AdminUploadProxyResponse = z.infer; export const AdminTenantParamsSchema = z.object({ tenantId: z.string().regex(tenantIdPattern), }); export type AdminTenantParams = z.infer; export const AdminTenantDocParamsSchema = z.object({ tenantId: z.string().regex(tenantIdPattern), docId: z.string().regex(docIdPattern), }); export type AdminTenantDocParams = z.infer; export const AdminTenantFolderParamsSchema = z.object({ tenantId: z.string().regex(tenantIdPattern), folderId: z.string().regex(folderIdPattern), }); export type AdminTenantFolderParams = z.infer; /** A destination: any folder, or root. */ export const AdminTenantFolderPlaceParamsSchema = z.object({ tenantId: z.string().regex(tenantIdPattern), folderId: FolderPlaceSchema, }); export type AdminTenantFolderPlaceParams = z.infer; export const AdminTenantDocLayerParamsSchema = AdminTenantDocParamsSchema.extend({ layerName: z.string().min(1).max(256), }); export type AdminTenantDocLayerParams = z.infer; /** * A layer that holds changes: one a grant or your tokens name, or a * grant visitor's own. A layer appears at its first change, and a * deleted one is no longer listed. Read and download it with the API token * through `/v1/docs/{docId}/layers/{layerName}`. */ export const AdminLayerRecordSchema = z.object({ docId: z.string(), layerName: z.string(), /** The grant whose visitor made it (the grant may since be deleted); null otherwise. */ grantId: z.string().nullable(), /** That visitor; null for a layer a grant or token names. */ visitorId: z.string().nullable(), /** Bytes the layer stores: its changes over the document, not the whole PDF. */ sizeBytes: z.number().int().nullable(), /** Its first change. */ createdAt: IsoDateTimeSchema, /** Its last change. */ updatedAt: IsoDateTimeSchema, /** A visitor's layer: when the visitor last opened it; null otherwise. */ lastSeenAt: IsoDateTimeSchema.nullable(), }); export type AdminLayerRecord = z.infer; /** Query parameters for `documents.layers.list`, as for the other lists. */ export const AdminDocumentLayerListQuerySchema = z.object({ limit: z.coerce .number() .int() .min(1) .max(ADMIN_DOCUMENT_LIST_MAX_LIMIT) .default(ADMIN_DOCUMENT_LIST_DEFAULT_LIMIT), cursor: z.string().min(1).optional(), /** Only the layers this grant's visitors made, a deleted grant's too. */ grantId: z.string().regex(grantIdPattern).optional(), }); export type AdminDocumentLayerListQuery = z.infer; export const AdminDocumentLayerListResponseSchema = z.object({ layers: z.array(AdminLayerRecordSchema), /** Opaque cursor for the next page; `null` on the last page. */ nextCursor: z.string().nullable(), }); export type AdminDocumentLayerListResponse = z.infer; export const AdminTenantJtiParamsSchema = z.object({ tenantId: z.string().regex(tenantIdPattern), jti: z.string().min(1).max(256), }); export type AdminTenantJtiParams = z.infer; export const AdminTokenRevokeRequestSchema = z.object({ /** Optional human reason, written to the audit row. */ reason: z.string().max(1024).optional(), /** * When the token expires (its `exp`); the revocation row is * garbage-collected once the token would have expired anyway. Defaults * server-side to 30 days from now. */ expiresAt: InstantInputSchema.optional(), }); export type AdminTokenRevokeRequest = z.infer; /** * License/reporting/usage passthrough. The inner shapes belong to the * licensing runtime and are surfaced as-is; they tighten to full * schemas when the licensing contract stabilizes. Each is always there: * `reporting` is null without a usage reporter, `usage` without meters. */ export const AdminLicenseStatusResponseSchema = z.object({ license: z.record(z.string(), z.unknown()), reporting: z.record(z.string(), z.unknown()).nullable(), usage: z.record(z.string(), z.unknown()).nullable(), }); export type AdminLicenseStatusResponse = z.infer; /** * One server module a tenant may use, named by the module's id. A * module's routes answer only tenants whose `features` hold it. * `stopped` keeps the feature but stops its routes (`402`): `'cap'` is * a spending cap reached, set by whoever bills the tenant; the server * keeps no caps itself. */ export const TenantFeatureSchema = z.object({ /** The module's id: lowercase words joined by `-`. */ id: z .string() .max(64) .regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/), stopped: closed(z.enum(['cap'])).optional(), }); export type TenantFeature = z.infer; export const AdminTenantRecordSchema = z.object({ id: z.string(), name: z.string(), /** True when the namespace materialized on first use rather than via explicit create. */ autoProvisioned: z.boolean(), /** * `suspended` tenants fail closed: every tenant JWT, doc JWT, and * grant exchange is refused until resume. The API token is exempt — * the operator must be able to inspect, resume, or delete a * suspended tenant. Optional because older servers omit it. */ status: closed(z.enum(['active', 'suspended'])).optional(), /** * The server modules this tenant may use; empty for a new tenant. * Optional because older servers omit it. */ features: z.array(TenantFeatureSchema).optional(), createdAt: IsoDateTimeSchema, }); export type AdminTenantRecord = z.infer; export const AdminTenantUpdateRequestSchema = z.object({ /** * The tenant's whole list, replacing the one it had: `[]` turns every * module off. Each id must name a module the server has installed. */ features: z .array(TenantFeatureSchema) .max(64) .refine((features) => new Set(features.map((f) => f.id)).size === features.length, { message: 'a feature is listed once', }), }); export type AdminTenantUpdateRequest = z.infer; export const AdminTenantCreateRequestSchema = z.object({ id: z.string().regex(tenantIdPattern), /** Display name; defaults to the id. */ name: z.string().min(1).max(256).optional(), }); export type AdminTenantCreateRequest = z.infer; export const AdminTenantCreateResponseSchema = z.object({ tenant: AdminTenantRecordSchema, /** False when the tenant already existed — create is ensure-style. */ created: z.boolean(), }); export type AdminTenantCreateResponse = z.infer; export const AdminTenantResponseSchema = z.object({ tenant: AdminTenantRecordSchema, }); export type AdminTenantResponse = z.infer; export const AdminTenantListQuerySchema = z.object({ limit: z.coerce .number() .int() .min(1) .max(ADMIN_DOCUMENT_LIST_MAX_LIMIT) .default(ADMIN_DOCUMENT_LIST_DEFAULT_LIMIT), cursor: z.string().min(1).optional(), }); export type AdminTenantListQuery = z.infer; export const AdminTenantListResponseSchema = z.object({ tenants: z.array(AdminTenantRecordSchema), /** Opaque cursor for the next page; `null` on the last page. */ nextCursor: z.string().nullable(), }); export type AdminTenantListResponse = z.infer; /** * Tenant-token scopes used by the admin surface. The wildcard `*` * always satisfies a scope check and is deliberately not listed — * operations declare the *specific* scope they require. * * `tokens.issue-doc` and `tokens.revoke` are deliberately separate: * issuance leaking is a confidentiality risk (unauthorized access * creation), revocation leaking is an availability risk (mass session * kill). Different failure directions, different scopes. * * `grants.manage` covers the whole grant lifecycle with one * scope: a grant is a standing mint capability, so creating and * revoking it are the same trust decision — unlike ephemeral tokens, * where issue and revoke fail in different directions. * * The `docs.*` scopes are create, read, update and delete over the * records of the tenant's documents and folders: names, folders, sizes, * states. `docs.update` renames and moves; `docs.delete` stays separate * because its failure direction is loss. No `docs.*` scope reaches what is * inside a document. * * Everything inside a document, reading included, takes document * permissions in the doc-token vocabulary (capabilities, collab scopes, * `pdf.permissions`). A doc JWT carries them for one document; a tenant JWT * may carry them next to its tenant scopes, and then they hold for every * document of the tenant. That includes the two collection calls that hand * out content: the original file needs `doc.download`, the thumbnail * `doc.render`. `tokens.issue-doc` and `grants.manage` hand out only the * document permissions the token holds itself (`scopeNotCovered` in * engine-core): next to `doc.open` and `doc.render` they make reading * tokens and reading grants, and nothing more. */ export const adminTenantScopes = [ 'docs.create', 'docs.read', 'docs.update', 'docs.delete', 'tokens.issue-doc', 'tokens.revoke', 'grants.manage', ] as const; export type AdminTenantScope = (typeof adminTenantScopes)[number]; export const AdminTokenIssueDocRequestSchema = z.object({ kind: z.literal('doc'), /** Subject of the minted token — the end user's id in your system. */ sub: z.string().min(1).max(256), docId: z.string().regex(docIdPattern), layerName: z.string().min(1).max(256).optional(), /** * Doc capability scopes (`doc.open`, `doc.render`, …, plus the * collab grammar). Validated server-side against the engine's scope * vocabulary — an unknown string rejects the whole request. A tenant * token gives only document permissions it holds itself. */ scope: z.array(z.string().min(1).max(128)).min(1).max(64), /** * Who the token acts for: the same `Identity` the local engine takes at * open time. `displayName` becomes the author of the annotations the token * creates, `userId` and `groupId` their owner and group. */ identity: IdentityInputSchema.optional(), /** * Origin lock: web origins (scheme + host, optional port; one leading * `*.` wildcard label allowed) the minted token may be presented * from. Enforced on every engine request that carries a browser * `Origin` header — hotlink prevention, not DRM: non-browser callers * are governed by the token itself. */ origins: originPatternArray.optional(), /** Token lifetime in seconds. */ expiresInSeconds: z .number() .int() .min(60) .max(60 * 60 * 24 * 90), }); export type AdminTokenIssueDocRequest = z.infer; export const AdminTokenIssueTenantRequestSchema = z.object({ kind: z.literal('tenant'), sub: z.string().min(1).max(256), /** * Tenant scopes (`docs.read`, `tokens.issue-doc`, …, or `*`) and document * permissions in the doc-token vocabulary, which hold for every document * of the tenant. Validated server-side, as a doc token's scope is. */ scope: z.array(z.string().min(1).max(128)).min(1).max(64), /** Token lifetime in seconds. */ expiresInSeconds: z .number() .int() .min(60) .max(60 * 60 * 24 * 90), }); export type AdminTokenIssueTenantRequest = z.infer; /** The most JSON an upload token's `metadata` may hold: it rides inside the token. */ export const UPLOAD_TOKEN_METADATA_MAX_BYTES = 4096; export const AdminTokenIssueUploadRequestSchema = z.object({ kind: z.literal('upload'), /** Who is uploading: the end user's id in your system. */ sub: z.string().min(1).max(256), /** The folder every upload goes into: a folder id, or root (the default). */ folderId: FolderPlaceSchema.optional(), /** * Your own data, put on every document uploaded with the token. The * browser can't change it: init takes the token's, not the request's. */ metadata: z .record(z.string(), z.unknown()) .refine( (value) => JSON.stringify(value).length <= UPLOAD_TOKEN_METADATA_MAX_BYTES, `metadata: at most ${UPLOAD_TOKEN_METADATA_MAX_BYTES} bytes of JSON`, ) .optional(), /** How many documents the token uploads. Defaults to 1. */ maxFiles: z.number().int().min(1).max(1000).optional(), /** The largest file the token takes, in bytes. */ maxBytes: z.number().int().min(1).optional(), /** Origin lock, as on a doc token: the websites the token works on. */ origins: originPatternArray.optional(), /** Token lifetime in seconds. */ expiresInSeconds: z .number() .int() .min(60) .max(60 * 60 * 24 * 90), }); export type AdminTokenIssueUploadRequest = z.infer; export const AdminTokenIssueRequestSchema = z.discriminatedUnion('kind', [ AdminTokenIssueDocRequestSchema, AdminTokenIssueTenantRequestSchema, AdminTokenIssueUploadRequestSchema, ]); export type AdminTokenIssueRequest = z.infer; export const AdminTokenIssueResponseSchema = z.object({ token: z.string(), jti: z.string(), /** When the token expires. */ expiresAt: IsoDateTimeSchema, }); export type AdminTokenIssueResponse = z.infer; // --------------------------------------------------------------------------- // Operation registry // --------------------------------------------------------------------------- // // The registry is the admin surface's contract: one entry per operation // carrying method, path template, required tenant scope, and the request/ // response schemas. The server mounts its routes from these entries (so the // registry is executed, not merely described), and the OpenAPI document is // generated from the same entries in CI. Migration status: `documents.list` // is registered; the remaining admin operations move in as they are touched. /** * The credential kinds of the one-rule auth model: the API token * (static deployment secret) is valid everywhere; a tenant JWT is valid * exactly under its own `/v1/tenants/{tenantId}/` subtree; a doc JWT is * valid exactly on the `/v1/docs/{docId}` subtree it names, gated by * the capability scopes it carries. */ // --------------------------------------------------------------------------- // Grants // --------------------------------------------------------------------------- // // A grant is a standing, revocable authorization decision stored // with the documents: "anyone presenting this reference, from these // origins, gets exactly these capabilities on this document". The grant // id is what a page holds to open the document — it is a reference whose power // is evaluated at exchange time, never a bearer credential, which is // what lets it live in public HTML while staying editable and // revocable. The only credential it ever produces is an ordinary // short-lived doc JWT, minted downward at `grants.exchange`. /** * Whose layer a grant's visitors write into: `'shared'`, one layer everyone * reads and writes (`layerName`), or `'per-visitor'`, a layer of each * visitor's own (`visitor-`), made at their first change. */ export const GrantLayerModeSchema = closed(z.enum(['shared', 'per-visitor'])); export type GrantLayerMode = z.infer; /** Delete a visitor after this long unseen: an hour to 30 days. */ const visitorIdleSecondsSchema = z .number() .int() .min(60 * 60) .max(30 * 24 * 60 * 60); const visitorQuestionSchema = closed(z.enum(['required', 'optional'])); /** * What a grant asks its visitors, so what they add carries their name and * the owner learns who they are. The answers are stored once per visitor * and go into every session token issued for them; a visitor can't change * an answer they gave (they start over instead). `userId` is never asked: a * visitor's is `visitor_`. */ export const GrantVisitorIdentitySchema = z.object({ /** The identity fields to ask, each required or optional; at least one. */ fields: z.object({ /** Their name: the author of what they add. */ displayName: visitorQuestionSchema.optional(), email: visitorQuestionSchema.optional(), title: visitorQuestionSchema.optional(), organization: visitorQuestionSchema.optional(), organizationalUnit: visitorQuestionSchema.optional(), }), /** * `'on-open'`: before the document opens (a lead gate). `'before-first-change'`: * reading is free, and the first change asks (a review grant). */ ask: closed(z.enum(['on-open', 'before-first-change'])), /** Shown with the questions: why they're asked. */ purpose: z.string().min(1).max(500).optional(), /** The link owner's privacy notice, linked from the questions. */ privacyUrl: z.string().url().max(2048).optional(), }); export type GrantVisitorIdentity = z.infer; /** A visitor's answers, the identity fields a grant asks. */ export const GrantVisitorAnswersSchema = z.object({ displayName: z.string().max(4096).optional(), email: z.string().max(4096).optional(), title: z.string().max(4096).optional(), organization: z.string().max(4096).optional(), organizationalUnit: z.string().max(4096).optional(), }); export type GrantVisitorAnswers = z.infer; const visitorFieldSchema = closed( z.enum(['displayName', 'email', 'title', 'organization', 'organizationalUnit']), ); /** * What a visitor is still asked: the details of `VisitorIdentityRequired`, * and the exchange's `visitor.identityRequest` on a grant that asks before * the first change. */ export const GrantVisitorIdentityRequestSchema = z.object({ /** What the grant asks, each required or optional. */ fields: GrantVisitorIdentitySchema.shape.fields, /** Required fields not answered yet. */ missing: z.array(visitorFieldSchema), /** Answers given this time that can't be taken (an email that isn't one, too long). */ invalid: z.array(visitorFieldSchema), purpose: z.string().optional(), privacyUrl: z.string().optional(), }); export type GrantVisitorIdentityRequest = z.infer; export const GrantRecordSchema = z.object({ /** The grant's id (`grt_…`; older grants `shr_…`): what a link page or an embed opens. */ id: z.string(), tenantId: z.string(), docId: z.string(), /** What it's called, for example "Website" or "Sent to Acme"; null when unnamed. */ name: z.string().nullable(), layerMode: GrantLayerModeSchema, /** The layer every visitor shares; null for a per-visitor grant. */ layerName: z.string().nullable(), /** * Per-visitor grants: a visitor's browser comes back to their layer on the next visit; false * gives every visit a new visitor and a new layer. */ keepVisitorLayers: z.boolean(), /** * Delete a visitor (their answers and their layer) after this long * unseen; null keeps them until they are deleted on purpose. */ visitorIdleSeconds: z.number().int().nullable(), /** What the grant asks its visitors; null asks nothing. */ visitorIdentity: GrantVisitorIdentitySchema.nullable(), /** * Who the grant's visitors are, for a grant made for one person; null when * they are whoever they answer. It prevails over their answers. */ identity: IdentitySchema.nullable(), /** Doc capabilities the exchanged session carries. */ scope: z.array(z.string()), /** Origin allowlist; null means any origin. */ origins: z.array(z.string()).nullable(), /** True when a passphrase is required at exchange. The passphrase itself is never returned. */ passphraseProtected: z.boolean(), /** Lifetime of each exchanged session token, in seconds. */ sessionTtlSeconds: z.number().int(), /** Paused grants refuse exchange (404) but keep their configuration. */ disabled: z.boolean(), /** * When the grant was archived: it refuses exchange for good and keeps what * its visitors made. Null while it works. */ archivedAt: IsoDateTimeSchema.nullable(), /** When exchange starts returning 410; null = no expiry. */ expiresAt: IsoDateTimeSchema.nullable(), /** Total successful exchanges — a dashboard convenience, not the usage meter. */ exchangeCount: z.number().int(), lastExchangedAt: IsoDateTimeSchema.nullable(), createdBy: z.string(), createdAt: IsoDateTimeSchema, updatedAt: IsoDateTimeSchema, }); export type GrantRecord = z.infer; export const GrantCreateRequestSchema = z.object({ docId: z.string().regex(docIdPattern), /** What to call it, 1 to 100 characters after trimming. Omit or null for none. */ name: grantNameSchema.nullable().optional(), /** Default `'shared'`. */ layerMode: GrantLayerModeSchema.optional(), /** The shared layer, default `default`. Not for a per-visitor grant, and never `visitor-…`. */ layerName: z.string().min(1).max(256).optional(), /** * Per-visitor grants: a visitor's browser comes back to their layer on the next visit; false * gives every visit a new visitor and a new layer. Default true. */ keepVisitorLayers: z.boolean().optional(), /** * Delete a visitor (their answers and their layer) after this long unseen, * for grants whose visitors' work is throwaway (examples, demos). Omit or * null to keep visitors until they are deleted on purpose (the default). */ visitorIdleSeconds: visitorIdleSecondsSchema.nullable().optional(), /** Ask visitors who they are; omit or null to ask nothing. */ visitorIdentity: GrantVisitorIdentitySchema.nullable().optional(), /** * Who the grant's visitors are, for a grant made for one person: the same * `Identity` as `tokens.issue`'s. Every session the grant gives carries it, * whoever opens the grant: a field it sets is never asked, and a visitor's * answer for it is ignored, so `visitorIdentity` can't ask it too. `userId` * replaces the visitor's own (`visitor_`). Omit or null for visitors * who are whoever they answer. */ identity: IdentityInputSchema.nullable().optional(), /** * Doc capability scopes the exchanged session will carry. Validated * server-side against the engine's scope vocabulary, same as * `tokens.issue`, and as there a tenant token gives only document * permissions it holds itself. */ scope: z.array(z.string().min(1).max(128)).min(1).max(64), /** Origin allowlist; left out or `null` allows any origin, as a read says. */ origins: originPatternArray.nullable().optional(), /** Optional passphrase gate, checked at exchange. Stored as a hash; never returned. */ passphrase: z.string().min(1).max(1024).optional(), /** Lifetime of exchanged session tokens. Default 600. */ sessionTtlSeconds: z .number() .int() .min(60) .max(60 * 60) .optional(), /** When the grant stops exchanging; left out or `null` for no expiry. */ expiresAt: InstantInputSchema.nullable().optional(), }); export type GrantCreateRequest = z.infer; /** * Partial update. `origins: null` clears the allowlist (any origin), * `passphrase: null` removes the passphrase, `name: null` the name, `expiresAt: null` removes * the expiry. Absent fields stay untouched. The exchanged capabilities * and origin lock of every embedded snippet follow the row — editing a * grant retargets the copies already pasted into pages. */ export const GrantUpdateRequestSchema = z.object({ /** Renames it; null removes the name. */ name: grantNameSchema.nullable().optional(), /** * Switching to `'per-visitor'` stops visitors writing into the shared * layer (it stays); switching to `'shared'` takes `layerName`, default * `default`. The id stays the same either way. */ layerMode: GrantLayerModeSchema.optional(), /** A shared grant's layer. Not for a per-visitor grant, and never `visitor-…`. */ layerName: z.string().min(1).max(256).optional(), keepVisitorLayers: z.boolean().optional(), /** null stops deleting visitors who go unseen. */ visitorIdleSeconds: visitorIdleSecondsSchema.nullable().optional(), /** null stops asking; a change applies at each visitor's next exchange. */ visitorIdentity: GrantVisitorIdentitySchema.nullable().optional(), /** Replaces the grant's identity; null clears it. Applies at each visitor's next exchange. */ identity: IdentityInputSchema.nullable().optional(), scope: z.array(z.string().min(1).max(128)).min(1).max(64).optional(), origins: originPatternArray.nullable().optional(), passphrase: z.string().min(1).max(1024).nullable().optional(), sessionTtlSeconds: z .number() .int() .min(60) .max(60 * 60) .optional(), disabled: z.boolean().optional(), /** When the grant stops exchanging; `null` removes the expiry. */ expiresAt: InstantInputSchema.nullable().optional(), }); export type GrantUpdateRequest = z.infer; export const GrantResponseSchema = z.object({ grant: GrantRecordSchema, }); export type GrantResponse = z.infer; export const GrantListQuerySchema = z.object({ limit: z.coerce .number() .int() .min(1) .max(ADMIN_DOCUMENT_LIST_MAX_LIMIT) .default(ADMIN_DOCUMENT_LIST_DEFAULT_LIMIT), cursor: z.string().min(1).optional(), /** Filter to one document's grants. */ docId: z.string().regex(docIdPattern).optional(), /** `true` lists the archived grants instead of the ones that still work. */ archived: queryFlag.optional(), }); export type GrantListQuery = z.infer; export const GrantListResponseSchema = z.object({ grants: z.array(GrantRecordSchema), /** Opaque cursor for the next page; `null` on the last page. */ nextCursor: z.string().nullable(), }); export type GrantListResponse = z.infer; export const AdminTenantGrantParamsSchema = z.object({ tenantId: z.string().regex(tenantIdPattern), grantId: z.string().regex(grantIdPattern), }); export type AdminTenantGrantParams = z.infer; export const AdminTenantGrantVisitorParamsSchema = AdminTenantGrantParamsSchema.extend({ visitorId: z.string().regex(/^[0-9a-f]{24}$/), }); export type AdminTenantGrantVisitorParams = z.infer; /** * A grant's visitor who answered its questions or made a change: their * answers, when they agreed and were last seen, and their own layer. */ export const GrantVisitorRecordSchema = z.object({ visitorId: z.string(), /** Their answers to what the grant asked; empty for a visitor who was asked nothing. */ answers: GrantVisitorAnswersSchema, /** Whether their email was verified (not yet offered: always false). */ emailVerified: z.boolean(), /** When they gave their answers; null for one who was asked nothing. */ consentedAt: IsoDateTimeSchema.nullable(), firstSeenAt: IsoDateTimeSchema, lastSeenAt: IsoDateTimeSchema, /** Their own layer, when it holds changes (per-visitor grants). */ layer: z .object({ layerName: z.string(), sizeBytes: z.number().int().nullable(), }) .nullable(), }); export type GrantVisitorRecord = z.infer; /** Query parameters for `grants.visitors.list`, as for the other lists. */ export const GrantVisitorListQuerySchema = z.object({ limit: z.coerce .number() .int() .min(1) .max(ADMIN_DOCUMENT_LIST_MAX_LIMIT) .default(ADMIN_DOCUMENT_LIST_DEFAULT_LIMIT), cursor: z.string().min(1).optional(), }); export type GrantVisitorListQuery = z.infer; export const GrantVisitorListResponseSchema = z.object({ visitors: z.array(GrantVisitorRecordSchema), /** Opaque cursor for the next page; `null` on the last page. */ nextCursor: z.string().nullable(), }); export type GrantVisitorListResponse = z.infer; /** * The grant travels in the body, never the path — URLs land in * access logs and proxy logs. */ export const GrantExchangeRequestSchema = z.object({ grant: z.string().regex(grantIdPattern), /** Required when the grant is passphrase-protected (422 otherwise). */ passphrase: z.string().min(1).max(1024).optional(), /** * The `visitor.handle` an earlier exchange answered: the same visitor, and * on a per-visitor grant the same layer. One the grant didn't issue, or * whose layer was deleted, gets a new visitor. */ visitorHandle: z.string().min(1).max(256).optional(), /** With `visitorHandle` on a per-visitor grant: delete that visitor's layer and start a new visitor. */ restart: z.boolean().optional(), /** * The visitor's answers to what the grant asks (`visitorIdentity`). Only * the fields the grant asks and they haven't answered count: an answer once * given stays. */ visitorIdentity: GrantVisitorAnswersSchema.optional(), }); export type GrantExchangeRequest = z.infer; export const GrantSessionResponseSchema = z.object({ /** A doc-scoped session JWT carrying the grant's capabilities and origin lock. */ token: z.string(), docId: z.string(), /** The layer the session reads and writes: the shared one, or this visitor's own. */ layerName: z.string(), layerMode: GrantLayerModeSchema, /** Who the session acts as: the session token names them as the author of what they add. */ visitor: z.object({ /** Send it back with the next exchange: renewals keep the same visitor. */ handle: z.string(), /** * Keep the handle for the next visit too: the browser comes back as this visitor, with their * answers and, on a per-visitor grant, their layer. False only on a per-visitor grant that * doesn't keep visitors' layers, where every visit is a new visitor. */ keep: z.boolean(), /** * What the grant asks before this visitor's first change, when they * haven't answered it: their writes are refused (403 * `VisitorIdentityRequired`) until they exchange again with their * answers. `null` when nothing is asked. */ identityRequest: GrantVisitorIdentityRequestSchema.nullable(), }), /** When the session token expires; exchange again for a fresh one. */ expiresAt: IsoDateTimeSchema, }); export type GrantSessionResponse = z.infer; // --------------------------------------------------------------------------- // Tenant usage + suspension // --------------------------------------------------------------------------- const utcDayPattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/; export const TenantUsageQuerySchema = z.object({ /** UTC month to report, `YYYY-MM`. Defaults to the current month. */ period: z .string() .regex(/^\d{4}-(0[1-9]|1[0-2])$/) .optional(), /** * The first UTC day to report, `YYYY-MM-DD`, with `to` in place of * `period`: a billing period that starts mid-month, say. */ from: z.string().regex(utcDayPattern).optional(), /** The UTC day after the last one reported, `YYYY-MM-DD`: at most 366 days after `from`. */ to: z.string().regex(utcDayPattern).optional(), }); export type TenantUsageQuery = z.infer; /** * Per-tenant usage facts for a window of UTC days: a month, or `from` to * `to`. Deliberately opinion-free: no limits, no plans, no billing state — * those belong to whoever operates the deployment. `pdfViews` counts * grant exchanges plus authorized `/v1/access` requests, deduplicated (a * grant session that later establishes access is not counted twice). * `storageBytes` is what the tenant stores now, whatever the window. */ export const TenantUsageResponseSchema = z.object({ tenantId: z.string(), /** The first day reported, `YYYY-MM-DD`. */ periodStart: z.string(), /** The day after the last one reported, `YYYY-MM-DD`. */ periodEnd: z.string(), /** The core's meters. */ metrics: z.object({ pdfViews: z.number().int(), pdfUploads: z.number().int(), storageBytes: z.number().int(), }), /** * The modules' meters by their names (`protected-display.views`): each * installed module's, 0 when nothing counted it, and any other module meter * counted in the window. */ moduleMeters: z.record(z.string(), z.number().int()), }); export type TenantUsageResponse = z.infer; /** One of a module's permissions, as the module declares it. */ export const ModulePermissionSchema = z.object({ /** The whole permission: `protected-display.view`. */ name: z.string(), /** `document`: in viewer tokens and grants; `tenant`: in tenant tokens and API keys. */ level: closed(z.enum(['document', 'tenant'])), /** What a grant or API key dialog says for it. */ label: z.string(), description: z.string().optional(), /** * The core document permission this one is another way of doing: * protected display's `view` replaces `doc.render`. A dialog can offer * the two as a choice. A scope may hold both; the core one then has its * usual effect, and a viewer plugin uses it. */ replaces: z.string().optional(), /** * Core document permissions that let out what this one protects, like * `doc.download`. Facts for a dialog to show; the server enforces none. */ bypassedBy: z.array(z.string()).optional(), }); export type ModulePermission = z.infer; /** One of a module's meters, counted per tenant and UTC day and reported in the tenants' usage. */ export const ModuleMeterSchema = z.object({ /** The whole meter: `protected-display.views`. */ name: z.string(), /** What a usage page calls it: `Protected views`. */ label: z.string(), /** What one counts as, plural: `views`. */ unit: z.string(), description: z.string().optional(), }); export type ModuleMeter = z.infer; /** A server module this deployment has installed: what it is and what it adds, as it declares it. */ export const ModuleManifestSchema = z.object({ /** Its id, the namespace of everything it adds: `protected-display`. */ id: z.string(), /** What people call it: `Screenshot protection`. */ name: z.string(), description: z.string().optional(), permissions: z.array(ModulePermissionSchema), meters: z.array(ModuleMeterSchema), /** What it does beyond whoever calls it: the core document permissions it holds itself. */ requires: z.object({ document: z.array(z.string()) }), }); export type ModuleManifest = z.infer; export const DeploymentModulesResponseSchema = z.object({ /** In the order the server loads them. */ modules: z.array(ModuleManifestSchema), }); export type DeploymentModulesResponse = z.infer; export const TenantSuspendRequestSchema = z.object({ /** Optional operator reason, written to the security-events trail. */ reason: z.string().max(1024).optional(), }); export type TenantSuspendRequest = z.infer; export const adminCredentials = ['api-token', 'tenant-jwt', 'doc-jwt', 'upload-jwt'] as const; export type AdminCredential = (typeof adminCredentials)[number]; export type AdminOperationMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; export interface AdminOperationHeader { name: string; description: string; /** Defaults to false. */ required?: boolean; } export interface AdminOperationResponse { /** * MIME type(s) of the response body. An array means the server picks * one per response (e.g. thumbnail webp/png). Absent = empty body * (204-style). */ contentType?: string | ReadonlyArray; /** Body schema; absent for empty or binary bodies. */ schema?: z.ZodTypeAny; } /** * Every error response, whichever route and status: * `{ error: { code, message, details? } }` (`ErrorResponseSchema`). */ const errorResponse: AdminOperationResponse = { contentType: 'application/json', schema: ErrorResponseSchema, }; export interface AdminOperationBody { /** Accepted request MIME type(s). */ contentType: string | ReadonlyArray; /** Body schema; absent for binary bodies. */ schema?: z.ZodTypeAny; /** Defaults to true; false when the operation accepts an empty body. */ required?: boolean; } /** * One admin operation, fully described: everything a server needs to mount * it and everything a generator needs to document it. */ export interface AdminOperation { /** Stable `resource.verb` id; becomes the OpenAPI operationId. */ operationId: string; /** * Short display name for documentation surfaces (page titles, nav) — * a noun phrase like "Create tenant", not a sentence. Emitted as * `x-docs-title`; the API reference renders it verbatim, so naming * an operation is part of designing it. */ title: string; summary: string; method: AdminOperationMethod; /** Fastify-style path template (`:param`); rewritten to `{param}` for OpenAPI. */ path: string; /** * Credentials accepted by this operation. The API token is root and * passes every scope check. A tenant JWT reaches only its own tenant: * on the admin surfaces the path's `tenantId` must equal the token's * `tenant_id`, and on the doc plane the document must belong to it. * Doc-scoped tokens are always rejected on the admin surfaces. */ credentials: ReadonlyArray; /** * Tenant scopes accepted on the tenant-jwt path — possessing any one * grants access (`*` always does). Empty for API-token-only * operations, where no scope model applies, and for operations on what * is inside a document, which take `docCapabilities` instead. */ scope: ReadonlyArray; /** * Document permissions the operation needs, on a doc JWT and a tenant * JWT alike: doc-plane operations, and the collection operations that * hand out what is inside a document. Typed against the engine-core * vocabulary so a misspelled capability fails compile. The API token * bypasses capability checks. */ docCapabilities?: ReadonlyArray; /** Documented request headers (beyond Authorization). */ requestHeaders?: ReadonlyArray; /** Path-parameter schema, keyed by template name. */ params?: z.ZodTypeAny; /** Query-string schema. */ query?: z.ZodTypeAny; /** Request body. */ body?: AdminOperationBody; /** Success and known-error responses by HTTP status code. */ responses: Readonly>; /** * Deployment caveats a generated doc must carry — e.g. an operation * that is only mounted under a server flag. */ notes?: string; } export const adminOperations = { 'tenants.create': { operationId: 'tenants.create', title: 'Create tenant', summary: 'Create a tenant, or confirm it already exists — ensure-style, idempotent.', method: 'POST', path: adminWirePaths.tenants, credentials: ['api-token'], scope: [], body: { contentType: 'application/json', schema: AdminTenantCreateRequestSchema }, responses: { 200: { contentType: 'application/json', schema: AdminTenantCreateResponseSchema }, 400: errorResponse, }, }, 'tenants.list': { operationId: 'tenants.list', title: 'List tenants', summary: 'List tenants, newest first, cursor-paginated.', method: 'GET', path: adminWirePaths.tenants, credentials: ['api-token'], scope: [], query: AdminTenantListQuerySchema, responses: { 200: { contentType: 'application/json', schema: AdminTenantListResponseSchema }, 400: errorResponse, }, }, 'tenants.get': { operationId: 'tenants.get', title: 'Get tenant', summary: 'Fetch one tenant record.', method: 'GET', path: '/v1/tenants/:tenantId', credentials: ['api-token'], scope: [], params: AdminTenantParamsSchema, responses: { 200: { contentType: 'application/json', schema: AdminTenantResponseSchema }, 404: errorResponse, }, }, 'tenants.update': { operationId: 'tenants.update', title: 'Update tenant', summary: 'Set the server modules a tenant may use: its whole features list.', method: 'PATCH', path: '/v1/tenants/:tenantId', credentials: ['api-token'], scope: [], params: AdminTenantParamsSchema, body: { contentType: 'application/json', schema: AdminTenantUpdateRequestSchema }, responses: { 200: { contentType: 'application/json', schema: AdminTenantResponseSchema }, 400: errorResponse, 404: errorResponse, }, notes: 'A feature names an installed module; any other id is a 400. A module route answers a ' + 'tenant without its feature 403 FeatureNotEnabled, and one whose feature is stopped 402 ' + 'FeatureStopped (details.feature, details.stopped). Other replicas apply a change within ' + '30 seconds.', }, 'tenants.delete': { operationId: 'tenants.delete', title: 'Delete tenant', summary: 'Delete a tenant and everything under it.', method: 'DELETE', path: '/v1/tenants/:tenantId', credentials: ['api-token'], scope: [], params: AdminTenantParamsSchema, responses: { 204: {}, 404: errorResponse, }, notes: 'Destroys the tenant and everything in its namespace — documents, layers, stored bytes, audit history. Irreversible.', }, 'documents.init': { operationId: 'documents.init', title: 'Initialize upload', summary: 'Begin an upload: create (or resume/dedupe) a pending document and issue upload access.', method: 'POST', path: '/v1/tenants/:tenantId/documents/init', credentials: ['api-token', 'tenant-jwt', 'upload-jwt'], scope: ['docs.create'], params: AdminTenantParamsSchema, body: { contentType: 'application/json', schema: AdminDocumentInitRequestSchema }, responses: { 200: { contentType: 'application/json', schema: AdminDocumentInitResponseSchema }, 400: errorResponse, 403: errorResponse, }, notes: "With an upload token, the document goes into the token's folder with the token's metadata, whatever the request says; sizeBytes must be within the token's maxBytes, and the token makes at most maxFiles documents (403 after). docId, idempotencyKey and dedupMode reuse-existing are refused (400): each could reach a document the token didn't make.", }, 'documents.commit': { operationId: 'documents.commit', title: 'Commit upload', summary: 'Finish an upload: verify the SHA-256 and promote the document to ready.', method: 'POST', path: '/v1/tenants/:tenantId/documents/:docId/commit', credentials: ['api-token', 'tenant-jwt', 'upload-jwt'], scope: ['docs.create'], params: AdminTenantDocParamsSchema, body: { contentType: 'application/json', schema: AdminDocumentCommitRequestSchema }, responses: { 200: { contentType: 'application/json', schema: AdminDocumentCommitResponseSchema }, 400: errorResponse, 404: errorResponse, }, notes: 'An upload token commits only the documents it started; any other document answers 404.', }, 'documents.uploadProxy': { operationId: 'documents.uploadProxy', title: 'Upload document through the origin', summary: 'Upload a bounded PDF through the API when the initialized transfer kind is proxy.', method: 'POST', path: '/v1/tenants/:tenantId/documents/:docId/upload-proxy', credentials: ['api-token', 'tenant-jwt', 'upload-jwt'], scope: ['docs.create'], params: AdminTenantDocParamsSchema, body: { contentType: 'multipart/form-data', }, responses: { 200: { contentType: 'application/json', schema: AdminUploadProxyResponseSchema }, 400: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: 'This bounded origin-mediated fallback must only be used after documents.init returns upload.kind=proxy. Auto mode prefers a presigned object-store PUT whenever available. An upload token sends files only to the documents it started.', }, 'documents.importFrom': { operationId: 'documents.importFrom', title: 'Import document', summary: 'Server-side pull: fetch a PDF from a caller-supplied URL (e.g. a presigned object-store GET) or an operator-registered storage connection into CloudPDF-owned storage, verify it, and commit it.', method: 'POST', path: '/v1/tenants/:tenantId/documents/import', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.create'], params: AdminTenantParamsSchema, body: { contentType: 'application/json', schema: AdminDocumentImportRequestSchema }, responses: { 200: { contentType: 'application/json', schema: AdminDocumentImportResponseSchema }, 202: { contentType: 'application/json', schema: AdminDocumentImportResponseSchema }, 400: errorResponse, 403: errorResponse, 502: errorResponse, }, notes: 'Default mode is synchronous and bounded: the response returns only after the transfer verified and committed (or failed). mode=async (connection sources only) answers 202 immediately and an in-process worker performs the transfer with leased, fenced retries; poll the document until ready/failed. The deployment import policy gates scheme, network range, and size; sources must declare a length. CloudPDF copies and owns the bytes — the source is never referenced in place. A 502 marks a retryable upstream failure: retry with the same idempotencyKey to resume the same document. URL sources are capabilities and never echoed back. Connection sources name operator-registered storage (bucket/prefix scope, allowed credential classes, and tenant bindings are deployment configuration); `revision` is provider-interpreted (S3 VersionId, GCS generation, Azure version id).', }, 'documents.list': { operationId: 'documents.list', title: 'List documents', summary: 'List documents in the tenant, cursor-paginated: newest first by default, or searched by name and sorted by name or size.', method: 'GET', path: '/v1/tenants/:tenantId/documents', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.read'], params: AdminTenantParamsSchema, query: AdminDocumentListQuerySchema, responses: { 200: { contentType: 'application/json', schema: AdminDocumentListResponseSchema }, 400: errorResponse, }, }, 'documents.get': { operationId: 'documents.get', title: 'Get document', summary: 'Fetch one document record.', method: 'GET', path: '/v1/tenants/:tenantId/documents/:docId', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.read'], params: AdminTenantDocParamsSchema, responses: { 200: { contentType: 'application/json', schema: AdminDocumentResponseSchema }, 403: errorResponse, 404: errorResponse, }, }, 'documents.update': { operationId: 'documents.update', title: 'Update document', summary: 'Rename a document.', method: 'PATCH', path: '/v1/tenants/:tenantId/documents/:docId', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.update'], params: AdminTenantDocParamsSchema, body: { contentType: 'application/json', schema: AdminDocumentUpdateRequestSchema }, responses: { 200: { contentType: 'application/json', schema: AdminDocumentResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, }, notes: 'A document that is being deleted answers 404.', }, 'documents.download': { operationId: 'documents.download', title: 'Download document', summary: 'Download the stored base PDF bytes.', method: 'GET', path: '/v1/tenants/:tenantId/documents/:docId/download', credentials: ['api-token', 'tenant-jwt'], scope: [], docCapabilities: ['doc.download'], params: AdminTenantDocParamsSchema, responses: { 200: { contentType: 'application/pdf' }, 403: errorResponse, 404: errorResponse, }, }, 'documents.delete': { operationId: 'documents.delete', title: 'Delete document', summary: 'Delete a document and its stored artifacts.', method: 'DELETE', path: '/v1/tenants/:tenantId/documents/:docId', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.delete'], params: AdminTenantDocParamsSchema, responses: { 204: {}, 403: errorResponse, 404: errorResponse, }, }, 'documents.layers.list': { operationId: 'documents.layers.list', title: 'List layers', summary: "A document's layers that hold changes, newest first, cursor-paginated: the ones grants and your tokens name, and each grant visitor's own.", method: 'GET', path: '/v1/tenants/:tenantId/documents/:docId/layers', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.read'], params: AdminTenantDocParamsSchema, query: AdminDocumentLayerListQuerySchema, responses: { 200: { contentType: 'application/json', schema: AdminDocumentLayerListResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, }, }, 'documents.layers.delete': { operationId: 'documents.layers.delete', title: 'Delete layer', summary: "Delete a layer and everything it stored. A layer that was written can't be used again under its name; one nobody wrote stays usable.", method: 'DELETE', path: '/v1/tenants/:tenantId/documents/:docId/layers/:layerName', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.delete'], params: AdminTenantDocLayerParamsSchema, responses: { 204: {}, 403: errorResponse, 404: errorResponse, 409: errorResponse, }, }, 'documents.thumbnail': { operationId: 'documents.thumbnail', title: 'Get thumbnail', summary: 'Fetch the warmed dashboard-tile render for a document.', method: 'GET', path: '/v1/tenants/:tenantId/documents/:docId/thumbnail', credentials: ['api-token', 'tenant-jwt'], scope: [], docCapabilities: ['doc.render'], params: AdminTenantDocParamsSchema, responses: { 200: { contentType: ['image/webp', 'image/png'] }, 404: errorResponse, }, }, 'folders.create': { operationId: 'folders.create', title: 'Create folder', summary: 'Create a folder at the top level or inside another folder.', method: 'POST', path: '/v1/tenants/:tenantId/folders', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.create'], params: AdminTenantParamsSchema, body: { contentType: 'application/json', schema: FolderCreateRequestSchema }, responses: { 200: { contentType: 'application/json', schema: FolderResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: '409 Conflict carries `details.reason`: `name-taken` (a sibling has the name, ignoring case; `details.name`) or `too-deep` (folders nest at most 100 levels; `details.maxDepth`). 404 when the parent folder does not exist.', }, 'folders.list': { operationId: 'folders.list', title: 'List folders', summary: 'List folders by name, cursor-paginated: every folder, or those directly in one folder.', method: 'GET', path: '/v1/tenants/:tenantId/folders', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.read'], params: AdminTenantParamsSchema, query: FolderListQuerySchema, responses: { 200: { contentType: 'application/json', schema: FolderListResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, }, }, 'folders.get': { operationId: 'folders.get', title: 'Get folder', summary: 'Fetch one folder and the folders above it.', method: 'GET', path: '/v1/tenants/:tenantId/folders/:folderId', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.read'], params: AdminTenantFolderParamsSchema, responses: { 200: { contentType: 'application/json', schema: FolderGetResponseSchema }, 403: errorResponse, 404: errorResponse, }, }, 'folders.update': { operationId: 'folders.update', title: 'Update folder', summary: 'Rename a folder.', method: 'PATCH', path: '/v1/tenants/:tenantId/folders/:folderId', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.update'], params: AdminTenantFolderParamsSchema, body: { contentType: 'application/json', schema: FolderUpdateRequestSchema }, responses: { 200: { contentType: 'application/json', schema: FolderResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: '409 Conflict with `details.reason` `name-taken` when a sibling has the name, ignoring case.', }, 'folders.moveInto': { operationId: 'folders.moveInto', title: 'Move into folder', summary: 'Move documents and folders into a folder, or to the top level with root. All of them move, or none do.', method: 'POST', path: '/v1/tenants/:tenantId/folders/:folderId/move-into', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.update'], params: AdminTenantFolderPlaceParamsSchema, body: { contentType: 'application/json', schema: FolderMoveIntoRequestSchema }, responses: { 204: {}, 400: errorResponse, 403: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: "Up to 1,000 ids in total. A folder moves with everything in it. 404 NotFound names the ids that do not exist or are being deleted in `details.docIds` and `details.folderIds`. 409 Conflict carries `details.reason`: `cycle` (the destination is a moved folder or inside one; `details.folderId`), `too-deep` (the move would nest folders deeper than 100 levels; `details.maxDepth`) or `name-taken` (a moved folder's name is taken in the destination, ignoring case; `details.name`).", }, 'folders.delete': { operationId: 'folders.delete', title: 'Delete folder', summary: 'Delete an empty folder, or with recursive=true a folder and everything in it.', method: 'DELETE', path: '/v1/tenants/:tenantId/folders/:folderId', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.delete'], params: AdminTenantFolderParamsSchema, query: FolderDeleteQuerySchema, responses: { 204: {}, 403: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: 'Without recursive, a folder with anything inside is refused: 409 Conflict with `details.reason` `not-empty` and what it holds, counted over every level below, in `details.folders` and `details.documents`. With recursive=true, the folder and every folder under it go at once, and every document in them stops opening, leaves every list and stops answering its grants at once; their stored files and grants are removed in the background. Uploads into those folders that have not committed cannot commit.', }, 'deployment.licenseStatus': { operationId: 'deployment.licenseStatus', title: 'License status', summary: 'License decision plus usage-reporting and meter snapshots for this deployment.', method: 'GET', path: adminWirePaths.deploymentLicenseStatus, credentials: ['api-token'], scope: [], responses: { 200: { contentType: 'application/json', schema: AdminLicenseStatusResponseSchema }, }, }, 'deployment.modules': { operationId: 'deployment.modules', title: 'Installed modules', summary: "The server modules this deployment has installed: each one's name, permissions and meters.", method: 'GET', path: adminWirePaths.deploymentModules, credentials: ['api-token'], scope: [], responses: { 200: { contentType: 'application/json', schema: DeploymentModulesResponseSchema }, }, notes: 'What each module declares, for a dashboard or a script that lists modules, offers their ' + 'permissions in its dialogs and shows their meters. Which tenants may use one is in ' + "their `features` (`tenants.get`); what it costs, if anything, is the operator's.", }, 'tokens.issue': { operationId: 'tokens.issue', title: 'Issue token', summary: 'Mint a delegated JWT: a doc token, an upload token for a browser, or (API token only) a tenant token.', method: 'POST', path: '/v1/tenants/:tenantId/tokens', credentials: ['api-token', 'tenant-jwt'], scope: ['tokens.issue-doc'], params: AdminTenantParamsSchema, body: { contentType: 'application/json', schema: AdminTokenIssueRequestSchema }, responses: { 200: { contentType: 'application/json', schema: AdminTokenIssueResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, }, notes: 'Authority mints only downward: kind "doc" gives only document permissions the caller holds itself, kind "tenant" requires the API token, and kind "upload" requires docs.create instead of tokens.issue-doc, since an upload token can do only what docs.create allows. Mounted only when the deployment can sign (HS256 mode); asymmetric deployments mint with their own private key.', }, 'tokens.revoke': { operationId: 'tokens.revoke', title: 'Revoke token', summary: 'Revoke a token by jti; live sessions drop on their next heartbeat.', method: 'POST', path: '/v1/tenants/:tenantId/tokens/:jti/revoke', credentials: ['api-token', 'tenant-jwt'], scope: ['tokens.revoke'], params: AdminTenantJtiParamsSchema, body: { contentType: 'application/json', schema: AdminTokenRevokeRequestSchema, required: false, }, responses: { 204: {}, 400: errorResponse, }, notes: 'Mounted only when the deployment enables token revocation.', }, 'tenants.usage': { operationId: 'tenants.usage', title: 'Tenant usage', summary: 'Per-tenant usage facts (views, uploads, stored bytes) for one UTC month.', method: 'GET', path: '/v1/tenants/:tenantId/usage', credentials: ['api-token', 'tenant-jwt'], scope: ['docs.read'], params: AdminTenantParamsSchema, query: TenantUsageQuerySchema, responses: { 200: { contentType: 'application/json', schema: TenantUsageResponseSchema }, 400: errorResponse, 404: errorResponse, }, notes: 'Facts only — no limits or billing state. Views count grant exchanges plus authorized ' + '/v1/access requests, deduplicated across the two.', }, 'tenants.suspend': { operationId: 'tenants.suspend', title: 'Suspend tenant', summary: 'Fail the tenant closed: refuse every tenant JWT, doc JWT, and grant exchange.', method: 'POST', path: '/v1/tenants/:tenantId/suspend', credentials: ['api-token'], scope: [], params: AdminTenantParamsSchema, body: { contentType: 'application/json', schema: TenantSuspendRequestSchema, required: false, }, responses: { 204: {}, 404: errorResponse, }, notes: 'Instantly reversible with resume. The API token is exempt, so a suspended tenant can ' + 'still be inspected, exported, resumed, or deleted.', }, 'tenants.resume': { operationId: 'tenants.resume', title: 'Resume tenant', summary: 'Lift a suspension; credentials for the tenant verify again.', method: 'POST', path: '/v1/tenants/:tenantId/resume', credentials: ['api-token'], scope: [], params: AdminTenantParamsSchema, responses: { 204: {}, 404: errorResponse, }, }, 'grants.create': { operationId: 'grants.create', title: 'Create grant', summary: 'Create a standing grant for one document — the no-backend embed credential.', method: 'POST', path: '/v1/tenants/:tenantId/grants', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantParamsSchema, body: { contentType: 'application/json', schema: GrantCreateRequestSchema }, responses: { 200: { contentType: 'application/json', schema: GrantResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, }, notes: 'The returned id is what a link page or an embed opens. Its scope gives only document ' + 'permissions the caller holds itself, as tokens.issue does. Mounted only when the deployment can ' + 'sign (HS256 mode) — exchange mints session JWTs, so grants exist only where minting does.', }, 'grants.list': { operationId: 'grants.list', title: 'List grants', summary: 'List grants in the tenant, newest first, cursor-paginated.', method: 'GET', path: '/v1/tenants/:tenantId/grants', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantParamsSchema, query: GrantListQuerySchema, responses: { 200: { contentType: 'application/json', schema: GrantListResponseSchema }, 400: errorResponse, }, }, 'grants.get': { operationId: 'grants.get', title: 'Get grant', summary: 'Fetch one grant.', method: 'GET', path: '/v1/tenants/:tenantId/grants/:grantId', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantGrantParamsSchema, responses: { 200: { contentType: 'application/json', schema: GrantResponseSchema }, 404: errorResponse, }, }, 'grants.update': { operationId: 'grants.update', title: 'Update grant', summary: 'Edit a grant in place — every link and embed of it follows.', method: 'PATCH', path: '/v1/tenants/:tenantId/grants/:grantId', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantGrantParamsSchema, body: { contentType: 'application/json', schema: GrantUpdateRequestSchema }, responses: { 200: { contentType: 'application/json', schema: GrantResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, 409: errorResponse, }, }, 'grants.archive': { operationId: 'grants.archive', title: 'Archive grant', summary: "End a grant for good and keep what its visitors made: exchange stops immediately, live sessions lapse at their exp, and its visitors' layers stay listed.", method: 'POST', path: '/v1/tenants/:tenantId/grants/:grantId/archive', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantGrantParamsSchema, responses: { 200: { contentType: 'application/json', schema: GrantResponseSchema }, 404: errorResponse, }, notes: 'Archiving is final: an archived grant never exchanges again, and to give access again you create a new grant. Pausing (`disabled`) is the reversible stop. An archived grant no longer counts as using its shared layer, so that layer can be deleted.', }, 'grants.visitors.list': { operationId: 'grants.visitors.list', title: 'List visitors', summary: "A grant's visitors who answered its questions or made a change, newest first, cursor-paginated: their answers and their layer.", method: 'GET', path: '/v1/tenants/:tenantId/grants/:grantId/visitors', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantGrantParamsSchema, query: GrantVisitorListQuerySchema, responses: { 200: { contentType: 'application/json', schema: GrantVisitorListResponseSchema }, 400: errorResponse, 404: errorResponse, }, notes: "An archived grant's visitors are listed too.", }, 'grants.visitors.delete': { operationId: 'grants.visitors.delete', title: 'Delete visitor', summary: "Erase a grant's visitor: their answers and their own layer.", method: 'DELETE', path: '/v1/tenants/:tenantId/grants/:grantId/visitors/:visitorId', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantGrantVisitorParamsSchema, responses: { 204: {}, 404: errorResponse, }, notes: 'Their handle brings them back as a new visitor, who is asked again. Deleting a visitor already deleted changes nothing.', }, 'grants.delete': { operationId: 'grants.delete', title: 'Delete grant', summary: 'Delete a grant that has no visitors; exchange stops immediately, live sessions lapse at their exp. A grant whose visitors answered its questions or have layers is archived instead (409).', method: 'DELETE', path: '/v1/tenants/:tenantId/grants/:grantId', credentials: ['api-token', 'tenant-jwt'], scope: ['grants.manage'], params: AdminTenantGrantParamsSchema, responses: { 204: {}, 404: errorResponse, 409: errorResponse, }, }, 'grants.exchange': { operationId: 'grants.exchange', title: 'Exchange grant', summary: 'Trade a grant for a short-lived document session JWT.', method: 'POST', path: adminWirePaths.grantSessions, credentials: [], scope: [], body: { contentType: 'application/json', schema: GrantExchangeRequestSchema }, responses: { 200: { contentType: 'application/json', schema: GrantSessionResponseSchema }, 400: errorResponse, 403: errorResponse, 404: errorResponse, 410: errorResponse, 422: errorResponse, }, notes: 'Unauthenticated, but requires a browser Origin header, checked against the grant ' + 'allowlist. Unknown, deleted, paused and archived grants are indistinguishable (404). ' + 'Passphrase-protected grants return 422 GrantPassphraseRequired until `passphrase` is ' + 'supplied. A grant that asks its visitors who they are on open returns 422 ' + 'VisitorIdentityRequired until the required answers are given; `error.details` carries ' + '`fields` (what the grant asks), `missing`, `invalid`, `purpose` and `privacyUrl`. A grant ' + 'that asks before the first change issues the session at once with ' + '`visitor.identityRequest`, and writes answer 403 VisitorIdentityRequired with the same ' + 'details until the visitor exchanges again with their answers. Answers that can not be ' + 'taken answer 422 on any grant. Mounted only when the deployment can sign (HS256 mode).', }, } as const satisfies Record; export type AdminOperationId = keyof typeof adminOperations; // --------------------------------------------------------------------------- // Doc-plane operations (the backend-usable document API) // --------------------------------------------------------------------------- // // The "API vs protocol" split: these are the document operations a backend // can genuinely call — plain origin paths, credentialed by the API token // (which the server resolves to the document's own tenant), or a tenant // JWT or doc JWT carrying the listed capabilities, a tenant JWT on its own // tenant's documents. Browsers only ever get doc JWTs. The viewer-session // protocol — /v1/access, /v1/warm, the immutable `@{version}` CDN // variants, SSE, password sessions — deliberately stays out of this // registry: it is the transport between the CloudPDF viewer SDK and the // engine, free to evolve behind the SDK boundary. Body/response schemas // start deliberately loose (documented paths, params, credentials, // capabilities) and tighten incrementally as the wire shapes are ported // from engine-core. export const DocIdParamsSchema = z.object({ docId: z.string().regex(docIdPattern), }); export const DocLayerParamsSchema = DocIdParamsSchema.extend({ layerName: z.string().min(1), }); export const DownloadLinkRequestSchema = z.object({ /** Seconds the link works for: 60 to 3600, default 300. */ expiresInSeconds: z .number() .int() .min(60) .max(60 * 60) .optional(), }); export type DownloadLinkRequest = z.infer; export const DownloadLinkResponseSchema = z.object({ /** * Downloads the layer's PDF as it is now, saved incrementally, with a * plain GET and no Authorization header. Use it as given. */ url: z.string(), /** When the link stops working. */ expiresAt: IsoDateTimeSchema, }); export type DownloadLinkResponse = z.infer; export const DocPageParamsSchema = DocLayerParamsSchema.extend({ pageKey: z .string() .min(1) .regex(/^obj:[1-9][0-9]*$/) .describe( "The page's address, `obj:N`: the page's indirect object number, the durable identity every `PageLayout.ref` carries. Mirrors `annotationKey` and `fieldKey`.", ), }); export const DocAnnotationParamsSchema = DocPageParamsSchema.extend({ annotationKey: z .string() .min(1) .regex(/^(obj:[1-9][0-9]*|base:(0|[1-9][0-9]*))$/) .describe( "The annotation's address on the page: `obj:N`, its indirect object number, or `base:N` for an annotation the uploaded file stored inline (without an object number of its own), the position it was born at in the page's /Annots. The name the annotation's `ref` carries for life.", ), }); export const DocFieldParamsSchema = DocLayerParamsSchema.extend({ fieldKey: z.string().min(1), }); export const DocAttachmentParamsSchema = DocLayerParamsSchema.extend({ fileKey: z .string() .min(1) .describe( "The embedded file's name-tree key (its `ref.key`), token-text encoded, as `fieldKey` is.", ), }); /** * Attached to every doc-plane operation: per-request password supply for * encrypted documents, API-token callers only. Viewer JWTs never send * passwords in headers — they use the SDK's password-session flow. */ export const documentPasswordHeader: AdminOperationHeader = { name: 'X-Document-Password', required: false, description: 'Base64-encoded password for an encrypted document. Valid only with the API token ' + '(403 anywhere else). An encrypted document answers 422 DocPasswordRequired when ' + 'the header is absent. Viewer doc JWTs use the SDK password-session flow instead.', }; /** The header that makes a layer write safe to retry. */ export const idempotencyKeyHeader: AdminOperationHeader = { name: 'Idempotency-Key', required: false, description: 'Names the change: 1 to 255 printable ASCII characters. A retry under the same key on ' + 'the same layer answers with what the first request committed, and changes nothing.', }; const looseJson = z.record(z.string(), z.unknown()); const docCredentials = ['api-token', 'tenant-jwt', 'doc-jwt'] as const; /** A font program, by the hash of the file a browser loads. */ export const DocFontProgramParamsSchema = DocLayerParamsSchema.extend({ displaySha256: z.string().regex(sha256Hex), }); export const DocSigningParamsSchema = DocLayerParamsSchema.extend({ signingId: z.string().min(1), }); const sha256Pattern = /^[0-9a-f]{64}$/; export const DocVersionParamsSchema = DocLayerParamsSchema.extend({ sha256: z.string().regex(sha256Pattern), }); export const DocVersionFieldParamsSchema = DocVersionParamsSchema.extend({ fieldKey: z.string().min(1), }); export const DocVersionDigestParamsSchema = DocVersionFieldParamsSchema.extend({ algorithm: z.enum(['sha1', 'sha256', 'sha384', 'sha512']), }); export const DocVersionRevisionParamsSchema = DocVersionParamsSchema.extend({ index: z.coerce.number().int().min(0), }); /** The flat analysis query: exactly one `since.*`; `level` only in exploratory mode. */ export const LayerSignaturesAnalysisQuerySchema = z.object({ 'since.signature': z.coerce.number().int().min(0).optional(), 'since.revision': z.coerce.number().int().min(0).optional(), level: z.enum(['none', 'lta', 'fill', 'annotate']).optional(), }); export const VersionSignaturesQuerySchema = z.object({ engine: z .string() .describe( "The `signatures` engine value from the layer's head (`engine.signatures`): what the answer is computed with besides the file. With it, the answer is cached.", ) .optional(), }); export const VersionAnalysisQuerySchema = LayerSignaturesAnalysisQuerySchema.extend({ until: z.coerce.number().int().min(0).optional(), engine: z .string() .describe( "The `analysis` engine value from the layer's head (`engine.analysis`): the rules the answer is judged with. With it, a settled answer is cached.", ) .optional(), }); export const docOperations = { 'doc.head': { operationId: 'doc.head', title: 'Open document', summary: 'Open a document and return its head (versions, page count, security).', method: 'GET', path: wireTemplates.docHead, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocIdParamsSchema, responses: { 200: { contentType: 'application/json', schema: DocumentHeadSchema }, 404: errorResponse, }, }, 'doc.manifest': { operationId: 'doc.manifest', title: 'Get manifest', summary: "Full layer manifest at the layer's current version.", method: 'GET', path: wireTemplates.layerManifest, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: DocumentManifestSchema }, 404: errorResponse, }, }, 'doc.metadata.get': { operationId: 'doc.metadata.get', title: 'Get metadata', summary: 'Document metadata (PDF info dictionary view) for a layer.', method: 'GET', path: wireTemplates.layerMetadata, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: DocumentMetadataSchema }, 404: errorResponse, }, }, 'doc.metadata.custom.get': { operationId: 'doc.metadata.custom.get', title: 'Get custom keys', summary: "The Info dictionary's own keys for a layer: every key but the standard fields, as { key: value }.", method: 'GET', path: wireTemplates.layerCustomMetadata, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: CustomMetadataSchema }, 404: errorResponse, }, }, 'doc.outline.get': { operationId: 'doc.outline.get', title: 'Get outline', summary: "The document's outline (its bookmarks) for a layer: every item, depth first, with its parent, its target in page space, its look and whether it opens. Edit it with the outline ops of a change.", method: 'GET', path: wireTemplates.layerOutline, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: DocumentOutlineSchema }, 404: errorResponse, }, }, 'doc.attachments.list': { operationId: 'doc.attachments.list', title: 'List attachments', summary: 'The files embedded in the document (its /EmbeddedFiles) for a layer, in key order: each with its name, type, description, size, checksum and dates, never its bytes. Add and remove them with the attachment ops of a change.', method: 'GET', path: wireTemplates.layerAttachments, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: AttachmentListSchema }, 404: errorResponse, }, notes: "A file-attachment annotation's file is listed with the annotation; read its bytes with `doc.annotations.readFile`.", }, 'doc.attachments.download': { operationId: 'doc.attachments.download', title: 'Download an attachment', summary: "One embedded file's bytes, decoded. Its name and type are what the listing says; `Content-Type` is its type, or `application/octet-stream` when it has none.", method: 'GET', path: wireTemplates.layerAttachmentFile, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocAttachmentParamsSchema, responses: { 200: { contentType: 'application/octet-stream' }, 400: errorResponse, 404: errorResponse, 413: errorResponse, }, notes: "A file that decodes past the server's limit is refused (PayloadTooLarge).", }, 'doc.fonts.list': { operationId: 'doc.fonts.list', title: 'List fonts', summary: "Every font text can be written in, in a layer: the standard fonts, the server's, and the document's own, each with whether new text can be written in it and why not, and its font files.", method: 'GET', path: wireTemplates.layerFonts, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: FontListSchema }, 404: errorResponse, }, }, 'doc.fonts.resolve': { operationId: 'doc.fonts.resolve', title: 'Resolve fonts', summary: 'The fonts a write would draw each run of text in, found the way the write finds them, without writing: what an editor shows while someone types.', method: 'POST', path: wireTemplates.layerFontsResolve, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: FontResolveRequestSchema }, responses: { 200: { contentType: 'application/json', schema: FontResolutionSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.fonts.programs.get': { operationId: 'doc.fonts.programs.get', title: 'Get font program', summary: "A font file's facts, by the hash of the file a browser loads: the characters the engine can write with it and its line metrics.", method: 'GET', path: wireTemplates.layerFontProgram, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocFontProgramParamsSchema, responses: { 200: { contentType: 'application/json', schema: FontProgramInfoSchema }, 404: errorResponse, }, }, 'doc.fonts.programs.download': { operationId: 'doc.fonts.programs.download', title: 'Download font program', summary: 'A font file a browser can load, by its hash: to show text being typed in the font the engine writes it with.', method: 'GET', path: wireTemplates.layerFontProgramFile, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.modify', 'doc.forms.fill', 'doc.forms.modify', 'doc.redact'], requestHeaders: [documentPasswordHeader], params: DocFontProgramParamsSchema, responses: { 200: { contentType: 'font/sfnt' }, 403: errorResponse, 404: errorResponse, }, notes: 'A document token needs any one of the listed capabilities: one that may write text in the document. ' + "A file the list says can't be downloaded (`canDownload: false`) is not found.", }, 'doc.signatures.list': { operationId: 'doc.signatures.list', title: 'List signatures', summary: 'The layer view of digital signatures: revisions, every signature field with its signed state, and the protection in force.', method: 'GET', path: wireTemplates.layerSignatures, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: SignatureSnapshotSchema }, 404: errorResponse, }, notes: "Describes the bytes the layer is over: the base version's signatures plus the layer's own edits as the last revision. " + 'Signed bytes (contents, digests, revision prefixes) are served per base version under /versions.', }, 'doc.signatures.analysis': { operationId: 'doc.signatures.analysis', title: 'Analyze layer changes', summary: 'What the layer changed after a signature (or after any revision), judged against the restrictions in force.', method: 'GET', path: wireTemplates.layerSignaturesAnalysis, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, query: LayerSignaturesAnalysisQuerySchema, responses: { 200: { contentType: 'application/json', schema: ChangeAnalysisSchema }, 400: errorResponse, 404: errorResponse, }, notes: "Exactly one of `since.signature=` or `since.revision=`; the layer's pending edits are the end. " + '`level=fill|annotate|lta|none` evaluates exploratorily and never becomes a verdict. ' + 'For history between two base revisions use the version analysis.', }, 'doc.signatures.validationInfo': { operationId: 'doc.signatures.validationInfo', title: 'Read validation data', summary: "The certificates, OCSP responses and CRLs the layer's file holds for checking its signatures with no network.", method: 'GET', path: wireTemplates.layerSignaturesValidationInfo, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: ValidationInfoWireSchema }, 404: errorResponse, }, notes: 'Each entry is one DER object, base64. It reads the layer as it is now, so entries stored and not yet sealed by a signature are among them. ' + 'Arrived in 3.3.', }, 'doc.signatures.addValidationInfo': { operationId: 'doc.signatures.addValidationInfo', title: 'Store validation data', summary: "Store certificates, OCSP responses and CRLs in the layer's file, so its signatures can be checked with no network.", method: 'POST', path: wireTemplates.layerSignaturesValidationInfo, credentials: docCredentials, scope: [], docCapabilities: ['doc.sign'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: ValidationInfoAddBodySchema }, responses: { 200: { contentType: 'application/json', schema: ValidationInfoAddResultSchema }, 400: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: 'Each entry is one DER object of at most 16 MiB, base64. An entry the file already holds, byte for byte, is not stored again: `added` counts the new ones. ' + 'An entry that is not one DER object fails the request and nothing is stored; the error names it, as in `certificates[1]`. ' + 'The server stores what it is given and asks no certificate authority: collect the answers first. ' + 'It needs `doc.sign` for the document, not for a group of fields, and is refused after a certification that allows no changes. ' + 'It cannot be undone, and it leaves undo for earlier changes as it was. Arrived in 3.3.', }, 'doc.signatures.prepare': { operationId: 'doc.signatures.prepare', title: 'Prepare a signature', summary: 'Author and seal a signing candidate; returns the digest to sign and the version fences.', method: 'POST', path: wireTemplates.layerSignaturesPrepare, credentials: docCredentials, scope: [], docCapabilities: ['doc.sign'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, body: { contentType: 'multipart/form-data' }, responses: { 200: { contentType: 'application/json', schema: SignaturePreparedWireSchema }, 400: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: 'Multipart: a JSON `body` part (field, subFilter, digest, contentsSize, signer, certify, lock), naming the appearance ' + "PDF it may carry as `resources: { appearance: '' }`, and that PDF as the part `resource:`. A certification (`certify.permission`) " + 'additionally requires `doc.sign.certify`. The layer is read-only until the signing completes, is cancelled, or expires (15 minutes). ' + "A document timestamp (`kind: 'timestamp'`) may leave `field` out, since 3.3: the engine then makes a field of no size for it, " + 'under a name no other field has, and the answer names it in `field`. That needs `doc.sign` for the document. ' + "The signature is made over the layer's own base: the upload, or the version its last signature made.", }, 'doc.signatures.complete': { operationId: 'doc.signatures.complete', title: 'Complete a signature', summary: "Install the CMS into the prepared candidate and publish the sealed bytes as the document's next base version.", method: 'POST', path: wireTemplates.layerSignatureComplete, credentials: docCredentials, scope: [], docCapabilities: ['doc.sign'], requestHeaders: [documentPasswordHeader], params: DocSigningParamsSchema, body: { contentType: 'application/json', schema: SignatureCompleteBodySchema }, responses: { 200: { contentType: 'application/json', schema: SignatureCompleteResultSchema }, 400: errorResponse, 404: errorResponse, 409: errorResponse, }, notes: '`cms` is the detached CMS over the prepared digest, base64. `expectedVersion` must be what prepare returned. ' + "Idempotent by signing id: the same CMS again answers `already-completed`. The new version is the layer's own: only this layer moves " + 'to it, and the document and every other layer stay as they were. Refetch the manifest after a completion.', }, 'doc.signatures.cancel': { operationId: 'doc.signatures.cancel', title: 'Cancel a signature', summary: 'Discard a pending signing candidate.', method: 'DELETE', path: wireTemplates.layerSignatureCancel, credentials: docCredentials, scope: [], docCapabilities: ['doc.sign'], requestHeaders: [documentPasswordHeader], params: DocSigningParamsSchema, responses: { 200: { contentType: 'application/json', schema: SignatureCancelResultSchema }, 404: errorResponse, }, }, 'doc.versions.list': { operationId: 'doc.versions.list', title: 'List versions', summary: "A layer's versions, oldest first: the upload, then the ones its signatures made; and its base.", method: 'GET', path: wireTemplates.layerVersions, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: LayerVersionsSchema }, 404: errorResponse, }, notes: "Every completed signature makes a new version of its layer; another layer's versions are never listed. " + 'Never cached: the list grows.', }, 'doc.versions.signatures': { operationId: 'doc.versions.signatures', title: 'Version signatures', summary: "The signature snapshot of one of a layer's versions.", method: 'GET', path: wireTemplates.layerVersionSignatures, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocVersionParamsSchema, query: VersionSignaturesQuerySchema, responses: { 200: { contentType: 'application/json', schema: SignatureSnapshotSchema }, 400: errorResponse, 404: errorResponse, }, notes: 'A version never changes, but what the server reads from it can: ' + "with `engine`, the `signatures` value of the layer's head, the answer is `immutable`. " + "Without it, or with another value, the answer is this server's own, with `no-store` and " + 'the current value in `EmbedPDF-Engine`.', }, 'doc.versions.signatureContents': { operationId: 'doc.versions.signatureContents', title: 'Signature contents', summary: "The DER /Contents of a signed field in one of a layer's versions (immutable).", method: 'GET', path: wireTemplates.layerVersionSignatureContents, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocVersionFieldParamsSchema, responses: { 200: { contentType: 'application/pkcs7-signature' }, 404: errorResponse, }, notes: "`fieldKey` is the field's fully qualified name, token-text encoded (the same encoding attachment keys use).", }, 'doc.versions.signatureDigest': { operationId: 'doc.versions.signatureDigest', title: 'Signature digest', summary: "The digest of a signed field's /ByteRange in one of a layer's versions (immutable).", method: 'GET', path: wireTemplates.layerVersionSignatureDigest, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocVersionDigestParamsSchema, responses: { 200: { contentType: 'application/octet-stream' }, 404: errorResponse, }, notes: 'What a CMS verifier compares its message digest to.', }, 'doc.versions.analysis': { operationId: 'doc.versions.analysis', title: 'Analyze version history', summary: "What changed between two revisions of one of a layer's versions.", method: 'GET', path: wireTemplates.layerVersionAnalysis, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocVersionParamsSchema, query: VersionAnalysisQuerySchema, responses: { 200: { contentType: 'application/json', schema: ChangeAnalysisSchema }, 400: errorResponse, 404: errorResponse, }, notes: 'Exactly one of `since.signature` / `since.revision`; `until=` defaults to the last. ' + 'The same answer for every caller. A version never changes, but the rules that judge it can: ' + "with `engine`, the `analysis` value of the layer's head, a settled answer is `immutable`. " + "Without it, or with another value, the answer is this server's own, with `no-store` and " + 'the current value in `EmbedPDF-Engine`.', }, 'doc.versions.download': { operationId: 'doc.versions.download', title: 'Download a version', summary: "The bytes of one of a layer's versions (immutable).", method: 'GET', path: wireTemplates.layerVersionDownload, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocVersionParamsSchema, responses: { 200: { contentType: 'application/pdf' }, 404: errorResponse, }, }, 'doc.versions.revision': { operationId: 'doc.versions.revision', title: 'Download a revision', summary: "The byte prefix of one revision of a layer's version: exactly what a signature over it signed (immutable).", method: 'GET', path: wireTemplates.layerVersionRevision, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocVersionRevisionParamsSchema, responses: { 200: { contentType: 'application/pdf' }, 404: errorResponse, }, }, 'doc.render': { operationId: 'doc.render', title: 'Render page', summary: 'Render one page as an image at the current layer version.', method: 'GET', path: wireTemplates.layerRenderPage, credentials: docCredentials, scope: [], docCapabilities: ['doc.render'], requestHeaders: [documentPasswordHeader], params: DocPageParamsSchema, notes: 'Render parameters (viewport, format) pass as flat dotted query keys, e.g. ' + '`?viewport.kind=width&viewport.width=800`; the full grammar is documented with the viewer.', responses: { 200: { contentType: 'image/webp' }, 404: errorResponse, }, }, 'doc.text': { operationId: 'doc.text', title: 'Extract page text', summary: 'Extracted text content for one page.', method: 'GET', path: wireTemplates.layerTextPage, credentials: docCredentials, scope: [], docCapabilities: ['doc.text.copy'], requestHeaders: [documentPasswordHeader], params: DocPageParamsSchema, responses: { 200: { contentType: 'application/json', schema: PageTextSnapshotSchema }, 404: errorResponse, }, }, 'doc.annotations.list': { operationId: 'doc.annotations.list', title: 'List annotations', summary: "One page's annotations at the current layer version.", method: 'GET', path: wireTemplates.layerAnnotationItems, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.read'], requestHeaders: [documentPasswordHeader], params: DocPageParamsSchema, responses: { 200: { contentType: 'application/json', schema: AnnotationListSchema }, 404: errorResponse, }, }, 'doc.annotations.listAll': { operationId: 'doc.annotations.listAll', title: 'List all annotations', summary: "All pages' annotations as one coherent snapshot at the current layer version.", method: 'GET', path: wireTemplates.layerAnnotationItemsAll, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.read'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, notes: 'Returns one entry per page plus the audit-log cursor for reconciling subsequent document events. Page order is unspecified; join by `page` (a `PageRef`) when display order matters.', responses: { 200: { contentType: 'application/json', schema: AnnotationListSchema }, 404: errorResponse, 409: errorResponse, }, }, 'doc.changes': { operationId: 'doc.changes', title: 'Apply changes', summary: 'Apply user actions to a layer, each a change whose ops apply in order, all or none, or the undo of an earlier change.', method: 'POST', path: wireTemplates.layerChanges, credentials: docCredentials, scope: [], docCapabilities: [ 'doc.annotate.modify', 'doc.attachments.modify', 'doc.forms.fill', 'doc.forms.modify', 'doc.metadata.modify', 'doc.outline.modify', 'doc.pages.assemble', ], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, body: { contentType: ['application/json', 'multipart/form-data'], schema: ChangeRequestSchema, }, notes: 'Each change stands on its own and names itself by `opId`: a refused change rolls back alone, and the answer lists ' + 'every change in order, applied with its result or refused with its error. Asked again under its `opId`, a change ' + 'gets the same answer, refusals included; a different change under an answered `opId` is refused ' + '(IdempotencyKeyReused). `{ opId, undoOf }` undoes an earlier change of the caller, here or in an earlier request; ' + 'an undo leaves alone what was changed since, and the undo of an undo redoes. A redaction, a flatten, a form repair ' + 'or a completed signature ends undo for the changes before it (UndoUnavailable). Each op is checked against its own ' + 'capability: annotation ops need `doc.annotate.modify`, form values `doc.forms.fill`, form structure ' + '`doc.forms.modify`, metadata `doc.metadata.modify`, outline `doc.outline.modify`, pages `doc.pages.assemble`, ' + 'embedded files `doc.attachments.modify`. ' + "Bytes (a stamp's drawing, an attached file, a signature's artwork, a PDF whose pages come in) travel as " + "multipart: a JSON `body` part, each op naming its files by role as `resources: { : '' }`, " + 'and each file as the part `resource:`. ' + 'At most 64 changes per request and 512 ops per change.', responses: { 200: { contentType: 'application/json', schema: ChangeResponseSchema }, 400: errorResponse, 404: errorResponse, 409: errorResponse, 413: errorResponse, }, }, 'doc.annotations.create': { operationId: 'doc.annotations.create', title: 'Create annotation', summary: 'Create an annotation on a page.', method: 'POST', path: wireTemplates.layerAnnotationItems, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocPageParamsSchema, body: { contentType: 'application/json', schema: looseJson }, notes: 'Doc JWTs may instead carry collab scopes (annotations:create:self, …) that refine ' + 'per-annotation authorship rules; the API token is exempt from both.', responses: { 200: { contentType: 'application/json', schema: AnnotationCreateResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.annotations.update': { operationId: 'doc.annotations.update', title: 'Update annotation', summary: 'Update one annotation by key.', method: 'PATCH', path: wireTemplates.layerAnnotationItem, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocAnnotationParamsSchema, body: { contentType: 'application/json', schema: looseJson }, responses: { 200: { contentType: 'application/json', schema: AnnotationUpdateResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.annotations.delete': { operationId: 'doc.annotations.delete', title: 'Delete annotation', summary: 'Delete one annotation by key.', method: 'DELETE', path: wireTemplates.layerAnnotationItem, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocAnnotationParamsSchema, responses: { 200: { contentType: 'application/json', schema: AnnotationDeleteResultSchema }, 404: errorResponse, }, }, 'doc.annotations.reorder': { operationId: 'doc.annotations.reorder', title: 'Reorder annotations', summary: "Change the stacking order of one page's annotations: they go together, in the order given, next to a neighbour annotation (`{ before }`, `{ after }`) or to the bottom (`'start'`) or top (`'end'`). Widgets paint above every annotation and have their own order (`doc.forms.reorderWidgets`): a widget is refused. Returns the page's new order.", method: 'POST', path: wireTemplates.layerAnnotationItemsReorder, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocPageParamsSchema, body: { contentType: 'application/json', schema: AnnotationReorderBodySchema }, responses: { 200: { contentType: 'application/json', schema: AnnotationReorderResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.annotations.flatten': { operationId: 'doc.annotations.flatten', title: 'Flatten annotations', summary: "Flatten a chosen set of one page's annotations into its content — pages.flatten for a selection. Painted annotations are removed; ineligible ones report unchanged.", method: 'POST', path: wireTemplates.layerAnnotationItemsFlatten, credentials: docCredentials, scope: [], docCapabilities: ['doc.pages.modify', 'doc.annotate.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocPageParamsSchema, body: { contentType: 'application/json', schema: looseJson }, responses: { 200: { contentType: 'application/json', schema: AnnotationFlattenResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.annotations.exportAppearance': { operationId: 'doc.annotations.exportAppearance', title: 'Export annotation appearances', summary: "The chosen annotations' appearances as one single-page PDF sized to their union rect — vector, positions preserved. A read; the source is untouched.", method: 'POST', path: wireTemplates.layerAnnotationItemsAppearance, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocPageParamsSchema, body: { contentType: 'application/json', schema: looseJson }, responses: { 200: { contentType: 'application/pdf' }, 400: errorResponse, 404: errorResponse, }, }, 'doc.annotations.readAppearance': { operationId: 'doc.annotations.readAppearance', title: 'Read an annotation appearance', summary: "A stamp's drawing as a one-page PDF, before the fit, rotation and opacity its data describes: with the data, the bytes to create the same stamp again. A read; the source is untouched.", method: 'GET', path: wireTemplates.layerAnnotationItemAppearanceResource, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocAnnotationParamsSchema, responses: { 200: { contentType: 'application/pdf' }, 400: errorResponse, 404: errorResponse, }, }, 'doc.annotations.readFile': { operationId: 'doc.annotations.readFile', title: 'Read an attached file', summary: "A file-attachment annotation's file, decoded: its `file` resource. Its name and type are what the annotation's `file` says. A read; the source is untouched.", method: 'GET', path: wireTemplates.layerAnnotationItemFileResource, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocAnnotationParamsSchema, responses: { 200: { contentType: 'application/octet-stream' }, 400: errorResponse, 404: errorResponse, 413: errorResponse, }, notes: "A file that decodes past the server's limit is refused (PayloadTooLarge).", }, 'doc.forms.list': { operationId: 'doc.forms.list', title: 'List form fields', summary: "The form: every field with its value, every widget's row (its place, look and state), and the calculation order. A form field's widgets come with the form, never with the annotations.", method: 'GET', path: wireTemplates.layerForm, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.read'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/json', schema: FormSnapshotSchema }, 404: errorResponse, }, }, 'doc.forms.setValue': { operationId: 'doc.forms.setValue', title: 'Set form value', summary: "Set one form field's value.", method: 'POST', path: wireTemplates.layerFormFieldValue, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.fill'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocFieldParamsSchema, body: { contentType: 'application/json', schema: looseJson }, responses: { 200: { contentType: 'application/json', schema: FormSetValueResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.forms.updateWidget': { operationId: 'doc.forms.updateWidget', title: 'Update form widget', summary: "Change a widget's place and look: what an annotation update takes, for a form field's widget. A widget is the form's, so the annotation routes refuse one.", method: 'PATCH', path: wireTemplates.layerFormWidget, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocAnnotationParamsSchema, body: { contentType: 'application/json', schema: FormWidgetUpdateBodySchema }, responses: { 200: { contentType: 'application/json', schema: FormWidgetUpdateResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.forms.deleteWidget': { operationId: 'doc.forms.deleteWidget', title: 'Delete form widget', summary: "Delete a widget: it leaves its page, and its field when it has one. The field survives, unplaced when this was its last widget. A widget that is its field's own dictionary is refused: delete the field. A widget is the form's, so the annotation routes refuse one.", method: 'DELETE', path: wireTemplates.layerFormWidget, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocAnnotationParamsSchema, responses: { 200: { contentType: 'application/json', schema: FormWidgetDeleteResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.forms.reorderWidgets': { operationId: 'doc.forms.reorderWidgets', title: 'Reorder form widgets', summary: "Change the stacking order of one page's widgets: they go together, in the order given, next to a neighbour widget or to the bottom (`'start'`) or top (`'end'`) of the page's widgets, which paint above every annotation. Where the page's `/Tabs` follows it, this is also the tab order. Returns the page's new widget order.", method: 'POST', path: wireTemplates.layerFormWidgetsReorder, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocPageParamsSchema, body: { contentType: 'application/json', schema: FormWidgetsReorderBodySchema }, responses: { 200: { contentType: 'application/json', schema: FormWidgetsReorderResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.forms.reorderCalculations': { operationId: 'doc.forms.reorderCalculations', title: 'Reorder form calculations', summary: "Change the form's calculation order, the order its fields' calculate scripts run in: the fields go together, in the order given, next to a neighbour field or to the start (`'start'`) or end (`'end'`). Every field named must have a calculate script, which puts it in the order. Returns the whole new order.", method: 'POST', path: wireTemplates.layerFormCalculationsReorder, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: FormCalculationsReorderBodySchema }, responses: { 200: { contentType: 'application/json', schema: FormCalculationsReorderResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.forms.reset': { operationId: 'doc.forms.reset', title: 'Reset form', summary: 'Reset the fields named in `refs` to their default values, or the whole form without it. Returns the fields that changed.', method: 'POST', path: wireTemplates.layerFormReset, credentials: docCredentials, scope: [], docCapabilities: ['doc.forms.fill'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: FormResetBodySchema }, responses: { 200: { contentType: 'application/json', schema: FormResetResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.pages.viewports': { operationId: 'doc.pages.viewports', title: 'Read measurement viewports', summary: 'Read page measurement viewports in drawing order from the current layer.', method: 'GET', path: wireTemplates.layerPageViewports, credentials: docCredentials, scope: [], docCapabilities: ['doc.open'], requestHeaders: [documentPasswordHeader], params: DocPageParamsSchema, responses: { 200: { contentType: 'application/json', schema: PageMeasurementViewportListSchema }, 404: errorResponse, }, }, 'doc.pages.setScale': { operationId: 'doc.pages.setScale', title: 'Set page measurement scale', summary: 'Upsert or remove EmbedPDF calibration while preserving foreign viewports. Existing annotation scales are unchanged.', method: 'PUT', path: wireTemplates.layerPageScale, credentials: docCredentials, scope: [], docCapabilities: ['doc.annotate.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocPageParamsSchema, body: { contentType: 'application/json', schema: PageScaleInputSchema }, responses: { 200: { contentType: 'application/json', schema: PageScaleResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.pages.setName': { operationId: 'doc.pages.setName', title: 'Set page name', summary: 'Register or rename a /Names /Pages entry (a named page). A page-structure mutation: the layout version advances.', method: 'POST', path: wireTemplates.layerPagesNames, credentials: docCredentials, scope: [], docCapabilities: ['doc.pages.assemble'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: looseJson }, responses: { 200: { contentType: 'application/json', schema: PageNameResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.pages.removeName': { operationId: 'doc.pages.removeName', title: 'Remove page name', summary: 'Remove a /Names /Pages entry; the page itself stays.', method: 'POST', path: wireTemplates.layerPagesNamesDelete, credentials: docCredentials, scope: [], docCapabilities: ['doc.pages.assemble'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: looseJson }, responses: { 200: { contentType: 'application/json', schema: PageNameResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.pages.flatten': { operationId: 'doc.pages.flatten', title: 'Flatten pages', summary: 'Flatten annotations and form fields into page content.', method: 'POST', path: wireTemplates.layerPagesFlatten, credentials: docCredentials, scope: [], docCapabilities: ['doc.pages.modify', 'doc.annotate.modify'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: looseJson, required: false }, responses: { 200: { contentType: 'application/json', schema: PageFlattenResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.pages.extract': { operationId: 'doc.pages.extract', title: 'Extract pages', summary: 'Export the listed pages, in order, as a standalone PDF.', method: 'POST', path: wireTemplates.layerPagesExtract, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: looseJson }, responses: { 200: { contentType: 'application/pdf' }, 400: errorResponse, 404: errorResponse, }, notes: 'A read, not a mutation: the source document is untouched and no event is published. Body is `{"pages": PageRef[], "flatten"?: {"usage"?: "display" | "print"}, "includeAnnotations"?: boolean, "includeFormFields"?: boolean}`; the response body is the new PDF. With `flatten` the copy is the pages as they draw for `usage` (`"print"`: a print copy): the annotations and form fields painted in, nothing interactive left, layers in their state for the usage. A flattened copy takes `doc.download` or `doc.download.flattened`, and paints only what the caller may read; `includeAnnotations` and `includeFormFields` choose what it paints, and are refused without `flatten`.', }, 'doc.redactions.apply': { operationId: 'doc.redactions.apply', title: 'Apply redactions', summary: 'Apply pending redactions, permanently removing content.', method: 'POST', path: wireTemplates.layerRedactionsApply, credentials: docCredentials, scope: [], docCapabilities: ['doc.pages.modify', 'doc.annotate.modify', 'doc.redact'], requestHeaders: [documentPasswordHeader, idempotencyKeyHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: RedactionApplyScopeInputSchema }, responses: { 200: { contentType: 'application/json', schema: RedactionApplyResultSchema }, 400: errorResponse, 404: errorResponse, }, }, 'doc.downloadLink': { operationId: 'doc.downloadLink', title: 'Create download link', summary: "A short-lived URL that downloads the layer's current PDF without an Authorization header, for services that only take a plain URL.", method: 'POST', path: wireTemplates.layerDownloadLink, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, body: { contentType: 'application/json', schema: DownloadLinkRequestSchema }, responses: { 200: { contentType: 'application/json', schema: DownloadLinkResponseSchema }, 404: errorResponse, 501: errorResponse, }, notes: 'The link opens the layer as it is when created: once the layer changes, it answers 404, so create it right before handing it over. It downloads that one file and nothing else, and a password-protected document is checked when the link is created. Deployments that verify tokens with their own keys (JWKS) mint links on their backend: a doc token with `layer_name`, a `download: { docVersion, mode: "incremental" }` claim and a short `exp`, passed as `link` on the versioned download URL.', }, 'doc.download': { operationId: 'doc.download', title: 'Download PDF', summary: "Download the layer's current PDF (base plus layer edits).", method: 'GET', path: wireTemplates.layerDownload, credentials: docCredentials, scope: [], docCapabilities: ['doc.download'], requestHeaders: [documentPasswordHeader], params: DocLayerParamsSchema, responses: { 200: { contentType: 'application/pdf' }, 404: errorResponse, }, }, } as const satisfies Record; export type DocOperationId = keyof typeof docOperations; /** Every operation in the published contract: admin surfaces + doc plane. */ export const allOperations = { ...adminOperations, ...docOperations } as const; /** * Documentation groups, keyed by the dot-joined `x-fern-sdk-group-name` * path of the operations they contain. Emitted as `x-docs-groups`; the * API reference derives its navigation sections from this manifest, so * key order here is section order there. `slug` overrides the URL * segment when the registry's short group name isn't the public one. * The emitter fails if an operation's group path is missing here. */ export interface DocsGroup { title: string; slug?: string; } export const docsGroups = { deployment: { title: 'Deployment' }, tenants: { title: 'Tenants' }, documents: { title: 'Tenant documents' }, 'documents.layers': { title: 'Layers' }, folders: { title: 'Folders' }, tokens: { title: 'Tokens' }, grants: { title: 'Grants' }, 'grants.visitors': { title: 'Visitors' }, doc: { title: 'Document operations', slug: 'document-operations' }, 'doc.annotations': { title: 'Annotations' }, 'doc.attachments': { title: 'Attachments' }, 'doc.fonts': { title: 'Fonts' }, 'doc.fonts.programs': { title: 'Font programs' }, 'doc.forms': { title: 'Forms' }, 'doc.metadata': { title: 'Metadata' }, 'doc.metadata.custom': { title: 'Custom keys' }, 'doc.outline': { title: 'Outline' }, 'doc.pages': { title: 'Pages' }, 'doc.redactions': { title: 'Redactions' }, 'doc.signatures': { title: 'Digital signatures' }, 'doc.versions': { title: 'Versions' }, } as const satisfies Record;