diff --git a/.changeset/38894-print-downloads-no-attachment.md b/.changeset/38894-print-downloads-no-attachment.md new file mode 100644 index 00000000000..2da82e26dbe --- /dev/null +++ b/.changeset/38894-print-downloads-no-attachment.md @@ -0,0 +1,31 @@ +--- +'@objectstack/service-print': patch +--- + +fix!: a record print answers the PDF itself and writes no attachment + +Clause-②: yes (narrowing) +Metadata-protocol: none + +**BREAKING — a print no longer attaches the PDF to the record; it hands the PDF back as a download.** `POST /api/v1/print/records` now answers the PDF itself and stores nothing; keeping the PDF on the record is a separate, explicit act. A declared `type: 'api'` action that targets the route, which is how an app put "Generate PDF" on a record page, now downloads the PDF in the console: see "Apps that declare a print action" below. + +- **The door's answer.** `POST /api/v1/print/records` used to answer `201` with JSON naming the stored file (`fileId`, `attachmentId`, `size`, `filename`). It now answers `200` with the PDF itself as the body: `Content-Type: application/pdf`, `Content-Disposition: attachment` (an ASCII `filename=` and the RFC 5987 `filename*=UTF-8''…` form, so a name such as `报价单.pdf` survives), `Cache-Control: no-store`. Refusals keep the JSON error envelope. +- **Nothing is stored.** A print used to write one `sys_file` and one `sys_attachment` on the record, as the caller. It now writes nothing. +- **Read access is the whole permission.** Printing used to need `enable: { files: true }` on the object (`FILES_DISABLED` / 403) and the attach rule, edit access to the record (`ATTACHMENT_PARENT_ACCESS` / 403). It now needs read access to the record and nothing else: a user who can read a record but not edit it can print it, on any object. +- **No storage dependency.** The `print` service was `unavailable` without a `file-attachments` service; it now needs none, and the package no longer depends on `@objectstack/service-storage`. +- A request's own `filename` is bounded at 255 characters (`PRINT_FILENAME_MAX_CHARS`) and must be well-formed text (a lone UTF-16 surrogate is refused); either refusal is `VALIDATION_ERROR` / 400, before anything is rendered. + +The in-process verb is renamed with its result, so a caller that still reads the stored file's ids fails at its own call instead of reading `undefined`: + +- FROM `IPrintService.printRecordToFile` TO `IPrintService.printRecordToPdf`, which takes the same request and context and resolves to the PDF. +- FROM `PrintedRecordFile` TO `PrintedRecordPdf`, `{ pdf, size, filename, contentType }`: read `pdf` where the code read `fileId` or `attachmentId`. + +**Apps that declare a print action.** The route's answer is now a file, and the REST action door (`POST /api/v1/actions/...`) relays a target's non-JSON `2xx` answer that carries `Content-Disposition: attachment` byte for byte: + +- **Through the REST action door and the console**, a declared `type: 'api'` action whose `target` is `/api/v1/print/records` (the showcase's `GenerateInvoicePdfAction`, HotCRM's Print Quote) delivers the PDF: the door answers the route's bytes with its `Content-Type: application/pdf` and `Content-Disposition: attachment`, and the console saves the file under the name that header gives. A PDF larger than the door's 32 MiB bound is the door's `502`. +- **MCP `run_action`** still answers a file with its own `502`: a tool result cannot carry one. A caller that ran the action over MCP to archive a PDF has no replacement there. +- FROM → TO for an app that declares such an action: it used to answer the stored file's ids (`fileId`, `attachmentId`, `size`, `filename`) and leave the PDF on the record's Attachments; a click now downloads the PDF, and nothing is on the record. A success message that promised an attachment should say the PDF was printed. + +The one-line fix for an app that wants the PDF kept on the record: save it with an explicit act of its own (an upload to the record's attachments, or an app action). An automation keyed on the attachment a print used to write no longer fires on a print: HotCRM's `quote_print_presented` flow, which matched the printed attachment's file name, must become an explicit "mark presented" action. + + diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 8d7aec63805..9e022041428 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -197,7 +197,7 @@ One of the largest consumers of the flag; | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | -| 47d | The print service REFUSES the system context: `printRecordToFile` admits a human user acting for themselves alone | service-print | Get: nothing — a system caller is refused (`PERMISSION_DENIED`) before any page is read, session minted or browser started. Lose: nothing a user held — the PDF is rendered as the requesting user and never as the system, so a record is archived only by someone who could read it | `refuseUnlessHumanCaller` | +| 47d | The print service REFUSES the system context: `printRecordToPdf` admits a human user acting for themselves alone | service-print | Get: nothing — a system caller is refused (`PERMISSION_DENIED`) before any page is read, session minted or browser started. Lose: nothing a user held — the PDF is rendered as the requesting user and never as the system, and handed back to that user only, so a record's PDF reaches only someone who could read it; a print stores nothing | `refuseUnlessHumanCaller` | | 47e | The caller-scoped attach verbs REFUSE the system context: `attachFileAs` and `assertMayAttach` admit a signed-in user alone, and so do the caller-scoped record-file verbs the MCP `read_file` and `create_upload_link` tools call (`listRecordFilesAs`, `readRecordFileAs`, `createUploadLinkAs`, `createUploadLinkForNewRecordAs`) | service-storage | Get: nothing — a system caller is refused (`PERMISSION_DENIED`); the system attaches through `attachFile`, whose rows name no user. Lose: nothing a user held — the caller-scoped verbs insert the attachment under the caller's context so every insert gate judges that user and both rows name them, and the record-file verbs read the record and judge the file as that user, and bind an upload link to them; `createUploadLinkForNewRecordAs` names no record, so it asks the object's create verdict and the field's writability as that user instead | `packages/services/service-storage/src/file-attachment-service.ts#requireUserContext`, `packages/services/service-storage/src/record-file-access.ts#requireUserContext` | | 47f | The file-reference claim path asks no read verdict of a system write: a record write claims or copies a referenced file only as its caller may read it (the download door's verdict), and a system write carries no caller to ask | service-storage | Get: a system write claims or copies any file the organization-scoped lookup reaches, as before #25692; a deliberate server-side copy between records runs this way. The exception is a file uploaded through an upload link that names no record (#32686), and the ids such a link answers before its upload (its own, and those it reserves for a several-file upload): until a record has held the file, only its uploader's own write takes it, so a system write naming it is refused at the field. Once a record holds it, a system write copies it as any; once a record lets it go, it is judged as any released file. Lose: nothing a user held — a user write is judged by the download door's verdict, and a context-less programmatic write is not asked either | `referencingCallerOf` | | 47g | The `sys_file` storage-owned columns guard returns early on create: a system insert keeps the `key`, `mime_type`, `size`, `status` and `etag` it writes | service-storage | Get: the storage service's own inserts (the upload doors, the field-file copy and backfill) write those five columns. Lose: nothing a user held — a non-system create has them dropped and starts `pending`, and on update the same columns are `readonly`, so the UPDATE `readonly` strip keeps them for every non-system caller | `installSysFileStorageOwnedColumnsGuard` | diff --git a/content/docs/ui/print-pages.mdx b/content/docs/ui/print-pages.mdx index b1ac607b5a6..3624a968ae5 100644 --- a/content/docs/ui/print-pages.mdx +++ b/content/docs/ui/print-pages.mdx @@ -1,7 +1,7 @@ --- title: Print pages — printing a record to a PDF file navTitle: Print Pages -description: Declare print on a record page, then archive a record's PDF as an attachment with the print service, rendered in headless Chromium as the requesting user +description: Declare print on a record page, then download a record's PDF from the print service, rendered in headless Chromium as the requesting user --- A **print page** is an ordinary page with one more key, `print`. The console @@ -10,15 +10,16 @@ paper: the sheet size, margins, page numbers and repeated header and footer come from the `print` declaration, mapped to print CSS by the console. `@objectstack/service-print` prints the same page on the server. It renders the -record's print page in **headless Chromium**, as the requesting user, and -archives the PDF as a file attached to the record — downloadable from the -record's attachments, and usable wherever a file is. +record's print page in **headless Chromium**, as the requesting user, and hands +the PDF back as a **download**. A print stores nothing: no file, and no +attachment on the record. Keeping a PDF on the record is a separate, explicit +act — an upload to the record's attachments, or an action of the app's own. ## Declare the print page A print page is a `kind: 'full'` record page whose blocks are all from the printable subset (`PRINTABLE_PAGE_COMPONENT_TYPES` in `@objectstack/spec/ui`; -`os validate` refuses anything else). The record's object must allow files. +`os validate` refuses anything else). ```ts import { definePage } from '@objectstack/spec/ui'; @@ -35,8 +36,6 @@ export const InvoiceDocumentPage = definePage({ { name: 'main', components: [{ type: 'record:details' }] }, ], }); - -// …and on the object: enable: { files: true } ``` A record prints on **any record page of its object that declares `print`**, so @@ -141,11 +140,11 @@ const print = kernel.getService('print'); print.status(); // { state: 'ready', placement: 'local', version: '141.0.7390.37' } -const file = await print.printRecordToFile( +const printed = await print.printRecordToPdf( { app: 'sales', object: 'invoice', recordId: 'inv_1', page: 'invoice_document' }, context, // the requesting user's execution context ); -// { fileId, attachmentId, size, filename: 'INV-0001.pdf' } +// { pdf: Uint8Array, size, filename: 'INV-0001.pdf', contentType: 'application/pdf' } ``` With no `filename`, the PDF is named after the record: its display name — the @@ -155,25 +154,29 @@ The name is made safe for a file: `/ \ : * ? " < > |` become `_`, control characters and runs of whitespace become one space, leading dots are dropped, and it is cut to 100 characters. A record with no display value keeps `-.pdf` (`invoice_document-inv_1.pdf`). A `filename` in the -request is used exactly as given. Printing a record twice attaches two files -of the same name; neither replaces the other. +request is used exactly as given, up to 255 characters; a longer one, or one +that is not well-formed text (it holds a lone UTF-16 surrogate), is refused +`VALIDATION_ERROR` / 400 before anything is rendered. The page is rendered as the requesting user — never as the system — through a short-lived session minted for that user and revoked as soon as the print ends, -whether it succeeded or not. The PDF is archived as theirs: the attachment is -written under their own permissions, and both the file and the attachment name -them. A user can never archive a record they could not read, or attach a file -where they could not attach one by hand. +whether it succeeded or not. A print asks one permission: the user must be able +to read the record. A user who may read a record but not edit it prints it as +anyone else does; a user who cannot read it is refused, and never learns +whether it exists. ## Print from the console `PrintServicePlugin` also mounts one HTTP route on the kernel's HTTP server, `POST /api/v1/print/records`, so a user can print the record they are looking at. Its JSON body is the same request, `{ app, object, recordId, page, -filename? }`, and it answers `201` with the stored file, -`{ fileId, attachmentId, size, filename }`. The print runs as the signed-in -caller, exactly as an in-process print with their context does, and the file is -attached once, by the service. +filename? }`, and it answers `200` with the **PDF itself** as the body: +`Content-Type: application/pdf`, `Content-Disposition: attachment` naming the +file (an ASCII `filename=` and the RFC 5987 `filename*=UTF-8''…` form, so a +name such as `报价单.pdf` survives), and `Cache-Control: no-store`. A browser +saves it as a download. The print runs as the signed-in caller, exactly as an +in-process print with their context does. A refusal is the usual JSON error +envelope. A kernel that owns no HTTP server, such as an environment's kernel behind a shared host, reaches the same route through the runtime dispatcher: it forwards @@ -185,43 +188,26 @@ the user's language saying the action needs a service this environment does not have, never the package name. A `SERVICE_UNAVAILABLE` / 503 keeps the route's own sentence, since it can clear on a retry. -Reach it from the console with an ordinary `type: 'api'` action on the object: - -```ts -import { defineAction } from '@objectstack/spec/ui'; - -export const GenerateInvoicePdf = defineAction({ - name: 'generate_invoice_pdf', - label: 'Generate PDF', - objectName: 'invoice', - type: 'api', - target: '/api/v1/print/records', - method: 'POST', - recordIdParam: 'recordId', // the clicked record's id - bodyExtra: { app: 'sales', object: 'invoice', page: 'invoice_document' }, - locations: ['record_row'], - refreshAfter: true, -}); -``` - -The route above answers JSON, which the action reads as data. The REST action -door also carries a file: a route that answers a PDF itself as an attachment -(`Content-Disposition: attachment`, not JSON) is relayed byte for byte, and the -console saves it under the name the header gives. The MCP action door does not -carry a file and answers `502` instead. See +A declared `type: 'api'` action whose `target` is this route (the clicked +record's id under `recordIdParam: 'recordId'`, and `app`, `object` and `page` +in `bodyExtra`) delivers the PDF: the REST action door relays the route's +answer byte for byte, `Content-Type` and `Content-Disposition` included, and +the console saves it as a download under the name that header gives. A PDF +larger than the door's 32 MiB bound is the door's `502`. The MCP action door +does not carry a file: `run_action` on such an action answers `502`. See [Call it over REST](/docs/ui/actions#call-it-over-rest). The route refuses, before it asks the service anything: an anonymous request (`UNAUTHENTICATED` / 401); a sign-in held by an authentication policy (`403` with the policy's own code); a request from an **impersonation session** — an -administrator signed in as the user — (`PERMISSION_DENIED` / 403: a print is -archived in the user's name, so it is never made for them by someone else); and +administrator signed in as the user — (`PERMISSION_DENIED` / 403: a print +signs a session in under the user's name, so it is never made for them by +someone else); and a query parameter or a body field outside the request (`VALIDATION_ERROR` / 400). Every refusal below then reaches the caller with its own `code` and `status`; a 5xx answers with the route's own sentence, and the service's text is written to the server log. The route writes no audit row of its own: the print's -session sign-in and sign-out are recorded as any sign-in is, and the file and -the attachment name the caller. +session sign-in and sign-out are recorded as any sign-in is. ## Refusals @@ -235,15 +221,11 @@ before a session is minted or a browser is started, in this order: | 3 | No such page | `RESOURCE_NOT_FOUND` / 404 | | 3 | The page is not a record page of the object (`type: 'record'`, that `object`), or declares no `print` | `VALIDATION_ERROR` / 400 | | 4 | The record does not exist, or the caller cannot read it | `RECORD_NOT_FOUND` / 404 | -| 5 | The object does not declare `enable: { files: true }` | `FILES_DISABLED` / 403 | -| 5 | The caller may not create attachments at all | `PERMISSION_DENIED` / 403 | -| 5 | The caller may not attach a file to this record (attaching needs edit access to it) | `ATTACHMENT_PARENT_ACCESS` / 403 | An engine that did not answer its last probe is probed once more only after -step 5, so no browser is started before every refusal above has had its say. +step 4, so no browser is started before every refusal above has had its say. -After those, a print can still fail as the render or the archive does: the page -not rendering within the 30 s budget (`TIMEOUT` / 504), or the archive's own -refusals, such as a file over the upload size limit (`PAYLOAD_TOO_LARGE` / 413). +After those, a print can still fail as the render does: the page not rendering +within the 30 s budget (`TIMEOUT` / 504). A failure to end the session afterwards never replaces the print's own outcome; it is logged, and the session expires on its own within 60 s. diff --git a/examples/app-showcase/src/data/objects/invoice.object.ts b/examples/app-showcase/src/data/objects/invoice.object.ts index 02ab445076c..58bc779ef3a 100644 --- a/examples/app-showcase/src/data/objects/invoice.object.ts +++ b/examples/app-showcase/src/data/objects/invoice.object.ts @@ -60,8 +60,8 @@ export const Invoice = ObjectSchema.create({ color: 'green', description: 'A customer invoice entered together with its line items.', - // Files on an invoice: its printed PDF is archived as an attachment of the - // record (`showcase_invoice_document` is its print page). + // Files on an invoice: users attach files to the record. A print stores + // none: `@objectstack/service-print` answers the PDF as a download. enable: { files: true }, // A PAID invoice is closed (ADR-0162). The platform refuses a caller's diff --git a/examples/app-showcase/src/system/translations/index.ts b/examples/app-showcase/src/system/translations/index.ts index 0b1181baf70..867c79c7c6e 100644 --- a/examples/app-showcase/src/system/translations/index.ts +++ b/examples/app-showcase/src/system/translations/index.ts @@ -793,7 +793,7 @@ export const ShowcaseTranslationBundle = { _actions: { showcase_generate_invoice_pdf: { label: '生成 PDF', - successMessage: 'PDF 已附加到发票。', + successMessage: '发票已打印为 PDF。', }, }, }, diff --git a/examples/app-showcase/src/ui/actions/index.ts b/examples/app-showcase/src/ui/actions/index.ts index 0bddd2d7722..783bf5c3c0d 100644 --- a/examples/app-showcase/src/ui/actions/index.ts +++ b/examples/app-showcase/src/ui/actions/index.ts @@ -413,25 +413,30 @@ export const SubmitForSignoffAction = defineAction({ }); /** - * api — print the invoice to a PDF and attach it to the invoice, as the user - * who clicks it. + * api — print the invoice to a PDF, as the user who clicks it. * * The target is `@objectstack/service-print`'s door, `POST * /api/v1/print/records`, which `PrintServicePlugin` mounts (composed in * `objectstack.config.ts`). The door prints the record on the invoice's * default record page, `showcase_invoice_document`, the page that declares - * `print`, through the in-process print service, which attaches the PDF to the - * invoice once, as the caller. The body is the door's whole request: the - * clicked record's id (`recordIdParam`) and the three constant fields - * (`bodyExtra`); `app` is the console route segment the record opens in. + * `print`, and answers the PDF itself as a download; it stores nothing on the + * invoice. The body is the door's whole request: the clicked record's id + * (`recordIdParam`) and the three constant fields (`bodyExtra`); `app` is the + * console route segment the record opens in. + * + * The console sends the click through the REST action door, which relays the + * door's PDF byte for byte (`Content-Disposition: attachment`), and saves it + * as a download under the print's file name. Over MCP `run_action` the same + * action answers `502`: a tool result cannot carry a file. * * Its availability is the user's access to the record: a row or a record the * user cannot read is not shown to them, and a page is never gated apart from - * the data it shows. The door re-judges every print anyway, and each of its - * refusals reaches the user as the action's error: no print engine configured - * (the showcase composes none by default: set `OS_PRINT_CHROMIUM_PATH` or - * `OS_PRINT_BROWSER_ENDPOINT`, and `OS_PRINT_CONSOLE_URL`), a record they may - * not edit (attaching needs it), an impersonation session. + * the data it shows. Read access is the whole permission a print asks. The + * door re-judges every print anyway, and each of its refusals reaches the user + * as the action's error: no print engine configured (the showcase composes + * none by default: set `OS_PRINT_CHROMIUM_PATH` or + * `OS_PRINT_BROWSER_ENDPOINT`, and `OS_PRINT_CONSOLE_URL`), a record they + * cannot read, an impersonation session. * * `record_row` puts it in the invoice list's row menu, where the console draws * it. `record_page` is its record-page placement, beside Submit for Sign-off. @@ -451,7 +456,7 @@ export const GenerateInvoicePdfAction = defineAction({ execution: 'perRecord', recordIdParam: 'recordId', bodyExtra: { app: 'com.example.showcase', object: invoice, page: 'showcase_invoice_document' }, - successMessage: 'The PDF is attached to the invoice.', + successMessage: 'The invoice was printed to PDF.', locations: ['record'], refreshAfter: true, }); diff --git a/examples/app-showcase/src/ui/pages/invoice-document.page.ts b/examples/app-showcase/src/ui/pages/invoice-document.page.ts index 89c73e0b1e6..0e83b4b99f0 100644 --- a/examples/app-showcase/src/ui/pages/invoice-document.page.ts +++ b/examples/app-showcase/src/ui/pages/invoice-document.page.ts @@ -6,8 +6,8 @@ import { definePage } from '@objectstack/spec/ui'; * Invoice Document — the invoice's record page, and a PRINT page: it declares * `print`, so the console's Print action prints it through the browser, and * `@objectstack/service-print` renders the same page in headless Chromium, as - * the requesting user, and archives the PDF as a file attached to the invoice - * (`showcase_invoice` declares `enable: { files: true }` for that). + * the requesting user, and answers the PDF itself as a download; nothing is + * stored on the invoice. * * It is the invoice's DEFAULT record page (`isDefault: true`), so the invoice * opens on its document. That is this app's choice, not a rule: a record prints diff --git a/packages/qa/dogfood/test/authz-conformance.matrix.ts b/packages/qa/dogfood/test/authz-conformance.matrix.ts index 729c701ef03..86574bb4bde 100644 --- a/packages/qa/dogfood/test/authz-conformance.matrix.ts +++ b/packages/qa/dogfood/test/authz-conformance.matrix.ts @@ -454,8 +454,8 @@ export const AUTHZ_CONFORMANCE: AuthzPrimitive[] = [ enforcement: 'core/security/own-row-delete-routes.ts (the personal-view and attachment removal doors) and service-storage/attachment-removal-routes.ts (the rename door) — the caller resolved from the request\'s own credentials (ownRowDeleteCallerResolver: no signed-in user 401, a held sign-in 403), the row read AS THE CALLER (object grant, organization wall, the owner-only scope of sys_personal_view, the attachment read-visibility gate; unreadable = unknown 404), the owner column checked (403 PERMISSION_DENIED) or the update gate asked, then a system write attributed to the caller; reached through IPersonalViewDoorsService.handlePersonalViewDoor and IAttachmentDoorsService.handleAttachmentDoor by runtime/domains/own-door-bridge.ts (personal-views.ts, attachments.ts), which claims exactly the door shapes, forwards the transport\'s request UNREAD, reads the REQUEST kernel\'s slot per request and adds no credential of its own (an absent slot or member is a typed 501, never a route miss). The two dispatcher preamble gates apply with NO exemption: core/security/auth-gate.ts ALLOW_ROUTES does not list the paths and runtime/http-dispatcher.ts enforceProjectMembership does not skip them. Each member runs the very registration its self-hosted mount runs (plugin-auth personal-view-door-member.ts, service-storage attachment-door-member.ts, over plugin-hono-server createDoorTableMember)', covers: ['dispatcher-domain:route-ledger.ts:/personal-views', 'dispatcher-domain:route-ledger.ts:/attachments'], note: 'The DISPATCHER domains only: on a self-hosted kernel the same paths are served from the plugins\' mounts on the kernel\'s http.server and never reach the dispatcher. Unit-, wire- and dogfood-proven: runtime domains/own-door-bridge.test.ts pins both domains on the real HttpDispatcher (the door shapes forwarded unread, every other method and path the ordinary miss, 501 for an absent slot or member, the slot read per request and only from the request kernel, the environment-scoped spelling forwarded at the wire path, a signed-in non-member and a gated session stopped before the member); personal-view-row-scope.dogfood.test.ts and member-attachment-baseline.dogfood.test.ts drive each door through a dispatcher alone over the real showcase and attachments stacks (`[hosted]`: the owner\'s removal and rename land, another member is refused as on the self-hosted door, anonymous is 401).' }, - { id: 'print-door-session', summary: 'The print door (`POST /print/records`) on a kernel with no http.server — a signed-in member acting for themselves prints a record page they can read and archives the PDF on it; an anonymous caller is refused 401 and an impersonation session 403 by the door itself, exactly as the self-hosted mount refuses them', state: 'enforced', - enforcement: 'service-print/print-routes.ts registerPrintRoutes — the caller resolved from the request\'s own credentials (resolveCaller: no signed-in user 401 UNAUTHENTICATED, a held sign-in 403), an impersonation session refused 403 PERMISSION_DENIED (impersonatorOf reads session.impersonatedBy), then PrintService.printRecord runs AS THE CALLER (the record read, the files and attachment grants, the per-print session minted for that user); reached through IPrintDoorService.handlePrintDoor by runtime/domains/own-door-bridge.ts (print.ts), which claims exactly `POST /print/records`, forwards the transport\'s request UNREAD, reads the REQUEST kernel\'s `print` slot per request and adds no credential of its own (an absent slot or member is a typed 501, never a route miss). The two dispatcher preamble gates apply with NO exemption: core/security/auth-gate.ts ALLOW_ROUTES does not list the path and runtime/http-dispatcher.ts enforceProjectMembership does not skip it. The member runs the very registration the self-hosted mount runs (service-print print-door-member.ts, over plugin-hono-server createDoorTableMember)', + { id: 'print-door-session', summary: 'The print door (`POST /print/records`) on a kernel with no http.server — a signed-in member acting for themselves prints a record page they can read and receives the PDF as a download, nothing stored; an anonymous caller is refused 401 and an impersonation session 403 by the door itself, exactly as the self-hosted mount refuses them', state: 'enforced', + enforcement: 'service-print/print-routes.ts registerPrintRoutes — the caller resolved from the request\'s own credentials (resolveCaller: no signed-in user 401 UNAUTHENTICATED, a held sign-in 403), an impersonation session refused 403 PERMISSION_DENIED (impersonatorOf reads session.impersonatedBy), then PrintService.printRecordToPdf runs AS THE CALLER (the record read — read access is the whole permission a print asks — and the per-print session minted for that user; no write, no attachment); reached through IPrintDoorService.handlePrintDoor by runtime/domains/own-door-bridge.ts (print.ts), which claims exactly `POST /print/records`, forwards the transport\'s request UNREAD, reads the REQUEST kernel\'s `print` slot per request and adds no credential of its own (an absent slot or member is a typed 501, never a route miss). The two dispatcher preamble gates apply with NO exemption: core/security/auth-gate.ts ALLOW_ROUTES does not list the path and runtime/http-dispatcher.ts enforceProjectMembership does not skip it. The member runs the very registration the self-hosted mount runs (service-print print-door-member.ts, over plugin-hono-server createDoorTableMember)', covers: ['dispatcher-domain:route-ledger.ts:/print'], note: 'The DISPATCHER domain only: on a self-hosted kernel the same path is served from PrintServicePlugin\'s mount on the kernel\'s http.server and never reaches the dispatcher. Unit- and wire-proven: runtime domains/own-door-bridge.test.ts pins the domain on the real HttpDispatcher (the door shape forwarded unread, every other method and path the ordinary miss, 501 for an absent slot or member, the slot read per request and only from the request kernel, a signed-in non-member and a gated session stopped before the member); http-conformance hono-print-door.conformance.test.ts drives createHonoApp over a kernel with no http.server with real better-auth sessions (anonymous 401 and a signed-in member with no engine 503, each byte-identical to the self-hosted mount; no plugin 501). The impersonation refusal is pinned on the self-hosted mount (print-door-impersonation.dogfood.test.ts); the bridged face runs the same handler.' }, diff --git a/packages/qa/dogfood/test/print-door-impersonation.dogfood.test.ts b/packages/qa/dogfood/test/print-door-impersonation.dogfood.test.ts index e32c7c48a31..b165431034c 100644 --- a/packages/qa/dogfood/test/print-door-impersonation.dogfood.test.ts +++ b/packages/qa/dogfood/test/print-door-impersonation.dogfood.test.ts @@ -5,8 +5,8 @@ // // `POST /api/v1/print/records` (`@objectstack/service-print`'s door, which the // showcase composes) refuses a print asked from an impersonation session: -// a printed PDF is rendered and archived as the session's user, and in an -// impersonation session that user is not the one asking. The door recognises +// a printed PDF is rendered under a session minted for the session's user, +// and in an impersonation session that user is not the one asking. The door recognises // such a session by the mark the auth service writes on it — better-auth's // admin plugin sets `impersonatedBy` on the session it mints, which // `@objectstack/plugin-auth` stores as `sys_session.impersonated_by` — read diff --git a/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts b/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts index b938d0bc318..b2d78539096 100644 --- a/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts +++ b/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts @@ -2,10 +2,13 @@ // // The print service on a real showcase boot: `PrintServicePlugin` composed // explicitly beside the real storage and audit plugins, and its refusal chain -// and archive judged by the REAL services a deployment composes — the -// metadata service's pages and objects, the data engine's row-level security -// read as the caller, and `file-attachments`' one writer of `sys_file` and -// `sys_attachment`. +// and its answer judged by the REAL services a deployment composes — the +// metadata service's pages and objects, and the data engine's row-level +// security read as the caller. +// +// A print hands the PDF back and stores nothing (the maintainer's +// print-download ruling): the file-attachments service is composed here and +// never written through, so `sys_file` and `sys_attachment` stay as they were. // // Two layers, on the same boot: // @@ -13,25 +16,24 @@ // so, and a print is refused `503` after the principal check and before any // page is read. // - **The service over the real kernel services**, with the two parts that -// need a browser or the auth mint stood in by recording doubles: the page, -// record and files refusals in the ruled order, and a successful archive — -// the PDF lands as one committed `sys_file` and one `sys_attachment` on the -// invoice, in the caller's organization, with the session revoked after it. -// The engine itself is pinned against a real Chromium on both placements in -// `@objectstack/service-print`'s own suite; the console route it loads is -// the console's. +// need a browser or the auth mint stood in by recording doubles: the page +// and record refusals in the ruled order, and a successful print — the PDF +// handed back under the invoice's display name, with the session revoked +// after it, and no row written. The engine itself is pinned against a real +// Chromium on both placements in `@objectstack/service-print`'s own suite; +// the console route it loads is the console's. // // The boot keeps the showcase's own default profile, as `objectstack serve` // wires it, and the member holds the app's `showcase_contributor`. The showcase's print page is `showcase_invoice_document`, the invoice's -// default record page; `showcase_invoice` declares `enable.files` for it, and -// its select RLS (`owner == current_user.email`) is what hides another user's -// invoice from a contributor. +// default record page; its select RLS (`owner == current_user.email`) is what +// hides another user's invoice from a contributor. The app's `showcase_auditor` +// reads every invoice and edits none: read access is the whole permission a +// print asks, so the auditor prints. // // A second member, `print-attacher`, holds the contributor's set plus the one // grant an app ships when it lets members attach files: `sys_attachment` -// read and create, and nothing on `sys_file`. Their print archives as THEIR -// write — the attachment names them — while `sys_file` stays unreadable to -// them through the data engine. +// read and create, and nothing on `sys_file`. Their print writes nothing +// either: the grant is never used by a print. import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; @@ -51,12 +53,7 @@ import { type IPrintService, type PrintEngine, } from '../../../services/service-print/src/print-service.js'; -import { - FILE_ATTACHMENT_SERVICE, - type IAuthService, - type IDataEngine, - type IFileAttachmentService, -} from '@objectstack/spec/contracts'; +import type { IAuthService, IDataEngine } from '@objectstack/spec/contracts'; const SYS = { isSystem: true } as const; const PAGE = 'showcase_invoice_document'; @@ -75,6 +72,14 @@ interface Refusal { status: unknown; } +/** How many `sys_file` and `sys_attachment` rows exist: a print changes neither. */ +async function storedRows(ql: IDataEngine): Promise<{ files: number; attachments: number }> { + return { + files: (await ql.find('sys_file', {}, { context: SYS })).length, + attachments: (await ql.find('sys_attachment', {}, { context: SYS })).length, + }; +} + async function refusalOf(p: Promise): Promise { try { await p; @@ -163,7 +168,6 @@ describe('print service on a real showcase boot', () => { }, driver: { placement: 'local', probe: async () => ({ version: 'stand-in' }), renderPdf }, getEngine: () => stack.kernel.getService('objectql'), - getAttachments: () => stack.kernel.getService(FILE_ATTACHMENT_SERVICE), getMinter: () => ({ mint }), }); await service.probe(); @@ -192,11 +196,11 @@ describe('print service on a real showcase boot', () => { it('refuses a print 503 for a signed-in user, and 403 for the system context first', async () => { const ctx = await stack.contextFor(memberToken); - expect(await refusalOf(plugin.printRecordToFile(request(ownInvoice), ctx))).toEqual({ + expect(await refusalOf(plugin.printRecordToPdf(request(ownInvoice), ctx))).toEqual({ code: 'SERVICE_UNAVAILABLE', status: 503, }); - expect(await refusalOf(plugin.printRecordToFile(request(ownInvoice), SYS))).toEqual({ + expect(await refusalOf(plugin.printRecordToPdf(request(ownInvoice), SYS))).toEqual({ code: 'PERMISSION_DENIED', status: 403, }); @@ -204,13 +208,13 @@ describe('print service on a real showcase boot', () => { }); describe('the service over the real kernel services', () => { - it('is ready once the archive, metadata and data services are found', () => { + it('is ready once the metadata and data services are found', () => { expect(service.status()).toMatchObject({ state: 'ready' }); }); it('an unknown page: RESOURCE_NOT_FOUND / 404', async () => { const ctx = await stack.contextFor(memberToken); - expect(await refusalOf(service.printRecordToFile(request(ownInvoice, 'showcase_no_such_page'), ctx))).toEqual({ + expect(await refusalOf(service.printRecordToPdf(request(ownInvoice, 'showcase_no_such_page'), ctx))).toEqual({ code: 'RESOURCE_NOT_FOUND', status: 404, }); @@ -220,7 +224,7 @@ describe('print service on a real showcase boot', () => { const ctx = await stack.contextFor(memberToken); const [task] = await ql.find('showcase_task', { limit: 1 }, { context: SYS }); expect( - await refusalOf(service.printRecordToFile(request(String(task.id), 'showcase_task_detail', 'showcase_task'), ctx)), + await refusalOf(service.printRecordToPdf(request(String(task.id), 'showcase_task_detail', 'showcase_task'), ctx)), ).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); }); @@ -231,7 +235,7 @@ describe('print service on a real showcase boot', () => { expect(await ql.findOne('showcase_invoice', { where: { id: othersInvoice } }, { context: SYS })).not.toBeNull(); mint.mockClear(); renderPdf.mockClear(); - expect(await refusalOf(service.printRecordToFile(request(othersInvoice), ctx))).toEqual({ + expect(await refusalOf(service.printRecordToPdf(request(othersInvoice), ctx))).toEqual({ code: 'RECORD_NOT_FOUND', status: 404, }); @@ -239,82 +243,64 @@ describe('print service on a real showcase boot', () => { expect(renderPdf).not.toHaveBeenCalled(); }); - it('a reader who can read the invoice but may not attach to it: refused with the archive’s own answer, before any mint or render', async () => { + it('a reader who can read the invoice but may not edit it prints it: read access is the whole permission', async () => { const ctx = await stack.contextFor(auditorToken); - // Control: the auditor really reads the invoice, so this is the attach rule and not the read. + // Controls: the auditor really reads the invoice, and really may not edit it. expect(await ql.findOne('showcase_invoice', { where: { id: ownInvoice } }, { context: ctx })).not.toBeNull(); + // (the edit is refused or reaches no row: either way the invoice is unchanged). + await ql.update('showcase_invoice', { id: ownInvoice, name: 'INV-PRINT-OWN-EDITED' }, { context: ctx }).catch(() => undefined); + expect((await ql.findOne('showcase_invoice', { where: { id: ownInvoice } }, { context: SYS }))?.name).toBe('INV-PRINT-OWN'); + const before = await storedRows(ql); mint.mockClear(); renderPdf.mockClear(); - // The auditor holds attachment create through the member baseline (the - // storage service's own set, `attachment-member-grant.ts`), so the - // insert passes the object grant and the attach rule answers: the - // auditor may read the invoice but not edit it. Asked before the render. - expect(await refusalOf(service.printRecordToFile(request(ownInvoice), ctx))).toEqual({ - code: 'ATTACHMENT_PARENT_ACCESS', - status: 403, - }); - expect(mint).not.toHaveBeenCalled(); - expect(renderPdf).not.toHaveBeenCalled(); + const out = await service.printRecordToPdf(request(ownInvoice), ctx); + expect(Buffer.from(out.pdf).equals(PDF)).toBe(true); + expect(out).toMatchObject({ size: PDF.byteLength, filename: 'INV-PRINT-OWN.pdf', contentType: 'application/pdf' }); + expect(mint).toHaveBeenCalledWith(ctx, 60); + expect(renderPdf).toHaveBeenCalledTimes(1); + expect(await storedRows(ql)).toEqual(before); }); - it('archives the PDF as one committed sys_file and one sys_attachment, both naming the requester', async () => { + it('hands the PDF back under the invoice’s display name and writes no sys_file and no sys_attachment', async () => { const ctx = await stack.contextFor(adminToken); + const before = await storedRows(ql); mint.mockClear(); revoke.mockClear(); - const out = await service.printRecordToFile(request(ownInvoice), ctx); + const out = await service.printRecordToPdf(request(ownInvoice), ctx); expect(mint).toHaveBeenCalledWith(ctx, 60); expect(renderPdf).toHaveBeenCalledWith( expect.objectContaining({ url: `http://127.0.0.1:1/_console/apps/showcase/showcase_invoice/record/${ownInvoice}` }), ); expect(revoke).toHaveBeenCalledTimes(1); // No filename in the request: the PDF is named from the invoice's display name (ADR-0079), its number. - expect(out).toMatchObject({ size: PDF.byteLength, filename: 'INV-PRINT-OWN.pdf' }); - - const file = await ql.findOne('sys_file', { where: { id: out.fileId } }, { context: SYS }); - expect(file).toMatchObject({ status: 'committed', mime_type: 'application/pdf', size: PDF.byteLength, scope: 'attachments' }); - const attachment = await ql.findOne('sys_attachment', { where: { id: out.attachmentId } }, { context: SYS }); - expect(attachment).toMatchObject({ parent_object: 'showcase_invoice', parent_id: ownInvoice, file_id: out.fileId }); - // Attached AS THE CALLER: both rows name the requester. - expect(file!.owner_id).toBe(ctx.userId); - expect(attachment!.uploaded_by).toBe(ctx.userId); + expect(out).toMatchObject({ size: PDF.byteLength, filename: 'INV-PRINT-OWN.pdf', contentType: 'application/pdf' }); + expect(Buffer.from(out.pdf).equals(PDF)).toBe(true); + expect(out).not.toHaveProperty('attachmentId'); + expect(out).not.toHaveProperty('fileId'); + expect(await storedRows(ql)).toEqual(before); + expect( + await ql.find('sys_attachment', { where: { parent_object: 'showcase_invoice', parent_id: ownInvoice } }, { context: SYS }), + ).toEqual([]); }); - it('a second print of the same invoice carries the same name and is a second attachment: neither replaces the other', async () => { + it('two prints of the same invoice answer the same name and still write nothing', async () => { const ctx = await stack.contextFor(adminToken); - const first = await service.printRecordToFile(request(ownInvoice), ctx); - const second = await service.printRecordToFile(request(ownInvoice), ctx); + const before = await storedRows(ql); + const first = await service.printRecordToPdf(request(ownInvoice), ctx); + const second = await service.printRecordToPdf(request(ownInvoice), ctx); expect(second.filename).toBe(first.filename); - expect(second.fileId).not.toBe(first.fileId); - expect(second.attachmentId).not.toBe(first.attachmentId); - const named = await ql.find( - 'sys_attachment', - { where: { parent_object: 'showcase_invoice', parent_id: ownInvoice, file_name: first.filename } }, - { context: SYS }, - ); - const ids = named.map((row) => String(row.id)); - expect(ids).toEqual(expect.arrayContaining([first.attachmentId, second.attachmentId])); - for (const fileId of [first.fileId, second.fileId]) { - expect(await ql.findOne('sys_file', { where: { id: fileId } }, { context: SYS })).toMatchObject({ status: 'committed' }); - } + expect(await storedRows(ql)).toEqual(before); }); - it('a member who may attach files archives their own invoice: the attachment is their write, and sys_file stays unreadable to them', async () => { + it('a member who may attach files prints their own invoice: the grant goes unused, nothing is written', async () => { const ctx = await stack.contextFor(attacherToken); // Preconditions: the member reads their invoice, and is refused a read of `sys_file`. expect(await ql.findOne('showcase_invoice', { where: { id: attacherInvoice } }, { context: ctx })).not.toBeNull(); expect(await refusalOf(ql.find('sys_file', { limit: 1 }, { context: ctx }))).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); - const out = await service.printRecordToFile(request(attacherInvoice), ctx); - const file = await ql.findOne('sys_file', { where: { id: out.fileId } }, { context: SYS }); - expect(file).toMatchObject({ status: 'committed', mime_type: 'application/pdf', scope: 'attachments', owner_id: ctx.userId }); - const attachment = await ql.findOne('sys_attachment', { where: { id: out.attachmentId } }, { context: SYS }); - expect(attachment).toMatchObject({ - parent_object: 'showcase_invoice', parent_id: attacherInvoice, file_id: out.fileId, uploaded_by: ctx.userId, - }); - // Still not readable after the archive: the print widened no read. - expect(await refusalOf(ql.findOne('sys_file', { where: { id: out.fileId } }, { context: ctx }))).toEqual({ - code: 'PERMISSION_DENIED', - status: 403, - }); + const before = await storedRows(ql); + const out = await service.printRecordToPdf(request(attacherInvoice), ctx); + expect(out.filename).toBe('INV-PRINT-ATTACHER.pdf'); + expect(await storedRows(ql)).toEqual(before); }); it('control: the same member’s own sys_attachment insert, naming a file they own and cannot read, is refused reference_not_found', async () => { @@ -366,11 +352,10 @@ describe('print service on a real showcase boot', () => { }, }, getEngine: () => stack.kernel.getService('objectql'), - getAttachments: () => stack.kernel.getService(FILE_ATTACHMENT_SERVICE), getMinter: () => minter, }); await real.probe(); - await real.printRecordToFile(request(ownInvoice), ctx); + await real.printRecordToPdf(request(ownInvoice), ctx); expect((duringRender as { user?: { id?: string } } | null)?.user?.id).toBe(ctx.userId); const after = await asSession(seenCookie!); expect([after.status, ((await after.json()) as { error?: { code?: string } }).error?.code]).toEqual([401, 'UNAUTHENTICATED']); diff --git a/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts b/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts index 8db7c52bd34..a7f930e5fbb 100644 --- a/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts +++ b/packages/qa/dogfood/test/print-service-named-page.dogfood.test.ts @@ -10,8 +10,8 @@ // kernel services, then: // // - prints a project on the brief, rendering the console's named record-page -// route (`…/record/ID/page/PAGE`, `RECORD_NAMED_PAGE_ROUTE`), and archives -// the PDF on the project as the requester; +// route (`…/record/ID/page/PAGE`, `RECORD_NAMED_PAGE_ROUTE`), and hands the +// PDF back under the project's display name, writing no attachment; // - still refuses the working page (it declares no `print`) and a print page // of another object, `VALIDATION_ERROR` / 400, before anything is minted. // @@ -29,7 +29,7 @@ import { AuditPlugin } from '@objectstack/plugin-audit'; import { bootShowcase } from './showcase-boot.js'; import { PrintServicePlugin } from '../../../services/service-print/src/print-service-plugin.js'; import { PrintService, type PrintEngine } from '../../../services/service-print/src/print-service.js'; -import { FILE_ATTACHMENT_SERVICE, type IDataEngine, type IFileAttachmentService } from '@objectstack/spec/contracts'; +import type { IDataEngine } from '@objectstack/spec/contracts'; import { PROJECT_BRIEF_PAGE } from './print-named-page.fixture.js'; const SYS = { isSystem: true } as const; @@ -92,7 +92,6 @@ describe('a record printed on a print page that is not its object’s default re placement: { state: 'configured', resolved: { placement: 'local', target: '/stand-in/chromium', consoleUrl: CONSOLE } }, driver: { placement: 'local', probe: async () => ({ version: 'stand-in' }), renderPdf }, getEngine: () => stack.kernel.getService('objectql'), - getAttachments: () => stack.kernel.getService(FILE_ATTACHMENT_SERVICE), getMinter: () => ({ mint }), }); await service.probe(); @@ -121,28 +120,30 @@ describe('a record printed on a print page that is not its object’s default re expect(brief?.isDefault).toBeUndefined(); }); - it('prints the project on the brief through the console’s named record-page route, archived as the requester', async () => { + it('prints the project on the brief through the console’s named record-page route, and writes no attachment', async () => { const ctx = await stack.contextFor(await stack.signIn()); mint.mockClear(); revoke.mockClear(); renderPdf.mockClear(); - const out = await service.printRecordToFile(request(PROJECT_BRIEF_PAGE.name), ctx); + const out = await service.printRecordToPdf(request(PROJECT_BRIEF_PAGE.name), ctx); expect(renderPdf).toHaveBeenCalledTimes(1); expect(renderPdf).toHaveBeenCalledWith( expect.objectContaining({ url: `${CONSOLE}/apps/showcase/showcase_project/record/${project}/page/${PROJECT_BRIEF_PAGE.name}` }), ); expect(revoke).toHaveBeenCalledTimes(1); // No filename in the request: the PDF is named from the project's display name (ADR-0079). - expect(out).toMatchObject({ size: PDF.byteLength, filename: `${projectName}.pdf` }); - const attachment = await ql.findOne('sys_attachment', { where: { id: out.attachmentId } }, { context: SYS }); - expect(attachment).toMatchObject({ parent_object: 'showcase_project', parent_id: project, file_id: out.fileId, uploaded_by: ctx.userId }); + expect(out).toMatchObject({ size: PDF.byteLength, filename: `${projectName}.pdf`, contentType: 'application/pdf' }); + expect(Buffer.from(out.pdf).equals(PDF)).toBe(true); + expect( + await ql.find('sys_attachment', { where: { parent_object: 'showcase_project', parent_id: project } }, { context: SYS }), + ).toEqual([]); }); it('the working default page, which declares no print, is still refused: VALIDATION_ERROR / 400, nothing minted', async () => { const ctx = await stack.contextFor(await stack.signIn()); mint.mockClear(); renderPdf.mockClear(); - expect(await refusalOf(service.printRecordToFile(request('showcase_project_detail'), ctx))).toEqual({ + expect(await refusalOf(service.printRecordToPdf(request('showcase_project_detail'), ctx))).toEqual({ code: 'VALIDATION_ERROR', status: 400, }); @@ -156,7 +157,7 @@ describe('a record printed on a print page that is not its object’s default re mint.mockClear(); renderPdf.mockClear(); expect( - await refusalOf(service.printRecordToFile(request(PROJECT_BRIEF_PAGE.name, 'showcase_invoice', String(invoice!.id)), ctx)), + await refusalOf(service.printRecordToPdf(request(PROJECT_BRIEF_PAGE.name, 'showcase_invoice', String(invoice!.id)), ctx)), ).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); expect(mint).not.toHaveBeenCalled(); expect(renderPdf).not.toHaveBeenCalled(); diff --git a/packages/qa/dogfood/test/print-service-render.dogfood.test.ts b/packages/qa/dogfood/test/print-service-render.dogfood.test.ts index 15deea8177f..02431d479c3 100644 --- a/packages/qa/dogfood/test/print-service-render.dogfood.test.ts +++ b/packages/qa/dogfood/test/print-service-render.dogfood.test.ts @@ -3,8 +3,8 @@ // The print service end to end, on a real showcase boot: `PrintServicePlugin` // mints a session for the requesting user (`IAuthService.mintPrincipalSession`), // headless Chromium loads the REAL console with only that session, prints the -// invoice's print page, and the PDF is archived on the invoice as the requester -// — on BOTH placements: +// invoice's print page, and the PDF is handed back to the requester, with +// nothing stored — on BOTH placements: // // - **local** — `chromiumPath`, the plugin launches the executable; // - **remote** — `browserEndpoint`: this test spawns the same executable with @@ -14,10 +14,9 @@ // Per placement it pins: // - the console booted under the requester, never the system (every // `get-session` the browser made answered the requester); -// - a real PDF archived as one `sys_attachment` on the invoice, with -// `sys_file.owner_id` and `sys_attachment.uploaded_by` the requester; +// - a real PDF handed back, and no `sys_attachment` written on the invoice; // - the minted session gone after the print — after a success and after a -// forced failure (the archive's byte store refusing after the render); +// forced failure (a render whose page never loads); // - the minted cookie in no refusal message; // - a project printed on a print page that is NOT its object's default record // page (the brief of `print-named-page.fixture.ts`, saved through the @@ -40,7 +39,7 @@ import { fileURLToPath } from 'node:url'; import type { VerifyStack } from '@objectstack/verify'; import { StorageServicePlugin } from '@objectstack/service-storage'; import { AuditPlugin } from '@objectstack/plugin-audit'; -import type { IAuthService, IDataEngine, IStorageService, PrincipalSession } from '@objectstack/spec/contracts'; +import type { IAuthService, IDataEngine, PrincipalSession } from '@objectstack/spec/contracts'; import { bootShowcase } from './showcase-boot.js'; import { PROJECT_BRIEF_PAGE } from './print-named-page.fixture.js'; import { createConsoleStaticPlugin } from '../../../cli/src/utils/console.js'; @@ -139,6 +138,8 @@ for (const placement of ['local', 'remote'] as const) { const sessionUsers: Array = []; /** Each session the plugin minted: its cookie, captured to prove it is gone afterwards. Never printed. */ const minted: Array = []; + /** While set, the door the browser reaches drops every connection: the render fails at its first load. */ + let dropConnections = false; beforeAll(async () => { const port = await freePort(); @@ -158,6 +159,10 @@ for (const placement of ['local', 'remote'] as const) { // The real HTTP door the browser reaches: every request handed to the // booted stack as it arrives, every answer handed back as it is. server = createServer(async (req, res) => { + if (dropConnections) { + req.socket.destroy(); + return; + } const chunks: Buffer[] = []; for await (const c of req) chunks.push(c as Buffer); const headers: Record = {}; @@ -225,26 +230,23 @@ for (const placement of ['local', 'remote'] as const) { expect(print.status()).toMatchObject({ state: 'ready', placement }); }); - it('prints the invoice through the real console as the requester, archives it as theirs, and the session is gone', async () => { + it('prints the invoice through the real console as the requester, hands the PDF back, stores nothing, and the session is gone', async () => { const token = await stack.signIn(); const ctx = await stack.contextFor(token); const invoice = await newInvoice(`INV-RENDER-${placement}`, 'admin@objectos.ai'); sessionUsers.length = 0; minted.length = 0; - const out = await print.printRecordToFile({ app: APP, object: 'showcase_invoice', recordId: invoice, page: PAGE }, ctx); + const out = await print.printRecordToPdf({ app: APP, object: 'showcase_invoice', recordId: invoice, page: PAGE }, ctx); // The console booted under the requester, and only them. expect(sessionUsers.length).toBeGreaterThan(0); expect(new Set(sessionUsers)).toEqual(new Set([ctx.userId])); - // A real PDF, archived on the invoice as the requester's. - const file = await ql.findOne('sys_file', { where: { id: out.fileId } }, { context: SYS }); - const attachment = await ql.findOne('sys_attachment', { where: { id: out.attachmentId } }, { context: SYS }); - expect(file).toMatchObject({ status: 'committed', mime_type: 'application/pdf', owner_id: ctx.userId }); - expect(attachment).toMatchObject({ parent_object: 'showcase_invoice', parent_id: invoice, file_id: out.fileId, uploaded_by: ctx.userId }); - const bytes = await stack.kernel.getService('storage').download(String(file!.key)); - expect(bytes.subarray(0, 5).toString('latin1')).toBe('%PDF-'); - expect(bytes.byteLength).toBe(out.size); + // A real PDF, handed back; nothing stored on the invoice. + expect(Buffer.from(out.pdf).subarray(0, 5).toString('latin1')).toBe('%PDF-'); + expect(out.pdf.byteLength).toBe(out.size); + expect(out.contentType).toBe('application/pdf'); + expect(await ql.find('sys_attachment', { where: { parent_id: invoice } }, { context: SYS })).toEqual([]); // The minted session is gone. expect(minted).toHaveLength(1); expect(await opensASession(minted[0]!)).toEqual([401, 'UNAUTHENTICATED']); @@ -258,38 +260,33 @@ for (const placement of ['local', 'remote'] as const) { sessionUsers.length = 0; minted.length = 0; - const out = await print.printRecordToFile( + const out = await print.printRecordToPdf( { app: APP, object: 'showcase_project', recordId: projectId, page: PROJECT_BRIEF_PAGE.name }, ctx, ); expect(new Set(sessionUsers)).toEqual(new Set([ctx.userId])); - const file = await ql.findOne('sys_file', { where: { id: out.fileId } }, { context: SYS }); - const attachment = await ql.findOne('sys_attachment', { where: { id: out.attachmentId } }, { context: SYS }); - expect(file).toMatchObject({ status: 'committed', mime_type: 'application/pdf', owner_id: ctx.userId }); - expect(attachment).toMatchObject({ parent_object: 'showcase_project', parent_id: projectId, uploaded_by: ctx.userId }); - const bytes = await stack.kernel.getService('storage').download(String(file!.key)); - expect(bytes.subarray(0, 5).toString('latin1')).toBe('%PDF-'); + expect(Buffer.from(out.pdf).subarray(0, 5).toString('latin1')).toBe('%PDF-'); + expect(await ql.find('sys_attachment', { where: { parent_id: projectId } }, { context: SYS })).toEqual([]); expect(minted).toHaveLength(1); expect(await opensASession(minted[0]!)).toEqual([401, 'UNAUTHENTICATED']); }, 120_000); - it('a print that fails after the render still revokes the session, stores nothing, and names no credential', async () => { + it('a print whose render fails still revokes the session, stores nothing, and names no credential', async () => { const token = await stack.signIn(); const ctx = await stack.contextFor(token); const invoice = await newInvoice(`INV-RENDER-FAIL-${placement}`, 'admin@objectos.ai'); minted.length = 0; - // Force the failure after the render: the archive's byte store refuses the upload once. - const storage = stack.kernel.getService('storage'); - const upload = storage.upload.bind(storage); - storage.upload = async () => { - storage.upload = upload; - throw new Error('forced byte-store failure'); - }; - - const r = await refusalOf(print.printRecordToFile({ app: APP, object: 'showcase_invoice', recordId: invoice, page: PAGE }, ctx)); + // Force the render to fail: the door the browser loads the console from drops every connection. + dropConnections = true; + let r: Refusal; + try { + r = await refusalOf(print.printRecordToPdf({ app: APP, object: 'showcase_invoice', recordId: invoice, page: PAGE }, ctx)); + } finally { + dropConnections = false; + } - expect(r.message).toContain('forced byte-store failure'); + expect(r.status, r.message).toBeGreaterThanOrEqual(500); expect(minted).toHaveLength(1); expect(r.message).not.toContain(minted[0]!.value); expect(await opensASession(minted[0]!)).toEqual([401, 'UNAUTHENTICATED']); diff --git a/packages/qa/http-conformance/src/action-door-attachment-38894.conformance.test.ts b/packages/qa/http-conformance/src/action-door-attachment-38894.conformance.test.ts index f3a2b607bb5..8083190ffc7 100644 --- a/packages/qa/http-conformance/src/action-door-attachment-38894.conformance.test.ts +++ b/packages/qa/http-conformance/src/action-door-attachment-38894.conformance.test.ts @@ -23,6 +23,14 @@ * answers `502`; a caller the door refuses gets the refusal and the target is * never called. The door's gates and the MCP door's `502` are pinned over * fakes in `packages/runtime/src/domains/api-action-forward.test.ts`. + * + * The print action end to end: the real `PrintServicePlugin` mounts its door + * (`POST /api/v1/print/records`, `service-print`'s own route), and a declared + * print action shaped as an app declares one (`recordIdParam` plus + * `bodyExtra`) reaches it through the REST action door. Only the renderer is + * replaced (`printRecordToPdf` on the composed service, since no browser runs + * here): the route's own answer, `Content-Type` and `Content-Disposition` + * included, is what arrives. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -32,6 +40,7 @@ import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { createDispatcherPlugin } from '@objectstack/runtime'; import { createHonoApp } from '@objectstack/hono'; +import { PrintServicePlugin, type IPrintService, type PrintRecordRequest } from '@objectstack/service-print'; import type { IHttpServer } from '@objectstack/spec/contracts'; import { installDefaultOrganization } from './default-organization.testkit.js'; @@ -40,8 +49,18 @@ const API = '/api/v1'; const OBJECT = 'c38894_doc'; const PDF = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x00, 0xff, 0xfe, 0x80, 0x0d, 0x0a, 0xc3, 0x28, 0x7f]); const DISPOSITION = 'attachment; filename="invoice.pdf"; filename*=UTF-8\'\'%E5%8F%91%E7%A5%A8.pdf'; +const PRINT_ENV_KEYS = ['OS_PRINT_CHROMIUM_PATH', 'OS_PRINT_BROWSER_ENDPOINT', 'OS_PRINT_CONSOLE_URL']; +/** The print action's constant body fields, as the showcase's Generate PDF declares them. */ +const PRINT_BODY = { app: 'com.test.c38894', object: OBJECT, page: 'c38894_doc_print' }; +/** The name the stub print gives its PDF, and the disposition the print route writes for it. */ +const PRINT_FILENAME = '发票 INV-1.pdf'; +const PRINT_DISPOSITION = 'attachment; filename="__ INV-1.pdf"; filename*=UTF-8\'\'%E5%8F%91%E7%A5%A8%20INV-1.pdf'; const ACTIONS = [ + { + name: 'print_pdf', label: 'Generate PDF', objectName: OBJECT, type: 'api', method: 'POST', target: `${API}/print/records`, + execution: 'perRecord', recordIdParam: 'recordId', bodyExtra: PRINT_BODY, + }, { name: 'download_pdf', label: 'Download', objectName: OBJECT, type: 'api', method: 'POST', target: `${API}/c38894/file` }, { name: 'download_csv', label: 'CSV', objectName: OBJECT, type: 'api', method: 'POST', target: `${API}/c38894/csv` }, { name: 'export_json', label: 'JSON export', objectName: OBJECT, type: 'api', method: 'POST', target: `${API}/c38894/json` }, @@ -127,10 +146,15 @@ interface Door { kernel: LiteKernel; send: (path: string, init?: RequestInit) => Promise; targetCalls: () => number; + /** Every print the composed print service was asked for, with the caller it ran as. */ + prints: Array<{ request: PrintRecordRequest; userId: unknown }>; + /** A record of {@link OBJECT} to print. */ + recordId: string; } async function boot(shape: 'self-hosted' | 'catch-all'): Promise { let calls = 0; + const prints: Door['prints'] = []; const kernel = new LiteKernel(); kernel.use(new ObjectQLPlugin()); // Every request is a signed-in member (the transport is under test, not sign-in). @@ -172,8 +196,18 @@ async function boot(shape: 'self-hosted' | 'catch-all'): Promise { }, }; kernel.use(target); + // The real print door, mounted on `http.server` at `kernel:ready`. + kernel.use(new PrintServicePlugin()); await kernel.bootstrap(); + // No browser runs here: the composed service's renderer is replaced, and + // everything around it (the print route, its answer and headers) is real. + const print = kernel.getService('print'); + print.printRecordToPdf = async (request, context) => { + prints.push({ request, userId: context.userId }); + return { pdf: PDF, size: PDF.byteLength, filename: PRINT_FILENAME, contentType: 'application/pdf' }; + }; + const ql = kernel.getService('objectql'); const driver = new SqliteWasmDriver({ filename: ':memory:' }); await driver.connect(); @@ -182,6 +216,7 @@ async function boot(shape: 'self-hosted' | 'catch-all'): Promise { await ql.syncObjectSchema(OBJECT); for (const o of authzResolverObjects) ql.registry.registerObject(o.def as never, o.owner); await installDefaultOrganization(ql as never); + const recordId = String(((await ql.insert(OBJECT, { title: 'INV-1' })) as { id: unknown }).id); let send: Door['send']; if (shape === 'catch-all') { @@ -192,7 +227,7 @@ async function boot(shape: 'self-hosted' | 'catch-all'): Promise { const base = `http://127.0.0.1:${server.getPort!()}`; send = (path, init) => fetch(`${base}${path}`, init); } - return { kernel, send, targetCalls: () => calls }; + return { kernel, send, targetCalls: () => calls, prints, recordId }; } const call = (body: unknown = {}): RequestInit => ({ @@ -203,9 +238,36 @@ const call = (body: unknown = {}): RequestInit => ({ describe.each(['self-hosted', 'catch-all'] as const)('[#38894] the REST action door relays an attachment on the %s transport', (shape) => { let door: Door; - beforeAll(async () => { door = await boot(shape); }, BOOT_TIMEOUT); + const savedEnv: Record = {}; + beforeAll(async () => { + for (const k of PRINT_ENV_KEYS) { + savedEnv[k] = process.env[k]; + delete process.env[k]; + } + door = await boot(shape); + }, BOOT_TIMEOUT); afterAll(async () => { await Promise.race([door?.kernel.shutdown(), new Promise((resolve) => setTimeout(resolve, 10_000))]); + for (const k of PRINT_ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } + }); + + it('a declared print action answers the print route\'s PDF as an attachment', async () => { + const before = door.prints.length; + const res = await door.send(`${API}/actions/${OBJECT}/print_pdf`, call({ recordId: door.recordId })); + const bytes = new Uint8Array(await res.arrayBuffer()); + expect(res.status, new TextDecoder().decode(bytes)).toBe(200); + expect(bytes).toEqual(PDF); + expect(res.headers.get('content-type')).toBe('application/pdf'); + expect(res.headers.get('content-disposition')).toBe(PRINT_DISPOSITION); + expect(res.headers.get('cache-control')).toBe('no-store'); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + // The route printed exactly the request the declaration assembles, as the caller. + expect(door.prints.slice(before)).toEqual([ + { request: { ...PRINT_BODY, recordId: door.recordId }, userId: 'u_member' }, + ]); }); it('a 2xx attachment arrives with identical bytes, status and file headers', async () => { diff --git a/packages/runtime/src/domains/print.ts b/packages/runtime/src/domains/print.ts index 2688bc083bd..c62e19798a6 100644 --- a/packages/runtime/src/domains/print.ts +++ b/packages/runtime/src/domains/print.ts @@ -7,7 +7,8 @@ * it forwards. * * `POST /print/records` prints a record's print page to a PDF as the caller - * and archives it on the record; a console `type: 'api'` action targets it. A + * and answers the PDF as a download; this domain returns that binary + * `Response` unread, as it returns every answer of the door. A * self-hosted kernel serves it already: service-print mounts it on the * kernel's `http.server` (`registerPrintRoutes`). A hosted tenant kernel owns * no `http.server`, so the host's `createHonoApp` catch-all — and the diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 4d0a072a8e6..20cabb6aa84 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -748,7 +748,7 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ // ── print door (the hosted door) ────────────────────────────────────────── { route: 'POST /print/records', domain: '/print', disposition: 'server-only', - note: 'the print door: print a record\'s print page to a PDF as the caller and archive it on the record; a console type:\'api\' action targets it, and the /actions door forwards that action in-process to this path. Forwarded with its body UNREAD to the REQUEST kernel\'s print service (IPrintDoorService.handlePrintDoor; service-print builds it in init), read per request and never from the host kernel\'s scoped fallback, and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller, every refusal (an unconfigured print engine is the door\'s own 503 SERVICE_UNAVAILABLE) and every answer are the mount\'s. Same credential, preamble-gate, absence and body notes as the personal-view row: a kernel that composes no print service answers 501 NOT_IMPLEMENTED, never the dispatcher\'s 404 ROUTE_NOT_FOUND. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from service-print\'s own mount on its http.server. NOT JS-SDK surface here: the mount\'s own ledger row (service-print print-route-ledger.ts) carries the disposition. Pinned in `domains/own-door-bridge.test.ts`' }, + note: 'the print door: print a record\'s print page to a PDF as the caller and answer the PDF itself as a download, storing nothing. A declared type:\'api\' action that targets it is forwarded in-process by the /actions door, which relays the PDF byte for byte as an attachment (MCP run_action answers it 502). Forwarded with its body UNREAD to the REQUEST kernel\'s print service (IPrintDoorService.handlePrintDoor; service-print builds it in init), read per request and never from the host kernel\'s scoped fallback, and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller, every refusal (an unconfigured print engine is the door\'s own 503 SERVICE_UNAVAILABLE) and every answer are the mount\'s. Same credential, preamble-gate, absence and body notes as the personal-view row: a kernel that composes no print service answers 501 NOT_IMPLEMENTED, never the dispatcher\'s 404 ROUTE_NOT_FOUND. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from service-print\'s own mount on its http.server. NOT JS-SDK surface here: the mount\'s own ledger row (service-print print-route-ledger.ts) carries the disposition. Pinned in `domains/own-door-bridge.test.ts`' }, // ── ai (dynamic route table, owned by another repo) ─────────────────────── { route: '* /ai/**', domain: '/ai', disposition: 'dynamic', diff --git a/packages/services/service-print/README.md b/packages/services/service-print/README.md index 8c391daa399..3b496f68d50 100644 --- a/packages/services/service-print/README.md +++ b/packages/services/service-print/README.md @@ -1,7 +1,9 @@ # @objectstack/service-print Prints a record's print page to a PDF in headless Chromium, as the requesting -user, and archives it as a file attached to the record. +user, and hands the PDF back as a download. A print stores nothing: no file +and no attachment on the record. Keeping a PDF on the record is a separate, +explicit act (an upload, or an action of the app's own). ```ts import { PrintServicePlugin } from '@objectstack/service-print'; @@ -20,11 +22,15 @@ absent, misconfigured or unreachable one once, with the setting to fix. ```ts const print = kernel.getService('print'); -await print.printRecordToFile({ app, object, recordId, page }, context); +const { pdf, filename } = await print.printRecordToPdf({ app, object, recordId, page }, context); ``` +A print asks one permission: the caller must be able to read the record. + The plugin also mounts `POST /api/v1/print/records` on the kernel's HTTP server: the same request as a JSON body, printed as the signed-in caller, answering -`201` with the stored file. A console `type: 'api'` action targets it. +`200` with the PDF itself (`Content-Type: application/pdf`, +`Content-Disposition: attachment`), which a browser saves as a download. A +refusal is the usual JSON error envelope. Documentation: [Print Pages](https://objectstack.ai/docs/ui/print-pages). diff --git a/packages/services/service-print/package.json b/packages/services/service-print/package.json index 14f12d3fe86..afb0e70b109 100644 --- a/packages/services/service-print/package.json +++ b/packages/services/service-print/package.json @@ -2,7 +2,7 @@ "name": "@objectstack/service-print", "version": "19.0.0-next.3", "license": "Apache-2.0", - "description": "Print Service for ObjectStack — renders a record's print page in headless Chromium under the requesting user's own principal and archives the PDF as a file attached to the record.", + "description": "Print Service for ObjectStack — renders a record's print page in headless Chromium under the requesting user's own principal and answers the PDF as a download; a print stores nothing.", "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -27,7 +27,6 @@ "dependencies": { "@objectstack/core": "workspace:*", "@objectstack/plugin-hono-server": "workspace:*", - "@objectstack/service-storage": "workspace:*", "@objectstack/spec": "workspace:*", "@objectstack/types": "workspace:*", "playwright-core": "1.63.0" diff --git a/packages/services/service-print/src/index.ts b/packages/services/service-print/src/index.ts index c44f039966b..2c7f91d2192 100644 --- a/packages/services/service-print/src/index.ts +++ b/packages/services/service-print/src/index.ts @@ -2,18 +2,19 @@ /** * @objectstack/service-print — print a record's print page to a PDF in - * headless Chromium, as the requesting user, and archive it as a file attached - * to the record. + * headless Chromium, as the requesting user, and hand the PDF back as a + * download. A print stores nothing. */ export { PrintServicePlugin, PRINT_SERVICE, type PrintServicePluginOptions } from './print-service-plugin.js'; export { + PRINT_FILENAME_MAX_CHARS, PRINT_RENDER_TIMEOUT_MS, PRINT_SESSION_TTL_SECONDS, type IPrintService, type PrintEngineStatus, type PrintRecordRequest, - type PrintedRecordFile, + type PrintedRecordPdf, } from './print-service.js'; export { PRINT_CHROMIUM_PATH_ENV, diff --git a/packages/services/service-print/src/print-door-member.test.ts b/packages/services/service-print/src/print-door-member.test.ts index e845cf1781d..78888593359 100644 --- a/packages/services/service-print/src/print-door-member.test.ts +++ b/packages/services/service-print/src/print-door-member.test.ts @@ -16,7 +16,8 @@ import { HonoHttpServer } from '@objectstack/plugin-hono-server'; import { PRINT_SERVICE, PrintServicePlugin } from './print-service-plugin.js'; import type { PrintService } from './print-service.js'; import { PRINT_BROWSER_ENDPOINT_ENV, PRINT_CHROMIUM_PATH_ENV, PRINT_CONSOLE_URL_ENV } from './config.js'; -import { PRINT_RECORDS_ROUTE } from './print-routes.js'; +import { PRINT_RECORDS_ROUTE, registerPrintRoutes, type PrintRoutesDeps } from './print-routes.js'; +import { createPrintDoorMember } from './print-door-member.js'; const ENV_KEYS = [PRINT_CHROMIUM_PATH_ENV, PRINT_BROWSER_ENDPOINT_ENV, PRINT_CONSOLE_URL_ENV]; const saved: Record = {}; @@ -101,3 +102,60 @@ describe('PrintService.handlePrintDoor — the print door for a kernel with no h } }); }); + +describe('PrintService.handlePrintDoor — a print answers the PDF as a download on both faces', () => { + const PDF = Buffer.from('%PDF-1.4 member\n\u00ff\u0000binary tail'); + + /** The door over a print service that answers `PDF`, for a caller whose bearer is `alice`. */ + function deps(): PrintRoutesDeps { + return { + print: { + status: () => ({ state: 'ready', placement: 'local', version: 'stand-in' }), + printRecordToPdf: async () => ({ pdf: PDF, size: PDF.byteLength, filename: '报价单.pdf', contentType: 'application/pdf' }), + }, + getEngine: () => ({ find: async () => [] }), + getAuth: () => + ({ + api: { + getSession: async (input: { headers: Headers }) => + input.headers.get('authorization') === 'Bearer alice' + ? { user: { id: 'usr_alice', email: 'alice@example.test' }, session: { id: 'ses_alice', userId: 'usr_alice' } } + : null, + }, + }) as never, + resolveTenancyPosture: async () => undefined, + }; + } + + function signedIn(): Request { + return new Request(`http://tenant.example.test${PRINT_RECORDS_ROUTE}`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: 'Bearer alice' }, + body: JSON.stringify({ app: 'sales', object: 'invoice', recordId: 'inv_1', page: 'invoice_document' }), + }); + } + + async function download(res: Response) { + return { + status: res.status, + type: res.headers.get('content-type'), + disposition: res.headers.get('content-disposition'), + cache: res.headers.get('cache-control'), + bytes: Buffer.from(await res.arrayBuffer()), + }; + } + + it('the member and the http.server mount answer the same bytes and headers, unchanged', async () => { + const member = createPrintDoorMember((http) => registerPrintRoutes(http, deps())); + const mount = new HonoHttpServer(0); + registerPrintRoutes(mount, deps()); + const viaMember = await download(await member(signedIn())); + const viaMount = await download(await mount.getRawApp().fetch(signedIn())); + expect(viaMember.status).toBe(200); + expect(viaMember.type).toBe('application/pdf'); + expect(viaMember.disposition).toBe(`attachment; filename="___.pdf"; filename*=UTF-8''${encodeURIComponent('报价单.pdf')}`); + expect(viaMember.cache).toBe('no-store'); + expect(viaMember.bytes.equals(PDF), 'the PDF bytes cross the member byte for byte').toBe(true); + expect(viaMember).toEqual(viaMount); + }); +}); diff --git a/packages/services/service-print/src/print-route-ledger.ts b/packages/services/service-print/src/print-route-ledger.ts index ab6af38abc9..bd0c8e03d18 100644 --- a/packages/services/service-print/src/print-route-ledger.ts +++ b/packages/services/service-print/src/print-route-ledger.ts @@ -48,5 +48,5 @@ export interface PrintRouteLedgerEntry { export const PRINT_ROUTE_LEDGER: readonly PrintRouteLedgerEntry[] = [ { route: 'POST /api/v1/print/records', family: 'print', disposition: 'server-only', - note: "print a record's print page to a PDF as the caller and archive it on the record; called by a declared type:'api' console action" }, + note: "print a record's print page to a PDF as the caller and answer the PDF itself as a download, storing nothing; reached directly or as a declared type:'api' action's target, whose PDF the REST action door relays as an attachment (the MCP action door answers it 502)" }, ]; diff --git a/packages/services/service-print/src/print-routes.test.ts b/packages/services/service-print/src/print-routes.test.ts index eb728c8565b..76c6a818523 100644 --- a/packages/services/service-print/src/print-routes.test.ts +++ b/packages/services/service-print/src/print-routes.test.ts @@ -7,18 +7,19 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { ChromiumDriver } from './chromium-driver.js'; import type { PrintPlacementResolution } from './config.js'; import { currentCredentialUseClient, hashApiKey } from '@objectstack/core'; -import { PRINT_RECORDS_ROUTE, registerPrintRoutes } from './print-routes.js'; +import { PRINT_RECORDS_ROUTE, pdfContentDisposition, registerPrintRoutes } from './print-routes.js'; import { PrintService, type IPrintService } from './print-service.js'; /** * The print door, `POST /api/v1/print/records`, driven through the handler it * mounts: the real platform resolver turns the request's bearer into an * execution context, and the real `PrintService` judges the print over - * recording doubles of the data engine, the archive, the mint and the browser. + * recording doubles of the data engine, the mint and the browser. * + * A print answers the PDF itself as a download and writes nothing: the data + * engine double carries every write verb as a trap, and none is ever called. * Each refusal is asserted by its envelope (`code` and `status`, ADR-0112), - * and each one by what it did NOT start: no session minted, no page read, no - * file stored. + * and each one by what it did NOT start: no session minted, no page read. */ const PDF = Buffer.from('%PDF-1.4 door'); @@ -94,24 +95,8 @@ function door(setup: DoorSetup = {}) { }, }; - // The archive: an in-memory `sys_file` / `sys_attachment` store, written as the caller. - const rows = { sys_file: [] as Record[], sys_attachment: [] as Record[] }; - const attachFileAs = vi.fn( - async (input: { parentObject: string; parentId: string; filename: string; data: Buffer }, context: ExecutionContext) => { - const fileId = `file_${rows.sys_file.length + 1}`; - const attachmentId = `att_${rows.sys_attachment.length + 1}`; - rows.sys_file.push({ id: fileId, owner_id: context.userId, name: input.filename, size: input.data.byteLength }); - rows.sys_attachment.push({ - id: attachmentId, - file_id: fileId, - parent_object: input.parentObject, - parent_id: input.parentId, - uploaded_by: context.userId, - }); - return { fileId, attachmentId, size: input.data.byteLength }; - }, - ); - const systemAttachFile = vi.fn(); + // Every write verb the data engine has, as a trap: a print writes nothing. + const writes = { insert: vi.fn(), update: vi.fn(), delete: vi.fn(), upsert: vi.fn() }; const findOne = vi.fn(async (_object: string, query: { where: { id: string } }, opts: { context: ExecutionContext }) => { const row = RECORDS[query.where.id]; return row && row.owner === opts.context.userId ? row : null; @@ -133,16 +118,16 @@ function door(setup: DoorSetup = {}) { getEngine: () => ({ findOne, + ...writes, registry: { getItem: (_type: string, name: string) => (name === PAGE ? page : undefined), getObject: () => ({ name: 'invoice', enable: { files: true } }), }, }) as never, - getAttachments: () => ({ attachFile: systemAttachFile, attachFileAs, assertMayAttach: async () => undefined }) as never, getMinter: () => ({ mint }), }); const service = setup.service ?? real; - const printRecordToFile = vi.spyOn(service, 'printRecordToFile'); + const printRecordToPdf = vi.spyOn(service, 'printRecordToPdf'); registerPrintRoutes(http as never, { print: service, @@ -170,7 +155,11 @@ function door(setup: DoorSetup = {}) { ) { const handler = handlers.get(`POST ${PRINT_RECORDS_ROUTE}`); if (!handler) throw new Error('the door mounted no POST handler at its route'); - const answer: { status: number; body: any } = { status: 0, body: undefined }; + const answer: { status: number; body: any; bytes?: Uint8Array; headers: Record } = { + status: 0, + body: undefined, + headers: {}, + }; const res = { status: (code: number) => { answer.status = code; @@ -179,8 +168,13 @@ function door(setup: DoorSetup = {}) { json: (body: unknown) => { answer.body = body; }, - header: () => res, - send: () => undefined, + header: (name: string, value: string) => { + answer.headers[name.toLowerCase()] = value; + return res; + }, + send: (bytes: Uint8Array) => { + answer.bytes = bytes; + }, }; await handler( { @@ -193,11 +187,13 @@ function door(setup: DoorSetup = {}) { }, res, ); - expect(envelopeViolations(answer.body), JSON.stringify(answer.body)).toEqual([]); + // A JSON answer is an envelope; a PDF answer is bytes and never both. + if (answer.bytes === undefined) expect(envelopeViolations(answer.body), JSON.stringify(answer.body)).toEqual([]); + else expect(answer.body).toBeUndefined(); return answer; } - return { call, real, ready: () => real.probe(), rows, mint, revoke, renderPdf, findOne, attachFileAs, systemAttachFile, printRecordToFile, auth, sessionReads }; + return { call, real, ready: () => real.probe(), writes, mint, revoke, renderPdf, findOne, printRecordToPdf, auth, sessionReads }; } type Door = ReturnType; @@ -225,13 +221,17 @@ function quietFaultLog() { }; } -/** Nothing minted, rendered or stored, and the record never read. */ +/** Nothing written through the data engine. */ +function expectNothingWritten(d: Door): void { + for (const [verb, trap] of Object.entries(d.writes)) expect(trap, verb).not.toHaveBeenCalled(); +} + +/** Nothing minted, rendered or written, and the record never read. */ function expectNothingStarted(d: Door): void { expect(d.mint).not.toHaveBeenCalled(); expect(d.renderPdf).not.toHaveBeenCalled(); expect(d.findOne).not.toHaveBeenCalled(); - expect(d.rows.sys_attachment).toHaveLength(0); - expect(d.systemAttachFile).not.toHaveBeenCalled(); + expectNothingWritten(d); } describe('the print door — mounted', () => { @@ -244,31 +244,40 @@ describe('the print door — mounted', () => { }); describe('the print door — a print', () => { - it('prints as the caller and answers 201 with the file the service stored: exactly one attachment, never a second', async () => { + it('prints as the caller and answers 200 with the PDF itself as a download, writing nothing', async () => { const d = door(); await d.ready(); const answer = await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice' } }); - expect(answer.status).toBe(201); - expect(answer.body).toEqual({ - success: true, - data: { fileId: 'file_1', attachmentId: 'att_1', size: PDF.byteLength, filename: `${PAGE}-inv_alice.pdf` }, + expect(answer.status).toBe(200); + expect(answer.bytes).toBe(PDF); + expect(answer.body, 'no JSON envelope names a stored file').toBeUndefined(); + expect(answer.headers).toEqual({ + 'content-type': 'application/pdf', + 'content-disposition': `attachment; filename="${PAGE}-inv_alice.pdf"; filename*=UTF-8''${PAGE}-inv_alice.pdf`, + 'cache-control': 'no-store', + 'x-content-type-options': 'nosniff', }); - const forTheInvoice = d.rows.sys_attachment.filter((r) => r.parent_object === 'invoice' && r.parent_id === 'inv_alice'); - expect(forTheInvoice).toHaveLength(1); - expect(d.rows.sys_attachment).toHaveLength(1); - expect(forTheInvoice[0]).toMatchObject({ id: 'att_1', file_id: 'file_1', uploaded_by: 'usr_alice' }); - expect(d.rows.sys_file).toEqual([expect.objectContaining({ id: 'file_1', owner_id: 'usr_alice' })]); - expect(d.attachFileAs).toHaveBeenCalledTimes(1); - expect(d.systemAttachFile).not.toHaveBeenCalled(); + expectNothingWritten(d); expect(d.revoke).toHaveBeenCalledTimes(1); }); + it('a non-ASCII file name: an ASCII fallback, and the RFC 5987 form that keeps the name', async () => { + const d = door(); + await d.ready(); + const answer = await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice', filename: '报价单 "Q1".pdf' } }); + expect(answer.status).toBe(200); + expect(answer.headers['content-disposition']).toBe( + `attachment; filename="___ _Q1_.pdf"; filename*=UTF-8''${encodeURIComponent('报价单 "Q1".pdf')}`, + ); + expect(decodeURIComponent(answer.headers['content-disposition']!.split("UTF-8''")[1]!)).toBe('报价单 "Q1".pdf'); + }); + it('hands the service the request and the caller\'s own context, which reaches the mint unchanged', async () => { const d = door(); await d.ready(); await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice', filename: 'INV-1.pdf' } }); - expect(d.printRecordToFile).toHaveBeenCalledTimes(1); - const [request, context] = d.printRecordToFile.mock.calls[0]!; + expect(d.printRecordToPdf).toHaveBeenCalledTimes(1); + const [request, context] = d.printRecordToPdf.mock.calls[0]!; expect(request).toEqual({ ...INVOICE, recordId: 'inv_alice', filename: 'INV-1.pdf' }); expect(context).toMatchObject({ userId: 'usr_alice', tenantId: 'org_1', principalKind: 'human', isSystem: false }); expect(d.mint.mock.calls[0]![0]).toBe(context); @@ -278,11 +287,21 @@ describe('the print door — a print', () => { const d = door(); await d.ready(); const answer = await d.call({ bearer: 'notImpersonated', body: { ...INVOICE, recordId: 'inv_alice' } }); - expect(answer.status).toBe(201); + expect(answer.status).toBe(200); expect(d.auth.api.getSession).toHaveBeenCalledTimes(1); }); }); +describe('pdfContentDisposition — total over every name', () => { + it('writes a lone UTF-16 surrogate as U+FFFD instead of throwing, and keeps a paired one', () => { + const lone = pdfContentDisposition('Q\ud83d.pdf'); + expect(lone).toBe(`attachment; filename="Q_.pdf"; filename*=UTF-8''Q%EF%BF%BD.pdf`); + const paired = pdfContentDisposition('Q\u{1F600}.pdf'); + expect(paired).toBe(`attachment; filename="Q__.pdf"; filename*=UTF-8''${encodeURIComponent('Q\u{1F600}.pdf')}`); + expect(decodeURIComponent(paired.split("UTF-8''")[1]!)).toBe('Q\u{1F600}.pdf'); + }); +}); + describe('the print door — the refusals card ③ pins, relayed through the door', () => { it('no render driver configured: SERVICE_UNAVAILABLE / 503, reported, before anything is minted or read', async () => { const d = door({ placement: { state: 'unconfigured', reason: 'No print engine is configured. Set OS_PRINT_CHROMIUM_PATH.' } }); @@ -302,6 +321,19 @@ describe('the print door — the refusals card ③ pins, relayed through the doo expectNothingStarted(d); }); + it('a file name holding a lone UTF-16 surrogate: VALIDATION_ERROR / 400, before anything is minted or rendered', async () => { + const d = door(); + await d.ready(); + // JSON "\ud83d.pdf": a high surrogate with no low one after it, which no + // download header can carry (encodeURIComponent throws on it). + for (const filename of ['\ud83d.pdf', 'a\udc00.pdf']) { + const answer = await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice', filename } }); + expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]); + expect(answer.bytes, 'a refusal carries no PDF').toBeUndefined(); + } + expectNothingStarted(d); + }); + it('a caller who cannot read the record: RECORD_NOT_FOUND / 404, judged as the caller', async () => { const d = door(); await d.ready(); @@ -309,7 +341,8 @@ describe('the print door — the refusals card ③ pins, relayed through the doo expect(envelope(answer)).toEqual(['RECORD_NOT_FOUND', 404]); expect(d.findOne).toHaveBeenCalledTimes(1); expect(d.mint).not.toHaveBeenCalled(); - expect(d.rows.sys_attachment).toHaveLength(0); + expect(answer.bytes, 'a refusal carries no PDF').toBeUndefined(); + expectNothingWritten(d); }); const declared: Array<[string, number]> = [ @@ -318,18 +351,15 @@ describe('the print door — the refusals card ③ pins, relayed through the doo ['RESOURCE_NOT_FOUND', 404], ['VALIDATION_ERROR', 400], ['RECORD_NOT_FOUND', 404], - ['FILES_DISABLED', 403], - ['ATTACHMENT_PARENT_ACCESS', 403], ['TIMEOUT', 504], ['INTERNAL_ERROR', 500], - ['PAYLOAD_TOO_LARGE', 413], ]; for (const [code, status] of declared) { it(`relays ${code} / ${status} with its code and status unchanged`, async () => { const text = `the service's own text for ${code}, naming /srv/secret/host-path`; const stub: IPrintService = { status: () => ({ state: 'ready', placement: 'local', version: 'stand-in' }), - printRecordToFile: async () => { + printRecordToPdf: async () => { throw Object.assign(new Error(text), { code, status }); }, }; @@ -353,7 +383,7 @@ describe('the print door — the refusals card ③ pins, relayed through the doo it('an undeclared throw is a fault: INTERNAL_ERROR / 500, its text withheld', async () => { const stub: IPrintService = { status: () => ({ state: 'ready', placement: 'local', version: 'stand-in' }), - printRecordToFile: async () => { + printRecordToPdf: async () => { throw new Error('ECONNRESET at /srv/secret/host-path'); }, }; @@ -372,7 +402,7 @@ describe("the print door — its own 5xx sentences, in the request's language", function throwing(error: unknown): IPrintService { return { status: () => ({ state: 'ready', placement: 'local', version: 'stand-in' }), - printRecordToFile: async () => { + printRecordToPdf: async () => { throw error; }, }; @@ -479,7 +509,7 @@ describe('the print door — its own refusals, before the service is asked', () const answer = await d.call({ bearer: 'impersonated', body: { ...INVOICE, recordId: 'inv_alice' } }); expect(envelope(answer)).toEqual(['PERMISSION_DENIED', 403]); expect(answer.body.error.message).toMatch(/impersonation/); - expect(d.printRecordToFile).not.toHaveBeenCalled(); + expect(d.printRecordToPdf).not.toHaveBeenCalled(); expectNothingStarted(d); }); @@ -488,7 +518,7 @@ describe('the print door — its own refusals, before the service is asked', () await d.ready(); const answer = await d.call({ body: { ...INVOICE, recordId: 'inv_alice' } }); expect(envelope(answer)).toEqual(['UNAUTHENTICATED', 401]); - expect(d.printRecordToFile).not.toHaveBeenCalled(); + expect(d.printRecordToPdf).not.toHaveBeenCalled(); expectNothingStarted(d); }); @@ -497,7 +527,7 @@ describe('the print door — its own refusals, before the service is asked', () await d.ready(); const answer = await d.call({ bearer: 'held', body: { ...INVOICE, recordId: 'inv_alice' } }); expect(envelope(answer)).toEqual(['PASSWORD_EXPIRED', 403]); - expect(d.printRecordToFile).not.toHaveBeenCalled(); + expect(d.printRecordToPdf).not.toHaveBeenCalled(); }); it('a body field outside the request\'s closed set: VALIDATION_ERROR / 400, never ignored', async () => { @@ -506,7 +536,7 @@ describe('the print door — its own refusals, before the service is asked', () const answer = await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice', fileName: 'INV-1.pdf' } }); expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]); expect(answer.body.error.message).toContain('fileName'); - expect(d.printRecordToFile).not.toHaveBeenCalled(); + expect(d.printRecordToPdf).not.toHaveBeenCalled(); }); it('a body that is not an object: VALIDATION_ERROR / 400', async () => { @@ -514,7 +544,7 @@ describe('the print door — its own refusals, before the service is asked', () await d.ready(); const answer = await d.call({ bearer: 'alice', body: ['inv_alice'] }); expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]); - expect(d.printRecordToFile).not.toHaveBeenCalled(); + expect(d.printRecordToPdf).not.toHaveBeenCalled(); }); it('a query parameter: VALIDATION_ERROR / 400 — the door reads none', async () => { @@ -522,7 +552,7 @@ describe('the print door — its own refusals, before the service is asked', () await d.ready(); const answer = await d.call({ bearer: 'alice', query: { recordId: 'inv_alice' }, body: { ...INVOICE, recordId: 'inv_alice' } }); expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]); - expect(d.printRecordToFile).not.toHaveBeenCalled(); + expect(d.printRecordToPdf).not.toHaveBeenCalled(); }); it('a missing field reaches the service, which refuses it: VALIDATION_ERROR / 400', async () => { @@ -583,7 +613,7 @@ describe('[#31898] the print door hands its client facts to the key\'s use stamp const KEY_31898 = 'osk_print_31898'; registerPrintRoutes(http as never, { // What the print answers is not this pin's question: the caller is resolved before it is asked. - print: { printRecordToFile: async () => ({ fileId: 'f' }) } as never, + print: { printRecordToPdf: async () => ({ pdf: new Uint8Array(), size: 0, filename: 'f.pdf', contentType: 'application/pdf' }) } as never, getEngine: () => keyEngine31898(KEY_31898, 'u_key_31898', stamps), getAuth: () => ({ api: { getSession: async () => null }, resolveClientAddress: trustRule31898(handed) }) as never, resolveTenancyPosture: async () => undefined, diff --git a/packages/services/service-print/src/print-routes.ts b/packages/services/service-print/src/print-routes.ts index 44b2c38dcc4..c278c82c912 100644 --- a/packages/services/service-print/src/print-routes.ts +++ b/packages/services/service-print/src/print-routes.ts @@ -26,23 +26,21 @@ import { inProcessSessionReadInput, resolveThrownHttpError, sendError, - sendOk, sendServerFault, } from '@objectstack/types'; -import type { IPrintService, PrintedRecordFile, PrintRecordRequest } from './print-service.js'; +import { toWellFormedText, type IPrintService, type PrintedRecordPdf, type PrintRecordRequest } from './print-service.js'; /** * The print door: `POST /api/v1/print/records`, the one HTTP route of - * `@objectstack/service-print`. A user prints a record from the console (a - * declared `type: 'api'` action whose `target` is this path) and the record's - * print page is rendered and archived on the record, as that user, by the - * in-process `print` service (`IPrintService.printRecordToFile`). + * `@objectstack/service-print`. The record's print page is rendered as the + * caller by the in-process `print` service (`IPrintService.printRecordToPdf`) + * and the PDF is answered as a download. A print stores nothing: no file and no + * attachment. Keeping the PDF on the record is a separate, explicit act. * * The door adds no print rule of its own beyond who may ask. It resolves the * caller, refuses the callers it must, and hands the service the request and * the caller's execution context. The service decides everything about the - * page, the record and the file, and it is the one writer of the attachment: - * the door never attaches anything, so a print stores exactly one file. + * page, the record and the PDF. * * ## The request * @@ -69,9 +67,9 @@ import type { IPrintService, PrintedRecordFile, PrintRecordRequest } from './pri * every other door gives it. * 4. **An impersonation session** — an administrator signed in as the user * through the auth service's impersonation: `PERMISSION_DENIED` / `403`, - * saying so. A print is rendered and archived as the session's user, so - * printing under an impersonation would put a file on the record in that - * user's name for something they never asked for. The session the request + * saying so. A print mints a session in the session user's own name and + * renders the page as them, so printing under an impersonation would sign + * that user in for something they never asked for. The session the request * resolved through is the one read, and the mark is the one the auth * service writes on it (`session.impersonatedBy`, stored as * `sys_session.impersonated_by`). Only a session credential can carry it: @@ -85,9 +83,12 @@ import type { IPrintService, PrintedRecordFile, PrintRecordRequest } from './pri * * ## What the door answers * - * - **Success:** `201` with `{ fileId, attachmentId, size, filename }`, the - * file the service stored. The attachment is the service's, written as the - * caller, so `sys_file.owner_id` and `sys_attachment.uploaded_by` name them. + * - **Success:** `200` with the PDF itself as the body, never a JSON envelope: + * `Content-Type: application/pdf`, `Content-Disposition: attachment` with + * the file name in both the ASCII `filename=` and the RFC 5987 + * `filename*=UTF-8''…` forms ({@link pdfContentDisposition}), and + * `Cache-Control: no-store`, since the document is what this one user may + * read. A browser saves it as a download. * - **A refusal the service declares** (`code` and `status` on the thrown * error, ADR-0112) is relayed with that `code` and `status` unchanged. A * 4xx carries the service's own message. A 5xx carries this door's own @@ -108,12 +109,11 @@ import type { IPrintService, PrintedRecordFile, PrintRecordRequest } from './pri * ## What is not recorded * * The door writes no audit row of its own. A print signs a session in and out - * for the caller, which the auth service records as it records any sign-in, - * and the archive names the caller on both rows it writes. That is the whole - * attribution a print gets. + * for the caller, which the auth service records as it records any sign-in. + * That is the whole attribution a print gets. */ -/** The route the door is mounted at. Not configurable: the console's declared actions name it. */ +/** The route the door is mounted at. Not configurable: callers name it, and the runtime dispatcher's `/print` domain forwards to it. */ export const PRINT_RECORDS_ROUTE = '/api/v1/print/records'; /** The body fields the door reads: exactly {@link PrintRecordRequest}'s. */ @@ -187,9 +187,9 @@ async function handlePrintRecord(req: IHttpRequest, res: IHttpResponse, deps: Pr res, 403, 'PERMISSION_DENIED', - 'This print was refused because the session is an impersonation: a printed PDF is rendered and archived as ' + - 'the signed-in user, and in an impersonation session that user is not the one asking. Stop impersonating, ' + - 'or ask the user to print the record themselves.', + 'This print was refused because the session is an impersonation: a printed PDF is rendered under a session ' + + 'minted for the signed-in user, and in an impersonation session that user is not the one asking. Stop ' + + 'impersonating, or ask the user to print the record themselves.', ); return; } @@ -214,14 +214,47 @@ async function handlePrintRecord(req: IHttpRequest, res: IHttpResponse, deps: Pr return; } - let printed: PrintedRecordFile; + let printed: PrintedRecordPdf; try { - printed = await deps.print.printRecordToFile(request, context); + printed = await deps.print.printRecordToPdf(request, context); } catch (err) { relayPrintFailure(res, err, requestLocaleOf(req)); return; } - sendOk(res, printed, 201); + sendPdf(res, printed); +} + +/** + * Answer the printed PDF as a download: the bytes as the body, typed + * `application/pdf`, offered under the print's file name, never cached. + */ +function sendPdf(res: IHttpResponse, printed: PrintedRecordPdf): void { + res + .status(200) + .header('Content-Type', printed.contentType) + .header('Content-Disposition', pdfContentDisposition(printed.filename)) + .header('Cache-Control', 'no-store') + .header('X-Content-Type-Options', 'nosniff'); + res.send(printed.pdf); +} + +/** + * The `Content-Disposition` value a print is downloaded under: `attachment`, + * an ASCII `filename=` fallback (every character outside printable ASCII, and + * `"` and `\`, become `_`, so the quoted string cannot be broken out of), and + * the RFC 5987 `filename*=UTF-8''…` form a browser prefers, which keeps a + * non-ASCII name such as `报价单.pdf` intact. The same spelling the storage + * service's stored-bytes doors write. + * + * Total: a lone UTF-16 surrogate, which `encodeURIComponent` throws on, is + * written as U+FFFD first ({@link toWellFormedText}). A request's own name + * holding one is refused before the render; this covers every other name. + */ +export function pdfContentDisposition(filename: string): string { + const name = toWellFormedText(filename); + const asciiFallback = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_'); + const encoded = encodeURIComponent(name).replace(/['()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase()); + return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${encoded}`; } /** diff --git a/packages/services/service-print/src/print-service-plugin.revoke-log.test.ts b/packages/services/service-print/src/print-service-plugin.revoke-log.test.ts index c63c0e0705e..7a155847d32 100644 --- a/packages/services/service-print/src/print-service-plugin.revoke-log.test.ts +++ b/packages/services/service-print/src/print-service-plugin.revoke-log.test.ts @@ -32,7 +32,6 @@ vi.mock('playwright-core', () => { }); const { PrintServicePlugin, PRINT_SERVICE } = await import('./print-service-plugin.js'); -const { FILE_ATTACHMENT_SERVICE } = await import('@objectstack/spec/contracts'); const TOKEN = 'minted-token-for-the-revoke-log-pin'; const USER = { userId: 'usr_alice', tenantId: 'org_1', principalKind: 'human' } as ExecutionContext; @@ -64,16 +63,6 @@ describe('PrintServicePlugin wires its logger into the service', () => { }, }, ], - [ - FILE_ATTACHMENT_SERVICE, - { - attachFile: async () => { - throw new Error('the system verb must not be used'); - }, - assertMayAttach: async () => undefined, - attachFileAs: async (input: { data: Buffer }) => ({ fileId: 'file_1', attachmentId: 'att_1', size: input.data.byteLength }), - }, - ], ]); const ctx = { logger: { @@ -93,12 +82,13 @@ describe('PrintServicePlugin wires its logger into the service', () => { const plugin = new PrintServicePlugin({ chromiumPath: '/staged/chromium', consoleUrl: 'http://127.0.0.1:3000/_console' }); await plugin.init(ctx); await plugin.start(ctx); - const print = services.get(PRINT_SERVICE) as { printRecordToFile: Function; status: Function }; + // No file-attachments service is composed: a print stores nothing, so it needs none. + const print = services.get(PRINT_SERVICE) as { printRecordToPdf: Function; status: Function }; expect(print.status()).toMatchObject({ state: 'ready' }); - const out = await print.printRecordToFile({ app: 'app', object: 'invoice', recordId: 'inv_1', page: 'invoice_print' }, USER); + const out = await print.printRecordToPdf({ app: 'app', object: 'invoice', recordId: 'inv_1', page: 'invoice_print' }, USER); - expect(out).toMatchObject({ fileId: 'file_1' }); + expect(Buffer.from(out.pdf).toString()).toBe('%PDF-1.4 staged'); const errors = logged.filter((l) => l.level === 'error'); expect(errors).toHaveLength(1); expect(errors[0]!.message).toMatch(/fingerprint [0-9a-f]{12}/); diff --git a/packages/services/service-print/src/print-service-plugin.test.ts b/packages/services/service-print/src/print-service-plugin.test.ts index f687181b208..b090a14b2fb 100644 --- a/packages/services/service-print/src/print-service-plugin.test.ts +++ b/packages/services/service-print/src/print-service-plugin.test.ts @@ -70,7 +70,7 @@ async function boot(options: ConstructorParameters[0] describe('PrintServicePlugin.start — absence is loud, once', () => { it('registers the print service on every path', async () => { const { service } = await boot({}); - expect(typeof service.printRecordToFile).toBe('function'); + expect(typeof service.printRecordToPdf).toBe('function'); expect(typeof service.status).toBe('function'); }); diff --git a/packages/services/service-print/src/print-service-plugin.ts b/packages/services/service-print/src/print-service-plugin.ts index 0a574008d5a..920b921350c 100644 --- a/packages/services/service-print/src/print-service-plugin.ts +++ b/packages/services/service-print/src/print-service-plugin.ts @@ -2,12 +2,7 @@ import type { Plugin, PluginContext, TenancyPostureSource } from '@objectstack/core'; import { classifyAdmissionTenancyPosture } from '@objectstack/core'; -import { - FILE_ATTACHMENT_SERVICE, - type IAuthService, - type IFileAttachmentService, - type IHttpServer, -} from '@objectstack/spec/contracts'; +import type { IAuthService, IHttpServer } from '@objectstack/spec/contracts'; import type { TenancyPosture } from '@objectstack/spec/security'; import { createChromiumDriver } from './chromium-driver.js'; import { @@ -34,9 +29,11 @@ export type PrintServicePluginOptions = PrintPlacementOptions; * Composed explicitly: a deployment that prints lists this plugin, and one that * does not never loads a browser driver. Two doors reach the service: the * in-process `print` service, and `POST /api/v1/print/records` on the - * kernel's HTTP server (`print-routes.ts`), which a console action calls to - * print the record it is on. The plugin registers no action: an app declares - * one (a `type: 'api'` action whose `target` is that path). + * kernel's HTTP server (`print-routes.ts`), which answers the record's PDF as + * a download. The plugin registers no action. An app's declared `type: 'api'` + * action that targets the route delivers the PDF: the REST action door relays + * the attachment byte for byte and the console saves it; the MCP action door + * answers a file `502`. * * Lifecycle: * - `init`: read the placement (options, then `OS_PRINT_*`), build the @@ -50,7 +47,7 @@ export type PrintServicePluginOptions = PrintPlacementOptions; * engine makes the deployment visibly smaller and loses nothing, which is * a `warn`. * - `kernel:ready`: the services a print needs (the auth service's - * principal-session mint, `file-attachments`, the data engine) + * principal-session mint and the data engine) * are registered by other plugins, so their absence is reported only once * every plugin has started. `status()` reads them at call time either way. * The door is mounted then too, on every path — an engine that is not @@ -90,7 +87,6 @@ export class PrintServicePlugin implements Plugin { placement, driver, getEngine: () => optional('objectql'), - getAttachments: () => optional(FILE_ATTACHMENT_SERVICE), getMinter: () => principalSessionMinterOf(optional('auth')), logger: ctx.logger, // [#36840] The print door for a kernel with no `http.server` (a hosted diff --git a/packages/services/service-print/src/print-service.test.ts b/packages/services/service-print/src/print-service.test.ts index 726363d2eab..6d972f15567 100644 --- a/packages/services/service-print/src/print-service.test.ts +++ b/packages/services/service-print/src/print-service.test.ts @@ -8,6 +8,7 @@ import type { PrintPlacementResolution } from './config.js'; import type { PrincipalSessionMinter, PrintSession } from './principal-session.js'; import { principalSessionMinterOf } from './principal-session.js'; import { + PRINT_FILENAME_MAX_CHARS, PRINT_RENDER_TIMEOUT_MS, PRINT_SESSION_TTL_SECONDS, PrintService, @@ -40,9 +41,6 @@ interface Harness { driver: { probe: ReturnType; renderPdf: ReturnType }; mint: ReturnType; revoke: ReturnType; - attachFile: ReturnType; - systemAttachFile: ReturnType; - assertMayAttach: ReturnType; findOne: ReturnType; metadataGet: ReturnType; loggerError: ReturnType; @@ -56,11 +54,7 @@ interface Setup { readError?: unknown; probeError?: Error; renderError?: unknown; - attachError?: unknown; noMint?: boolean; - noAttachments?: boolean; - noCallerAttach?: boolean; - attachRefusal?: Error; revokeError?: Error; } @@ -92,14 +86,6 @@ async function harness(setup: Setup = {}): Promise { return PDF; }), }; - const attachFile = vi.fn(async (input: { data: Buffer }, _context?: unknown) => { - if (setup.attachError) throw setup.attachError; - return { fileId: 'file_1', attachmentId: 'att_1', size: input.data.byteLength }; - }); - const systemAttachFile = vi.fn(); - const assertMayAttach = vi.fn(async () => { - if (setup.attachRefusal) throw setup.attachRefusal; - }); const findOne = vi.fn(async () => { if (setup.readError) throw setup.readError; return 'record' in setup ? setup.record : { id: 'inv_1' }; @@ -119,17 +105,11 @@ async function harness(setup: Setup = {}): Promise { getObject: () => ('object' in setup ? setup.object : { name: 'invoice', enable: { files: true } }), }, }) as never, - getAttachments: () => - setup.noAttachments - ? undefined - : ((setup.noCallerAttach - ? { attachFile: systemAttachFile } - : { attachFile: systemAttachFile, attachFileAs: attachFile, assertMayAttach }) as never), getMinter: () => (setup.noMint ? undefined : minter), logger: { error: loggerError }, }); await service.probe(); - return { service, driver, mint, revoke, attachFile, systemAttachFile, assertMayAttach, findOne, metadataGet, loggerError }; + return { service, driver, mint, revoke, findOne, metadataGet, loggerError }; } /** The refusal's ADR-0112 envelope: `code` and `status`. */ @@ -143,12 +123,10 @@ async function refusalOf(p: Promise): Promise<{ code: unknown; status: throw new Error('expected a refusal, the call resolved'); } -/** Nothing was minted, rendered or stored. */ +/** Nothing was minted or rendered. */ function expectNothingStarted(h: Harness): void { expect(h.mint).not.toHaveBeenCalled(); expect(h.driver.renderPdf).not.toHaveBeenCalled(); - expect(h.attachFile).not.toHaveBeenCalled(); - expect(h.systemAttachFile).not.toHaveBeenCalled(); } describe('PrintService — the principal (step ①)', () => { @@ -165,7 +143,7 @@ describe('PrintService — the principal (step ①)', () => { for (const [label, context] of cases) { it(`refuses ${label}: PERMISSION_DENIED / 403, before anything is minted or launched`, async () => { const h = await harness(); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, context as ExecutionContext)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, context as ExecutionContext)); expect([r.code, r.status]).toEqual(['PERMISSION_DENIED', 403]); expectNothingStarted(h); expect(h.findOne).not.toHaveBeenCalled(); @@ -174,7 +152,7 @@ describe('PrintService — the principal (step ①)', () => { it('a principal refusal wins over an absent engine (the ruled order)', async () => { const h = await harness({ placement: { state: 'unconfigured', reason: 'none' } }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, { isSystem: true } as ExecutionContext)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, { isSystem: true } as ExecutionContext)); expect([r.code, r.status]).toEqual(['PERMISSION_DENIED', 403]); }); }); @@ -182,7 +160,7 @@ describe('PrintService — the principal (step ①)', () => { describe('PrintService — the engine (step ②)', () => { it('no placement configured: SERVICE_UNAVAILABLE / 503 naming the reason; the page is never read', async () => { const h = await harness({ placement: { state: 'unconfigured', reason: 'Set OS_PRINT_CHROMIUM_PATH.' } }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['SERVICE_UNAVAILABLE', 503]); expect(r.message).toContain('OS_PRINT_CHROMIUM_PATH'); expect(h.metadataGet).not.toHaveBeenCalled(); @@ -191,7 +169,7 @@ describe('PrintService — the engine (step ②)', () => { it('a misconfigured placement: SERVICE_UNAVAILABLE / 503', async () => { const h = await harness({ placement: { state: 'misconfigured', placement: 'remote', reason: 'bad endpoint' } }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['SERVICE_UNAVAILABLE', 503]); expectNothingStarted(h); }); @@ -199,39 +177,36 @@ describe('PrintService — the engine (step ②)', () => { it('an unreachable engine is probed once more per call, then refused 503', async () => { const h = await harness({ probeError: new Error('connect ECONNREFUSED') }); expect(h.service.status()).toMatchObject({ state: 'unavailable', placement: 'local' }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['SERVICE_UNAVAILABLE', 503]); expect(h.driver.probe).toHaveBeenCalledTimes(2); expectNothingStarted(h); }); - it('an unreachable engine is re-probed only AFTER step 5: an unknown page is refused 404 with no browser started', async () => { + it('an unreachable engine is re-probed only AFTER step 4: an unknown page is refused 404 with no browser started', async () => { const h = await harness({ probeError: new Error('connect ECONNREFUSED'), page: undefined }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['RESOURCE_NOT_FOUND', 404]); expect(h.driver.probe).toHaveBeenCalledTimes(1); // the boot probe alone expectNothingStarted(h); }); - it('an unreachable engine is re-probed only AFTER step 5: an attach refusal wins with no browser started', async () => { - const h = await harness({ - probeError: new Error('connect ECONNREFUSED'), - attachRefusal: refusalError('ATTACHMENT_PARENT_ACCESS', 403, 'no edit'), - }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect([r.code, r.status]).toEqual(['ATTACHMENT_PARENT_ACCESS', 403]); + it('an unreachable engine is re-probed only AFTER step 4: an unreadable record wins with no browser started', async () => { + const h = await harness({ probeError: new Error('connect ECONNREFUSED'), record: null }); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); + expect([r.code, r.status]).toEqual(['RECORD_NOT_FOUND', 404]); expect(h.driver.probe).toHaveBeenCalledTimes(1); expectNothingStarted(h); }); - it('an engine that answers its re-probe after step 5 serves the print', async () => { + it('an engine that answers its re-probe after step 4 serves the print', async () => { const h = await harness({ probeError: new Error('connect ECONNREFUSED') }); h.driver.probe.mockResolvedValueOnce({ version: '141.0.7390.37' }); - const out = await h.service.printRecordToFile(REQUEST, USER); - expect(out.fileId).toBe('file_1'); + const out = await h.service.printRecordToPdf(REQUEST, USER); + expect(out.pdf).toBe(PDF); expect(h.driver.probe).toHaveBeenCalledTimes(2); const order = (fn: ReturnType): number => fn.mock.invocationCallOrder[fn.mock.invocationCallOrder.length - 1]!; - expect(order(h.assertMayAttach)).toBeLessThan(order(h.driver.probe)); + expect(order(h.findOne)).toBeLessThan(order(h.driver.probe)); expect(order(h.driver.probe)).toBeLessThan(order(h.mint)); }); @@ -239,18 +214,11 @@ describe('PrintService — the engine (step ②)', () => { const h = await harness({ noMint: true }); expect(h.service.status()).toMatchObject({ state: 'unavailable', version: '141.0.7390.37' }); expect(h.service.status().reason).toContain('mintPrincipalSession'); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['SERVICE_UNAVAILABLE', 503]); expectNothingStarted(h); }); - it('no file-attachments service: unavailable, 503', async () => { - const h = await harness({ noAttachments: true }); - expect(h.service.status().reason).toContain('file-attachments'); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect([r.code, r.status]).toEqual(['SERVICE_UNAVAILABLE', 503]); - expectNothingStarted(h); - }); it('a ready engine reports its placement and version', async () => { const h = await harness(); @@ -261,8 +229,31 @@ describe('PrintService — the engine (step ②)', () => { describe('PrintService — the page (step ③)', () => { it('a malformed request: VALIDATION_ERROR / 400', async () => { const h = await harness(); - for (const bad of [{ ...REQUEST, app: '' }, { ...REQUEST, recordId: 7 }, { ...REQUEST, filename: '' }]) { - const r = await refusalOf(h.service.printRecordToFile(bad as PrintRecordRequest, USER)); + for (const bad of [ + { ...REQUEST, app: '' }, + { ...REQUEST, recordId: 7 }, + { ...REQUEST, filename: '' }, + { ...REQUEST, filename: `${'n'.repeat(PRINT_FILENAME_MAX_CHARS)}.pdf` }, + ]) { + const r = await refusalOf(h.service.printRecordToPdf(bad as PrintRecordRequest, USER)); + expect([r.code, r.status]).toEqual(['VALIDATION_ERROR', 400]); + } + expectNothingStarted(h); + }); + + it('a filename at the bound prints; one past it, or one holding a lone UTF-16 surrogate, is refused before anything starts', async () => { + const atBound = `${'n'.repeat(PRINT_FILENAME_MAX_CHARS - 4)}.pdf`; + expect(Array.from(atBound)).toHaveLength(PRINT_FILENAME_MAX_CHARS); + const ok = await harness(); + expect((await ok.service.printRecordToPdf({ ...REQUEST, filename: atBound }, USER)).filename).toBe(atBound); + // A paired surrogate (one astral character) is well-formed and prints: the + // control for the lone-surrogate refusal below. + const astral = await harness(); + expect((await astral.service.printRecordToPdf({ ...REQUEST, filename: 'Q\u{1F600}.pdf' }, USER)).filename).toBe('Q\u{1F600}.pdf'); + + const h = await harness(); + for (const filename of [`n${atBound}`, '\ud83d.pdf', 'a\udc00.pdf']) { + const r = await refusalOf(h.service.printRecordToPdf({ ...REQUEST, filename }, USER)); expect([r.code, r.status]).toEqual(['VALIDATION_ERROR', 400]); } expectNothingStarted(h); @@ -270,7 +261,7 @@ describe('PrintService — the page (step ③)', () => { it('an unknown page: RESOURCE_NOT_FOUND / 404, and the record is never read', async () => { const h = await harness({ page: undefined }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['RESOURCE_NOT_FOUND', 404]); expect(h.findOne).not.toHaveBeenCalled(); expectNothingStarted(h); @@ -290,7 +281,7 @@ describe('PrintService — the page (step ③)', () => { for (const [label, page] of invalid) { it(`${label}: VALIDATION_ERROR / 400, and the record is never read`, async () => { const h = await harness({ page }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['VALIDATION_ERROR', 400]); expect(h.findOne).not.toHaveBeenCalled(); expectNothingStarted(h); @@ -301,80 +292,58 @@ describe('PrintService — the page (step ③)', () => { describe('PrintService — the record, read as the caller (step ④)', () => { it('reads the record with the caller’s own context, never a system one', async () => { const h = await harness(); - await h.service.printRecordToFile(REQUEST, USER); + await h.service.printRecordToPdf(REQUEST, USER); expect(h.findOne).toHaveBeenCalledWith('invoice', { where: { id: 'inv_1' } }, { context: USER }); }); it('a record the caller cannot see: RECORD_NOT_FOUND / 404', async () => { const h = await harness({ record: null }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['RECORD_NOT_FOUND', 404]); expectNothingStarted(h); }); it('a read refused 403 answers the same 404, so the answer discloses nothing', async () => { const h = await harness({ readError: refusalError('PERMISSION_DENIED', 403, 'no read on invoice') }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['RECORD_NOT_FOUND', 404]); expectNothingStarted(h); }); it('a read that fails for another reason is not disguised', async () => { const h = await harness({ readError: refusalError('DATABASE_ERROR', 500, 'down') }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['DATABASE_ERROR', 500]); expectNothingStarted(h); }); }); -describe('PrintService — the files opt-in (step ⑤)', () => { - it('an object without enable.files: FILES_DISABLED / 403, before any render', async () => { - const h = await harness({ object: { name: 'invoice', enable: {} } }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect([r.code, r.status]).toEqual(['FILES_DISABLED', 403]); - expectNothingStarted(h); - }); - - for (const [label, refusal] of [ - ['the attach rule refuses (no edit access)', ['ATTACHMENT_PARENT_ACCESS', 403]], - ['the caller may not create attachments at all', ['PERMISSION_DENIED', 403]], - ] as const) { - it(`${label}: the archive's own refusal, ${refusal[0]} / ${refusal[1]}, before any mint or render`, async () => { - const h = await harness({ attachRefusal: refusalError(refusal[0], refusal[1], label) }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect([r.code, r.status]).toEqual([...refusal]); - expect(h.assertMayAttach).toHaveBeenCalledWith('invoice', 'inv_1', USER); - expect(h.assertMayAttach.mock.calls[0]![2]).toBe(USER); - expectNothingStarted(h); - }); - } - - it('a files refusal wins over the attach rule (the ruled order)', async () => { - const h = await harness({ object: { enable: {} }, attachRefusal: refusalError('ATTACHMENT_PARENT_ACCESS', 403, 'x') }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect(r.code).toBe('FILES_DISABLED'); - expect(h.assertMayAttach).not.toHaveBeenCalled(); +describe('PrintService — read access is the whole permission; nothing is stored', () => { + it('composes no file-attachments service and is ready without one', async () => { + const h = await harness(); + expect(h.service.status()).toEqual({ state: 'ready', placement: 'local', version: '141.0.7390.37' }); }); - it('an archive that can only attach as the system: unavailable, 503 — never a system-attributed PDF', async () => { - const h = await harness({ noCallerAttach: true }); - expect(h.service.status().reason).toContain('attachFileAs'); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect([r.code, r.status]).toEqual(['SERVICE_UNAVAILABLE', 503]); - expectNothingStarted(h); + it('an object that does not enable files prints: the files opt-in belongs to attachments, and a print makes none', async () => { + const h = await harness({ object: { name: 'invoice', enable: {} } }); + const out = await h.service.printRecordToPdf(REQUEST, USER); + expect(out.pdf).toBe(PDF); }); - it('an unreadable record wins over a files refusal (the ruled order)', async () => { - const h = await harness({ record: null, object: { enable: {} } }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect(r.code).toBe('RECORD_NOT_FOUND'); + it('a caller who can read the record prints it; edit access is never asked', async () => { + // The harness's engine answers the caller's own read and offers nothing + // else: no attach rule, no edit check, no write verb of any kind. + const h = await harness(); + const out = await h.service.printRecordToPdf(REQUEST, USER); + expect(out).toEqual({ pdf: PDF, size: PDF.byteLength, filename: 'invoice_print-inv_1.pdf', contentType: 'application/pdf' }); + expect(h.findOne).toHaveBeenCalledTimes(1); }); }); -describe('PrintService — mint, render, archive, revoke', () => { - it('mints for the caller with the TTL, renders the record URL with the cookie, archives the PDF', async () => { +describe('PrintService — mint, render, revoke', () => { + it('mints for the caller with the TTL, renders the record URL with the cookie, and hands the PDF back', async () => { const h = await harness(); - const out = await h.service.printRecordToFile(REQUEST, USER); + const out = await h.service.printRecordToPdf(REQUEST, USER); expect(h.mint).toHaveBeenCalledWith(USER, PRINT_SESSION_TTL_SECONDS); // The request's own context, unchanged — the very object the caller passed, never one assembled. expect(h.mint.mock.calls[0]![0]).toBe(USER); @@ -386,29 +355,14 @@ describe('PrintService — mint, render, archive, revoke', () => { cookie: expect.objectContaining({ value: COOKIE_VALUE }), timeoutMs: PRINT_RENDER_TIMEOUT_MS, }); - expect(h.attachFile).toHaveBeenCalledWith( - { - parentObject: 'invoice', - parentId: 'inv_1', - organizationId: 'org_1', - filename: 'invoice_print-inv_1.pdf', - mimeType: 'application/pdf', - data: PDF, - }, - USER, - ); - // Archived AS THE CALLER: the caller's own context, and never the system verb. - expect(h.attachFile.mock.calls[0]![1]).toBe(USER); - expect(h.systemAttachFile).not.toHaveBeenCalled(); - expect(h.assertMayAttach).toHaveBeenCalledWith('invoice', 'inv_1', USER); expect(h.revoke).toHaveBeenCalledTimes(1); - expect(out).toEqual({ fileId: 'file_1', attachmentId: 'att_1', size: PDF.byteLength, filename: 'invoice_print-inv_1.pdf' }); + expect(out).toEqual({ pdf: PDF, size: PDF.byteLength, filename: 'invoice_print-inv_1.pdf', contentType: 'application/pdf' }); }); it('a print page that is not the default record page prints on the console’s named record-page route', async () => { const named = { ...PRINT_PAGE, name: 'invoice_document', isDefault: undefined }; const h = await harness({ page: named }); - const out = await h.service.printRecordToFile({ ...REQUEST, page: 'invoice_document' }, USER); + const out = await h.service.printRecordToPdf({ ...REQUEST, page: 'invoice_document' }, USER); expect(h.driver.renderPdf).toHaveBeenCalledWith({ url: `${CONSOLE}/apps/showcase/invoice/record/inv_1/page/invoice_document`, cookie: expect.objectContaining({ value: COOKIE_VALUE }), @@ -420,48 +374,39 @@ describe('PrintService — mint, render, archive, revoke', () => { it('the default record page keeps the plain record route; every segment of the named route is encoded', async () => { const h = await harness({ page: { ...PRINT_PAGE, name: 'doc/1', isDefault: false } }); - await h.service.printRecordToFile({ ...REQUEST, recordId: 'inv 1', page: 'doc/1' }, USER); + await h.service.printRecordToPdf({ ...REQUEST, recordId: 'inv 1', page: 'doc/1' }, USER); expect(h.driver.renderPdf.mock.calls[0]![0].url).toBe(`${CONSOLE}/apps/showcase/invoice/record/inv%201/page/doc%2F1`); const d = await harness(); - await d.service.printRecordToFile(REQUEST, USER); + await d.service.printRecordToPdf(REQUEST, USER); expect(d.driver.renderPdf.mock.calls[0]![0].url).toBe(`${CONSOLE}/apps/showcase/invoice/record/inv_1`); }); - it('the mint happens only after every refusal check, and the revoke after the archive', async () => { + it('the mint happens only after every refusal check, and the revoke after the render', async () => { const h = await harness(); - await h.service.printRecordToFile(REQUEST, USER); + await h.service.printRecordToPdf(REQUEST, USER); const order = (fn: ReturnType): number => fn.mock.invocationCallOrder[0]!; expect(order(h.findOne)).toBeLessThan(order(h.mint)); expect(order(h.mint)).toBeLessThan(order(h.driver.renderPdf)); - expect(order(h.driver.renderPdf)).toBeLessThan(order(h.attachFile)); - expect(order(h.attachFile)).toBeLessThan(order(h.revoke)); + expect(order(h.driver.renderPdf)).toBeLessThan(order(h.revoke)); }); - it('a caller with no organization archives in none', async () => { + it('a caller with no organization prints, under the filename the request names', async () => { const h = await harness(); - await h.service.printRecordToFile({ ...REQUEST, filename: 'copy.pdf' }, { userId: 'usr_alice' } as ExecutionContext); - expect(h.attachFile).toHaveBeenCalledWith(expect.objectContaining({ organizationId: null, filename: 'copy.pdf' }), expect.anything()); + const out = await h.service.printRecordToPdf({ ...REQUEST, filename: 'copy.pdf' }, { userId: 'usr_alice' } as ExecutionContext); + expect(out.filename).toBe('copy.pdf'); }); it('a failed render still revokes the session, and the failure is passed on unchanged', async () => { const h = await harness({ renderError: refusalError('TIMEOUT', 504, 'the print page did not load') }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['TIMEOUT', 504]); expect(h.revoke).toHaveBeenCalledTimes(1); - expect(h.attachFile).not.toHaveBeenCalled(); }); - it('a refused archive still revokes the session', async () => { - const h = await harness({ attachError: refusalError('PAYLOAD_TOO_LARGE', 413, 'too large') }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); - expect([r.code, r.status]).toEqual(['PAYLOAD_TOO_LARGE', 413]); - expect(h.revoke).toHaveBeenCalledTimes(1); - }); - - it('a revoke that fails after a committed archive: the caller still gets the success, and the failure is logged at error by fingerprint', async () => { + it('a revoke that fails after a rendered PDF: the caller still gets the PDF, and the failure is logged at error by fingerprint', async () => { const h = await harness({ revokeError: new Error(`session store down while revoking ${TOKEN}`) }); - const out = await h.service.printRecordToFile(REQUEST, USER); - expect(out).toMatchObject({ fileId: 'file_1', attachmentId: 'att_1' }); + const out = await h.service.printRecordToPdf(REQUEST, USER); + expect(out.pdf).toBe(PDF); expect(h.revoke).toHaveBeenCalledTimes(1); expect(h.loggerError).toHaveBeenCalledTimes(1); const line = String(h.loggerError.mock.calls[0]![0]); @@ -476,7 +421,7 @@ describe('PrintService — mint, render, archive, revoke', () => { renderError: refusalError('TIMEOUT', 504, 'the print page did not load'), revokeError: new Error('session store down'), }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['TIMEOUT', 504]); expect(h.loggerError).toHaveBeenCalledTimes(1); expect(String(h.loggerError.mock.calls[0]![0])).not.toContain(TOKEN); @@ -485,7 +430,7 @@ describe('PrintService — mint, render, archive, revoke', () => { it('a mint refusal is passed on, and nothing is rendered', async () => { const h = await harness(); h.mint.mockRejectedValueOnce(refusalError('PERMISSION_DENIED', 403, 'banned')); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect([r.code, r.status]).toEqual(['PERMISSION_DENIED', 403]); expect(h.driver.renderPdf).not.toHaveBeenCalled(); expect(h.revoke).not.toHaveBeenCalled(); @@ -493,7 +438,7 @@ describe('PrintService — mint, render, archive, revoke', () => { it('the minted credential appears in no refusal message', async () => { const h = await harness({ renderError: refusalError('INTERNAL_ERROR', 500, 'engine crashed') }); - const r = await refusalOf(h.service.printRecordToFile(REQUEST, USER)); + const r = await refusalOf(h.service.printRecordToPdf(REQUEST, USER)); expect(r.message).not.toContain(COOKIE_VALUE); expect(r.message).not.toContain(TOKEN); }); @@ -507,19 +452,17 @@ describe('PrintService — the default file name (the record’s display name, A fields: { number: { type: 'text' }, total: { type: 'currency' } }, }; - /** The name a print with no `filename` archives `record` under, on an object `object`. */ + /** The name a print with no `filename` offers `record`'s PDF under, on an object `object`. */ async function defaultName(record: Record, object: unknown = INVOICE): Promise { const h = await harness({ object, record: { id: 'inv_1', ...record } }); - const out = await h.service.printRecordToFile(REQUEST, USER); - expect(h.attachFile.mock.calls[0]![0].filename).toBe(out.filename); + const out = await h.service.printRecordToPdf(REQUEST, USER); return out.filename; } it('names the PDF from the record’s display name, read once, from the row the caller’s own read answered', async () => { const h = await harness({ object: INVOICE, record: { id: 'inv_1', number: 'INV-0001' } }); - const out = await h.service.printRecordToFile(REQUEST, USER); + const out = await h.service.printRecordToPdf(REQUEST, USER); expect(out.filename).toBe('INV-0001.pdf'); - expect(h.attachFile).toHaveBeenCalledWith(expect.objectContaining({ filename: 'INV-0001.pdf' }), USER); expect(h.findOne).toHaveBeenCalledTimes(1); expect(h.findOne.mock.calls[0]![2].context).toBe(USER); }); @@ -531,7 +474,7 @@ describe('PrintService — the default file name (the record’s display name, A it('an explicit filename wins unchanged, display name or not', async () => { const h = await harness({ object: INVOICE, record: { id: 'inv_1', number: 'INV-0001' } }); - const out = await h.service.printRecordToFile({ ...REQUEST, filename: 'a/b: raw.PDF' }, USER); + const out = await h.service.printRecordToPdf({ ...REQUEST, filename: 'a/b: raw.PDF' }, USER); expect(out.filename).toBe('a/b: raw.PDF'); }); @@ -561,6 +504,10 @@ describe('PrintService — the default file name (the record’s display name, A expect(await defaultName({ number: 'Quote 7.PDF' })).toBe('Quote 7.pdf'); }); + it('a display value holding a lone UTF-16 surrogate keeps it as U+FFFD, so the download header can carry it', async () => { + expect(await defaultName({ number: 'Q\ud83d-7' })).toBe('Q\uFFFD-7.pdf'); + }); + it('a long name is cut to 100 characters before .pdf, never inside a character', async () => { const name = await defaultName({ number: `${'a'.repeat(99)}\u{1F600}tail` }); expect(name).toBe(`${'a'.repeat(99)}\u{1F600}.pdf`); diff --git a/packages/services/service-print/src/print-service.ts b/packages/services/service-print/src/print-service.ts index 7d3f6aa536b..110124f5d90 100644 --- a/packages/services/service-print/src/print-service.ts +++ b/packages/services/service-print/src/print-service.ts @@ -2,25 +2,28 @@ import { createHash } from 'node:crypto'; import { recordNotFoundError } from '@objectstack/core'; -import type { RegisteredErrorCode, StandardErrorCode } from '@objectstack/spec/api'; +import type { StandardErrorCode } from '@objectstack/spec/api'; import { resolveDisplayField, type DisplayNameObjectMeta } from '@objectstack/spec/data'; -import type { EngineSchemaRegistryView, IDataEngine, IFileAttachmentService, IPrintDoorService } from '@objectstack/spec/contracts'; +import type { EngineSchemaRegistryView, IDataEngine, IPrintDoorService } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { defaultRecordPageObject } from '@objectstack/spec/ui'; -import type { ICallerFileAttachmentService } from '@objectstack/service-storage'; import type { ChromiumDriver } from './chromium-driver.js'; import type { PrintPlacement, PrintPlacementResolution } from './config.js'; import type { PrincipalSessionMinter, PrintSession } from './principal-session.js'; /** * The print service: render a record's print page in headless Chromium, as - * the requesting user, and archive the PDF as a file attached to the record. + * the requesting user, and hand the PDF back to the caller. A print writes + * nothing: no file and no attachment. The record page's "generate PDF" is a + * download, and keeping the PDF on the record is a separate, explicit act + * (the maintainer's ruling on the print-download card, which supersedes the + * archive half of the record-print ruling). * * ## The order — every refusal before anything is minted or launched * * A call is judged in this order, and each step refuses with `code` and - * `status` (ADR-0112) before the next one runs. Nothing is minted, no browser - * is launched or connected and nothing is stored until every step has passed: + * `status` (ADR-0112) before the next one runs. Nothing is minted and no + * browser is launched or connected until every step has passed: * * 1. **The principal.** A human user acting for themselves: a context with a * user, not the system, `principalKind` absent or `human`, and no @@ -31,7 +34,7 @@ import type { PrincipalSessionMinter, PrintSession } from './principal-session.j * `SERVICE_UNAVAILABLE` / `503`, carrying the reason `status()` gives. * One exception keeps an engine recoverable without a restart: an engine * that failed its last probe, with everything else composed, is probed - * once more AFTER step 5 — so even that probe never starts a browser + * once more AFTER step 4 — so even that probe never starts a browser * before every other refusal has had its say. * 3. **The page.** The request names the page it expects; it must exist * (`RESOURCE_NOT_FOUND` / `404`), be a record page of the record's object, @@ -41,31 +44,20 @@ import type { PrincipalSessionMinter, PrintSession } from './principal-session.j * named record-page route ({@link printPageUrl}). * 4. **The record, read AS THE CALLER.** A record the caller cannot read and * a record that does not exist answer the same `RECORD_NOT_FOUND` / `404`, - * so the answer says nothing about a record the caller may not see. A user - * never archives what they could not read. The row this read answers is - * the one the default file name is built from ({@link defaultPrintFilename}), - * so the name never shows a value the caller may not read. - * 5. **The files opt-in, and the attach rule.** The record's object must - * declare `enable: { files: true }`, the opt-in every attachment of it - * needs (`FILES_DISABLED` / `403`), and the caller must be allowed to - * attach a file to the record, asked of the archive with the insert's own - * answers (`assertMayAttach`): may they create attachments at all - * (`PERMISSION_DENIED` / `403`), and edit access to the record, the attach - * rule (`ATTACHMENT_PARENT_ACCESS` / `403`). All are checked here so a - * refused archive never costs a render. + * so the answer says nothing about a record the caller may not see. Read + * access is the whole permission a print asks: a user who may read the + * record may print it, whether or not they may edit it. The row this read + * answers is the one the default file name is built from + * ({@link defaultPrintFilename}), so the name never shows a value the + * caller may not read. * * Then the session is minted for the caller's own principal, the page is - * rendered with it, the PDF is archived through the `file-attachments` service, - * and the session is revoked in a `finally` — after a failed render or a - * refused archive as much as after a success. A revoke that itself fails never - * replaces the print's outcome: it is logged at `error` by a fingerprint of the - * session (never its token), and the session's 60 s TTL ends it. - * - * The archive is the one writer of `sys_file` and `sys_attachment`, run AS - * THE CALLER (`attachFileAs`, `@objectstack/service-storage`): its size limit, - * its organization wall and every gate on an attachment insert judge this file - * for the requesting user exactly as they judge their own upload, and both - * rows name that user (`sys_file.owner_id`, `sys_attachment.uploaded_by`). + * rendered with it, and the session is revoked in a `finally` — after a failed + * render as much as after a success. A revoke that itself fails never replaces + * the print's outcome: it is logged at `error` by a fingerprint of the session + * (never its token), and the session's 60 s TTL ends it. The rendered bytes go + * back to the caller ({@link PrintedRecordPdf}); the HTTP door answers them as + * a download (`print-routes.ts`). */ /** A request to print one record. */ @@ -79,23 +71,28 @@ export interface PrintRecordRequest { /** The print page the caller expects the record to print on. */ page: string; /** - * The archived file's name, used as given. Defaults to the record's display - * name (ADR-0079) as a safe file name plus `.pdf`, or to + * The PDF's file name, used as given (at most + * {@link PRINT_FILENAME_MAX_CHARS} characters, and well-formed text: a lone + * UTF-16 surrogate is refused). Defaults to the record's + * display name (ADR-0079) as a safe file name plus `.pdf`, or to * `-.pdf` when the record has no display value. */ filename?: string; } -/** What a print stored. */ -export interface PrintedRecordFile { - /** The `sys_file` row's id. */ - fileId: string; - /** The `sys_attachment` row's id. */ - attachmentId: string; +/** + * What a print answers: the rendered PDF, handed back to the caller. Nothing + * is stored — no `sys_file`, no `sys_attachment`. + */ +export interface PrintedRecordPdf { + /** The PDF's bytes. */ + pdf: Uint8Array; /** The PDF's size in bytes. */ size: number; - /** The file name it was stored under. */ + /** The file name the download is offered under. */ filename: string; + /** Always `application/pdf`. */ + contentType: 'application/pdf'; } /** @@ -122,8 +119,8 @@ export interface PrintEngineStatus { export interface IPrintService { /** The engine's state, read now. */ status(): PrintEngineStatus; - /** Print one record to a PDF as the caller and attach it to the record. */ - printRecordToFile(request: PrintRecordRequest, context: ExecutionContext): Promise; + /** Print one record to a PDF as the caller and hand the PDF back. Nothing is stored. */ + printRecordToPdf(request: PrintRecordRequest, context: ExecutionContext): Promise; } /** @@ -141,7 +138,6 @@ export interface PrintServiceDeps { /** The engine for the configured placement; `null` exactly when none is configured. */ driver: ChromiumDriver | null; getEngine(): PrintEngine | undefined; - getAttachments(): (IFileAttachmentService & Partial) | undefined; getMinter(): PrincipalSessionMinter | undefined; /** Where a failed revoke is reported. */ logger?: { error(message: string): void }; @@ -168,12 +164,41 @@ export const PRINT_PROBE_TIMEOUT_MS = 15_000; const PDF_MIME_TYPE = 'application/pdf'; +/** + * The most characters a request's own `filename` may carry. The name travels + * in the download's `Content-Disposition` header, so it is bounded; 255 is the + * longest name a common file system stores. + */ +export const PRINT_FILENAME_MAX_CHARS = 255; + +/** + * A lone UTF-16 surrogate: a high surrogate with no low one after it, or a low + * one with no high one before it. A string holding one is not well-formed text: + * it has no UTF-8 spelling, so `encodeURIComponent` throws on it. + */ +const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? |`) become `_`, whitespace runs collapse to one space, * leading dots and spaces are dropped (no hidden file, no `..`), a trailing @@ -237,14 +262,12 @@ const DEFAULT_FILENAME_MAX_CHARS = 100; * with trailing dots and spaces dropped after the cut. `''` when nothing is * left. * - * The archive stores the bytes under a key built from the file's id, never its - * name, and the download header encodes the name, so this keeps the name - * readable and storable on the user's own disk: `sys_attachment.file_name` - * holds at most 255 characters, and a longer name would be refused only after - * the render. + * The download header encodes the name (RFC 5987), so this keeps the name + * readable and storable on the user's own disk, well inside + * {@link PRINT_FILENAME_MAX_CHARS}. */ function safeFileBase(name: string): string { - const cleaned = name + const cleaned = toWellFormedText(name) .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ') .replace(/[\\/:*?"<>|]/g, '_') .replace(/\s+/g, ' ') @@ -255,7 +278,7 @@ function safeFileBase(name: string): string { } /** - * The name a print is archived under when the request names none: the + * The name a print is downloaded under when the request names none: the * record's display name (ADR-0079), made safe by {@link safeFileBase}, plus * `.pdf` — `Q-2026-0042.pdf` rather than `quote_print-.pdf`. * @@ -266,8 +289,8 @@ function safeFileBase(name: string): string { * of that row, a value that is not text or a number, or one that is empty once * made safe — keeps `-.pdf`, never the `Record #` floor. * - * Two prints of one record carry the same name and are two attachments: the - * archive keys each file by its own id and holds no unique name per record. + * Two prints of one record carry the same name: the browser that saves both + * decides how to tell them apart. */ function defaultPrintFilename( objectDef: DisplayNameObjectMeta | undefined, @@ -345,39 +368,24 @@ export class PrintService implements IPrintService, IPrintDoorService { "a page cannot be rendered as the requesting user. Compose an auth plugin that provides it." ); } - const attachments = this.deps.getAttachments(); - if (!attachments) { - return ( - 'No file-attachments service is registered, so a rendered PDF has nowhere to be archived. Compose ' + - "@objectstack/service-storage's StorageServicePlugin." - ); - } - if (typeof attachments.attachFileAs !== 'function' || typeof attachments.assertMayAttach !== 'function') { - return ( - 'The registered file-attachments service cannot attach a file as the requesting user (attachFileAs / ' + - "assertMayAttach, @objectstack/service-storage's ICallerFileAttachmentService), so a PDF could only be archived " + - 'as the system. Compose a StorageServicePlugin that provides them.' - ); - } if (!this.deps.getEngine()) return 'No data engine is registered, so a page or a record cannot be read.'; return undefined; } - async printRecordToFile(request: PrintRecordRequest, context: ExecutionContext): Promise { + async printRecordToPdf(request: PrintRecordRequest, context: ExecutionContext): Promise { // ① The principal. this.refuseUnlessHumanCaller(context); // ② The engine, as configured and composed. An engine whose last probe - // failed is probed once more — but only after step ⑤, so no browser is + // failed is probed once more — but only after step ④, so no browser is // launched or connected before every other refusal has had its say. const status = this.status(); const reprobe = status.state === 'unavailable' && this.lastProbe?.ok === false && !this.missingService(); if (status.state !== 'ready' && !reprobe) { - printRefusal('SERVICE_UNAVAILABLE', 503, `Records cannot be printed to a file: ${status.reason}`); + printRefusal('SERVICE_UNAVAILABLE', 503, `Records cannot be printed to a PDF: ${status.reason}`); } const driver = this.deps.driver!; const engine = this.deps.getEngine()!; - const attachments = this.deps.getAttachments() as IFileAttachmentService & ICallerFileAttachmentService; const minter = this.deps.getMinter()!; const placement = this.deps.placement as Extract; @@ -385,41 +393,26 @@ export class PrintService implements IPrintService, IPrintDoorService { const req = validateRequest(request); const page = this.refuseUnlessPrintPage(engine, req); - // ④ The record, read as the caller. + // ④ The record, read as the caller: the whole permission a print asks. const row = await this.readAsCaller(engine, req, context); - // ⑤ The files opt-in, and the attach rule for the caller. - this.refuseUnlessFilesEnabled(engine, req.object); - await attachments.assertMayAttach(req.object, req.recordId, context); - // ② again, for an engine that failed its last probe: probe it now, so an // endpoint that came up after boot serves without a restart. if (reprobe) { const probed = await this.probe(); if (probed.state !== 'ready') { - printRefusal('SERVICE_UNAVAILABLE', 503, `Records cannot be printed to a file: ${probed.reason}`); + printRefusal('SERVICE_UNAVAILABLE', 503, `Records cannot be printed to a PDF: ${probed.reason}`); } } - // Mint, render, archive — and revoke, whatever happened. + // Mint, render — and revoke, whatever happened. Nothing is stored. const filename = req.filename ?? defaultPrintFilename(engine.registry.getObject(req.object) as DisplayNameObjectMeta | undefined, row, req); const url = printPageUrl(placement.resolved.consoleUrl, req, page); const session: PrintSession = await minter.mint(context, PRINT_SESSION_TTL_SECONDS); try { const pdf = await driver.renderPdf({ url, cookie: session.cookie, timeoutMs: PRINT_RENDER_TIMEOUT_MS }); - const attached = await attachments.attachFileAs( - { - parentObject: req.object, - parentId: req.recordId, - organizationId: nonEmptyString(context.tenantId) ? context.tenantId : null, - filename, - mimeType: PDF_MIME_TYPE, - data: pdf, - }, - context, - ); - return { fileId: attached.fileId, attachmentId: attached.attachmentId, size: attached.size, filename }; + return { pdf, size: pdf.byteLength, filename, contentType: PDF_MIME_TYPE }; } finally { await this.revokeQuietly(session, context); } @@ -427,7 +420,7 @@ export class PrintService implements IPrintService, IPrintDoorService { /** * End the minted session. A revoke that fails never replaces the print's own - * outcome — the committed archive or the refusal — and is not silent either: + * outcome — the rendered PDF or the refusal — and is not silent either: * it is logged at `error`, naming the session by a fingerprint of its token * (never the token or the cookie), and the session's own TTL ends it. */ @@ -501,25 +494,13 @@ export class PrintService implements IPrintService, IPrintDoorService { if (!row) throw recordNotFoundError(req.object, req.recordId, context); return row; } - - private refuseUnlessFilesEnabled(engine: PrintEngine, object: string): void { - const def = engine.registry.getObject(object) as { enable?: { files?: unknown } } | undefined; - if (def?.enable?.files !== true) { - printRefusal( - 'FILES_DISABLED', - 403, - `Files are not enabled on '${object}', so a printed PDF cannot be attached to its records. Declare ` + - `enable: { files: true } on the object.`, - ); - } - } } type ValidRequest = Required> & { filename?: string }; /** The request, checked field by field: a JavaScript caller can hand anything. */ function validateRequest(request: PrintRecordRequest): ValidRequest { - const fail = (message: string): never => printRefusal('VALIDATION_ERROR', 400, `printRecordToFile: ${message}`); + const fail = (message: string): never => printRefusal('VALIDATION_ERROR', 400, `printRecordToPdf: ${message}`); if (!request || typeof request !== 'object') fail('the request must be an object'); for (const field of ['app', 'object', 'recordId', 'page'] as const) { if (!nonEmptyString(request[field])) fail(`'${field}' must be a non-empty string`); @@ -527,5 +508,11 @@ function validateRequest(request: PrintRecordRequest): ValidRequest { if (request.filename !== undefined && !nonEmptyString(request.filename)) { fail("'filename' must be a non-empty string when given"); } + if (request.filename !== undefined && Array.from(request.filename).length > PRINT_FILENAME_MAX_CHARS) { + fail(`'filename' must be at most ${PRINT_FILENAME_MAX_CHARS} characters`); + } + if (request.filename !== undefined && hasLoneSurrogate(request.filename)) { + fail("'filename' must be well-formed text: it holds a lone UTF-16 surrogate, which no download header can carry"); + } return request as ValidRequest; } diff --git a/packages/spec/src/contracts/print-door-service.ts b/packages/spec/src/contracts/print-door-service.ts index 6f6f58a0026..efdd8f473db 100644 --- a/packages/spec/src/contracts/print-door-service.ts +++ b/packages/spec/src/contracts/print-door-service.ts @@ -9,8 +9,8 @@ * door needs no slot of its own. * * The door, `POST /api/v1/print/records`, prints a record's print page to a - * PDF as the signed-in caller and archives it on the record. A console action - * reaches it as a same-origin `type: 'api'` action whose `target` is that path. + * PDF as the signed-in caller and answers the PDF itself as a download; a + * print stores nothing on the record. * * A self-hosted kernel serves it from the print plugin's own mount on the * kernel's `http.server`. A hosted tenant kernel owns no socket and so has no @@ -34,8 +34,10 @@ export interface IPrintDoorService { * - It resolves the caller from the request's own credentials, the rule the * self-hosted mount applies. With no signed-in caller it answers `401`; a * sign-in that still owes an authentication step answers `403`. - * - Every refusal and answer is the door's own, in the - * `{ success, data | error: { code, message } }` envelope: a print engine + * - Every answer is the door's own. A print answers `200` with the PDF + * bytes as the body (`application/pdf`, `Content-Disposition: + * attachment`); every refusal is the + * `{ success: false, error: { code, message } }` envelope: a print engine * this deployment has not configured is the door's * `503 SERVICE_UNAVAILABLE`, as on the self-hosted mount. * - A request whose method and path do not match the door answers @@ -59,7 +61,7 @@ export interface IPrintDoorService { * * @param request - The forwarded request: the caller's credentials are in its * headers and the print request in its JSON body - * @returns The door's JSON answer + * @returns The door's answer: the PDF download, or a JSON refusal */ handlePrintDoor?(request: Request): Promise; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9285629a171..f3e9929bfe8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3416,9 +3416,6 @@ importers: '@objectstack/plugin-hono-server': specifier: workspace:* version: link:../../plugins/plugin-hono-server - '@objectstack/service-storage': - specifier: workspace:* - version: link:../service-storage '@objectstack/spec': specifier: workspace:* version: link:../../spec