Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .changeset/38894-print-downloads-no-attachment.md
Original file line number Diff line number Diff line change
@@ -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.

<!-- adr-0087: not-required (runtime-export-retired @objectstack/service-print#PrintedRecordFile, @objectstack/service-print#IPrintService.printRecordToFile) a TypeScript consumer of the print service meets the break at its own import or call; no metadata names the print service, so objectstack migrate meta has nothing to rewrite -->
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
90 changes: 36 additions & 54 deletions content/docs/ui/print-pages.mdx
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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';
Expand All @@ -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
Expand Down Expand Up @@ -141,11 +140,11 @@ const print = kernel.getService<IPrintService>('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
Expand All @@ -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
`<page>-<recordId>.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
Expand All @@ -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

Expand All @@ -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.
4 changes: 2 additions & 2 deletions examples/app-showcase/src/data/objects/invoice.object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion examples/app-showcase/src/system/translations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ export const ShowcaseTranslationBundle = {
_actions: {
showcase_generate_invoice_pdf: {
label: '生成 PDF',
successMessage: 'PDF 已附加到发票。',
successMessage: '发票已打印为 PDF。',
},
},
},
Expand Down
Loading
Loading