From ba42805929bc2667a602fc307bd6859a306b64fc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:40:40 +0000 Subject: [PATCH 01/12] feat(runtime): the REST action door relays a target's 2xx attachment byte for byte Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- packages/runtime/src/action-dispatch.ts | 28 +++- packages/runtime/src/action-execution.ts | 67 ++++++-- .../runtime/src/action-forward-attachment.ts | 146 ++++++++++++++++++ packages/runtime/src/dispatcher-plugin.ts | 22 ++- 4 files changed, 244 insertions(+), 19 deletions(-) create mode 100644 packages/runtime/src/action-forward-attachment.ts diff --git a/packages/runtime/src/action-dispatch.ts b/packages/runtime/src/action-dispatch.ts index f7c8c2128a3..9cdb84bee58 100644 --- a/packages/runtime/src/action-dispatch.ts +++ b/packages/runtime/src/action-dispatch.ts @@ -63,6 +63,7 @@ import type { AIActionConfirmation, ActionConfirmationPending } from '@objectsta import type { ExecutionContext } from '@objectstack/spec/kernel'; import * as actionExec from './action-execution.js'; import type { ActionExecutionDeps } from './action-execution.js'; +import { apiActionAttachmentResponse, type ApiActionAttachmentAnswer } from './action-forward-attachment.js'; import { actionInvocationBranch, actionInvocationBulkReading, @@ -104,8 +105,12 @@ export interface ActionRefusal { /** What a dispatched arm answered. */ export type ActionDispatchOutcome = - /** The action ran: its result, and the headers an api forward relays. */ - | { kind: 'answered'; result: unknown; headers?: Record } + /** + * The action ran: its result, and the headers an api forward relays. + * [#38894] `attachment` is the file an api forward's target answered, at + * the REST door only: the door answers it as the file, not as `result`. + */ + | { kind: 'answered'; result: unknown; headers?: Record; attachment?: ApiActionAttachmentAnswer } /** * The arm refused without a throw: the api forward's own refusals (a * forward loop, no in-process transport, a request the declaration cannot @@ -777,11 +782,17 @@ async function dispatchAdmittedAction( // named environment): the forward targets the action's own path, // so a scoped URL's environment does not cross with it. const placedEnvironment = resolverPlacedEnvironmentOf(requestContext); + // [#38894, ruling A] Only the REST door carries a file the target + // answers as an attachment; MCP's tool result and the host door's + // `{ status, body }` answer cannot, and keep the 502. const forward = await actionExec.forwardApiAction(inject, requestContext, built, { objectName, actionName, target: actionDef?.target, ...(recordId ? { recordId: String(recordId) } : {}), - }, placedEnvironment !== undefined ? { environmentId: placedEnvironment } : undefined); + }, placedEnvironment !== undefined ? { environmentId: placedEnvironment } : undefined, { relayAttachment: door === 'rest' }); if (forward.status >= 200 && forward.status < 300) { + if (forward.attachment) { + return { kind: 'answered', result: undefined, headers: forward.headers, attachment: forward.attachment }; + } return { kind: 'answered', result: actionExec.apiActionResultOf(forward), headers: forward.headers }; } return { kind: 'forward-refused', forward }; @@ -992,7 +1003,13 @@ export async function runResolvedActionAsRest( // hands off; a REST-rendered call never does. Answered as the success it // is, should a door ever set it here, and like a refusal it writes no row. if ('handedOff' in run) return { handled: true, response: deps.success(run.handedOff) }; - const { response } = restAnswerOf(deps, run.admitted, run.outcome); + // [#38894] A file an api forward's target answered: the door's answer is + // that file (`result`, a `Response` the transports write as it is), and + // its row records the status the file came with. + const attachment = run.outcome.kind === 'answered' ? run.outcome.attachment : undefined; + const { response } = attachment + ? { response: { status: attachment.status, body: undefined as any } } + : restAnswerOf(deps, run.admitted, run.outcome); // [#27908] THE INVOCATION ROW: one row for every call that cleared the // gates, whatever the arm answered. A call a gate refused writes none. const { actionDef, objectName, actionName, recordId } = run.admitted; @@ -1018,6 +1035,9 @@ export async function runResolvedActionAsRest( ? actionInvocationBulkReading(run.admitted.params, run.outcome.result) : undefined, }); + if (attachment) { + return { handled: true, result: apiActionAttachmentResponse(attachment, run.outcome.kind === 'answered' ? run.outcome.headers : undefined) }; + } return { handled: true, response }; } diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index ef9dd6cb740..164f0bf6d92 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -101,6 +101,7 @@ import type { HttpProtocolContext } from './http-dispatcher.js'; // The ONE admitted sequence every action door shares; `invokeBusinessAction` // below is its MCP door (posture `ai`). import { addressedUnknownNameRefusal, refusalOfThrown, refuseDispatchToDisabledObject, runResolvedAction, type ActionRefusal } from './action-dispatch.js'; +import { apiActionAttachmentTooLargeError, isAttachmentDisposition, readForwardAttachment, type ApiActionAttachmentAnswer } from './action-forward-attachment.js'; import { admittingCredentialKind, type AdmittingCredentialKind } from './security/admitting-credential.js'; import { ENVIRONMENT_ACTION_COORDINATE, @@ -2108,10 +2109,11 @@ export function apiActionOAuthForwardRefusal(action: any, target: string, door: export type ApiActionForwardAnswer = { status: number; /** - * The target's JSON body (`null` for an empty one). A 2xx answer that is - * not JSON is turned into the door's own 502 refusal before it gets here - * (see {@link forwardApiAction}); a non-2xx non-JSON answer carries its - * text as `{ raw }` so the refusal can quote it. + * The target's JSON body (`null` for an empty one, and for a relayed + * {@link attachment}). A 2xx answer that is not JSON is turned into the + * door's own 502 refusal before it gets here (see {@link forwardApiAction}); + * a non-2xx non-JSON answer carries its text as `{ raw }` so the refusal + * can quote it. */ body: any; /** @@ -2119,6 +2121,12 @@ export type ApiActionForwardAnswer = { * `set-cookie` is a `string[]` — one line per cookie, never comma-joined. */ headers: Record; + /** + * [#38894] The target's 2xx `Content-Disposition: attachment` answer, byte + * for byte, when the door asked for files (`relayAttachment`). Absent on + * every other answer. + */ + attachment?: ApiActionAttachmentAnswer; }; /** @@ -2187,12 +2195,15 @@ export function apiActionForwardUnavailableError( * The 502 for a target that answered 2xx with something other than JSON (a * file, HTML, a stream): the door's answer is a JSON envelope and the console's * direct fetch read such a body as `{}` — a silent loss this door refuses by name. + * [#38894] The REST door relays one such answer instead, a file sent as + * `Content-Disposition: attachment` (`./action-forward-attachment.ts`). */ export function apiActionNonJsonAnswerError(actionName: string, status: number, contentType: string | null): string { return ( `Action '${actionName}' — its target answered HTTP ${status} with ` + `${contentType ? `content-type '${contentType}'` : 'no content-type'}, not JSON. The action doors relay JSON ` + - `answers only; a target that serves a file or a page is not a \`type: 'api'\` action this door can carry.` + `answers, and the REST door also a file the target sends with \`Content-Disposition: attachment\`; a ` + + `target that serves any other body or a page is not a \`type: 'api'\` action these doors can carry.` ); } @@ -2264,10 +2275,17 @@ export function apiActionForwardLoopError(action: any, mark: string): string { * headers a target like `/admin/impersonate-user` emits — `set-auth-token` / * `set-admin-session-token` (the bearer lane) and `Set-Cookie` (the cookie * lane). Everything else about the answer stays the target's business. A 2xx - * answer that is not JSON is refused as 502 here: this door answers JSON + * answer that is not JSON is refused as 502 here: the doors answer JSON * envelopes (the console's direct fetch read such an answer as `{}`, which - * is a silent loss, not a result), and a declaration whose target streams a - * file is not an action this door can carry. + * is a silent loss, not a result). + * + * [#38894, ruling A] One 2xx non-JSON answer is carried: a file the target + * sent as `Content-Disposition: attachment`, when the door asks for files + * (`answers.relayAttachment`, the REST door only). It comes back as + * `attachment`, byte for byte, under the size bound of + * `./action-forward-attachment.ts`, which also says what is kept of its + * headers. Every other 2xx non-JSON answer, and every answer at a door that + * does not ask (MCP, the host door), is the 502 as before. */ export async function forwardApiAction( inject: (url: string, init: RequestInit) => Promise, @@ -2275,6 +2293,7 @@ export async function forwardApiAction( req: ApiActionRequest, mark: { objectName: string; actionName: string; target?: string; recordId?: string }, routing?: { environmentId?: string }, + answers?: { relayAttachment?: boolean }, ): Promise { // A caller whose credential the target's door cannot read (the table, // {@link API_FORWARD_DOOR_ACCEPTS}) is refused here, before the target is @@ -2333,6 +2352,27 @@ export async function forwardApiAction( ) : await inject(url, init); + // [#38894] A file the target answered as an attachment, at a door that + // carries files: read as bytes, never decoded as text. + if (answers?.relayAttachment === true && res.status >= 200 && res.status < 300 + && isAttachmentDisposition(res.headers.get('content-disposition'))) { + const attachment = await readForwardAttachment(res); + if (!attachment) { + return { + status: 502, + body: { + success: false, + error: { + code: standardErrorCodeForHttpStatus(502), + message: apiActionAttachmentTooLargeError(mark.actionName, res.status), + }, + }, + headers: {}, + }; + } + return { status: res.status, body: null, headers: agent ? {} : apiForwardRelayedHeaders(res), attachment }; + } + const text = await res.text(); let body: any; let isJson = true; @@ -2359,9 +2399,14 @@ export async function forwardApiAction( headers: {}, }; } - const relayed: Record = {}; // [ADR-0090 D10 rule 5] Nothing a target mints reaches an agent caller. - if (agent) return { status: res.status, body, headers: relayed }; + if (agent) return { status: res.status, body, headers: {} }; + return { status: res.status, body, headers: apiForwardRelayedHeaders(res) }; +} + +/** The credential-rotation headers a forward relays to a caller that is not an agent. */ +function apiForwardRelayedHeaders(res: Response): Record { + const relayed: Record = {}; for (const name of API_FORWARD_RELAYED_RESPONSE_HEADERS) { const value = res.headers.get(name); if (value) relayed[name] = value; @@ -2374,7 +2419,7 @@ export async function forwardApiAction( const cookies: string[] = typeof (res.headers as any).getSetCookie === 'function' ? (res.headers as any).getSetCookie() : []; if (cookies.length > 0) relayed['set-cookie'] = cookies; - return { status: res.status, body, headers: relayed }; + return relayed; } /** diff --git a/packages/runtime/src/action-forward-attachment.ts b/packages/runtime/src/action-forward-attachment.ts new file mode 100644 index 00000000000..f44a0a35ac2 --- /dev/null +++ b/packages/runtime/src/action-forward-attachment.ts @@ -0,0 +1,146 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38894, ruling A] A declared `type: 'api'` action delivers a FILE through + * the REST action door. + * + * The action doors answer JSON envelopes, and a target that answered `2xx` + * with anything else was refused as the door's own `502` + * (`apiActionNonJsonAnswerError`, `action-execution.ts`). The ruling keeps + * that refusal for every answer but one: a `2xx` that carries + * `Content-Disposition: attachment` (RFC 6266) is a file the target meant the + * caller to save, and the REST door relays it byte for byte. + * + * ## What is relayed + * + * - The target's status (any `2xx`) and its body, byte for byte. + * - Four of its headers, each only when the target sent it, as it sent it: + * `Content-Type`, `Content-Disposition`, `Cache-Control` and + * `X-Content-Type-Options` ({@link API_FORWARD_ATTACHMENT_HEADERS}). Nothing + * else of the target's answer crosses, as on the JSON relay; the + * credential-rotation headers keep their own rule (`forwardApiAction`). + * + * ## Which doors relay it + * + * The REST door only (`POST /actions/...`, the console's and the SDK's door). + * The MCP `run_action` door keeps the `502`: a tool result is JSON text, and a + * file has no place in it. The host door (`dispatchAction`) keeps it too: its + * answer is a `{ status, body }` value, not an HTTP response. The decision is + * made per door by the caller of `forwardApiAction` (`action-dispatch.ts`). + * + * ## The size bound: buffered, at most {@link API_FORWARD_ATTACHMENT_MAX_BYTES} + * + * The door has always read the target's whole answer into memory before it + * answers (the JSON relay parses it). A file is read the same way, as bytes, + * and bounded: a declared `Content-Length` over the bound is refused unread, + * and a body with no declared length is counted while it is read and refused + * once it passes the bound, its source cancelled. Exactly the bound is relayed. + * The refusal is the door's `502` ({@link apiActionAttachmentTooLargeError}): + * the target answered, and the door could not carry that answer. Buffered, + * not streamed, because the standalone server's writer sends a body in one + * piece anyway (`sendWebResponse`), and because the invocation row and the + * answer's status are settled before the first byte leaves. + */ + +/** The largest file the REST action door relays: 32 MiB. */ +export const API_FORWARD_ATTACHMENT_MAX_BYTES = 32 * 1024 * 1024; + +/** The target's answer headers a relayed file keeps, each only when the target sent it. */ +export const API_FORWARD_ATTACHMENT_HEADERS: readonly string[] = [ + 'content-type', + 'content-disposition', + 'cache-control', + 'x-content-type-options', +]; + +/** A target's `2xx` file answer, as the REST door relays it. */ +export interface ApiActionAttachmentAnswer { + status: number; + bytes: Uint8Array; + /** {@link API_FORWARD_ATTACHMENT_HEADERS}, lower-case, each only when the target sent it. */ + headers: Record; +} + +/** + * `true` when a `Content-Disposition` value's disposition type is + * `attachment` (RFC 6266 section 4.2: the type is the token before the first + * `;`, compared case-insensitively). `inline`, any other type and an absent + * header are not. + */ +export function isAttachmentDisposition(value: string | null | undefined): boolean { + if (typeof value !== 'string') return false; + return value.split(';', 1)[0].trim().toLowerCase() === 'attachment'; +} + +/** + * Read a target's file answer under `maxBytes` + * ({@link API_FORWARD_ATTACHMENT_MAX_BYTES}). `null` when it is over the + * bound; nothing past the bound is read. + */ +export async function readForwardAttachment( + res: Response, + maxBytes: number = API_FORWARD_ATTACHMENT_MAX_BYTES, +): Promise { + const declared = Number(res.headers.get('content-length') ?? Number.NaN); + if (Number.isFinite(declared) && declared > maxBytes) { + await res.body?.cancel().catch(() => undefined); + return null; + } + const chunks: Uint8Array[] = []; + let total = 0; + if (res.body) { + const reader = res.body.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => undefined); + return null; + } + chunks.push(value); + } + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + const headers: Record = {}; + for (const name of API_FORWARD_ATTACHMENT_HEADERS) { + const value = res.headers.get(name); + if (value !== null) headers[name] = value; + } + return { status: res.status, bytes, headers }; +} + +/** The `502` sentence for a file answer over {@link API_FORWARD_ATTACHMENT_MAX_BYTES}. */ +export function apiActionAttachmentTooLargeError(actionName: string, status: number): string { + return ( + `Action '${actionName}' — its target answered HTTP ${status} with a file larger than the action door ` + + `relays (${API_FORWARD_ATTACHMENT_MAX_BYTES} bytes). The file was not delivered. Call the target ` + + `directly to download a file this large.` + ); +} + +/** + * The REST door's HTTP answer for a relayed file: the target's status, bytes + * and kept headers, after the credential-rotation headers the forward relays + * (one line per `Set-Cookie`). + */ +export function apiActionAttachmentResponse( + file: ApiActionAttachmentAnswer, + relayed: Record = {}, +): Response { + const headers = new Headers(); + for (const [name, value] of Object.entries(relayed)) { + if (Array.isArray(value)) for (const line of value) headers.append(name, line); + else headers.set(name, value); + } + for (const [name, value] of Object.entries(file.headers)) headers.set(name, value); + // A copy the Response owns, over a plain `ArrayBuffer`. + const body = new Uint8Array(file.bytes.byteLength); + body.set(file.bytes); + return new Response(body, { status: file.status, headers }); +} diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index 752ec15ba0f..afeffd46d4f 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -2220,6 +2220,20 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // back to `system` (#2701). The scoped-URL `:environmentId` rides on // `req.params` and is picked up by `prepareResolverHints`, exactly as // the automation routes handle it. + // [#38894, ruling A] The `/actions` door's answer: a file an api + // action's target sent as an attachment comes back from the domain + // as a `Response` (`HttpDispatcherResult.result`), written here as + // it is, status, headers and bytes, after the security headers, so + // the target's own `X-Content-Type-Options` / `Cache-Control` stand. + // `sendResult` writes every other answer as JSON, as before. + const sendActionResult = async (result: HttpDispatcherResult, res: any): Promise => { + if (result.handled && result.result instanceof Response) { + if (securityHeaders) for (const [k, v] of Object.entries(securityHeaders)) res.header(k, v); + await sendWebResponse(result.result, res); + return; + } + sendResult(result, res); + }; const registerActionRoutes = (base: string) => { // [#3913 follow-up] The OBJECT-LESS shape, with the object // segment left empty: `POST /actions//:action`. This is the URL @@ -2240,7 +2254,7 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu server!.post(`${base}/actions//:action`, async (req: any, res: any) => { try { const result = await dispatcher.dispatch('POST', `/actions//${req.params.action}`, deferRequestBody(req), req.query, { request: req }); - sendResult(result, res); + await sendActionResult(result, res); } catch (err: any) { errorResponse(err, res); } @@ -2248,7 +2262,7 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu server!.post(`${base}/actions/:object/:action`, async (req: any, res: any) => { try { const result = await dispatcher.dispatch('POST', `/actions/${req.params.object}/${req.params.action}`, deferRequestBody(req), req.query, { request: req }); - sendResult(result, res); + await sendActionResult(result, res); } catch (err: any) { errorResponse(err, res); } @@ -2256,7 +2270,7 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu server!.post(`${base}/actions/:object/:action/:recordId`, async (req: any, res: any) => { try { const result = await dispatcher.dispatch('POST', `/actions/${req.params.object}/${req.params.action}/${req.params.recordId}`, deferRequestBody(req), req.query, { request: req }); - sendResult(result, res); + await sendActionResult(result, res); } catch (err: any) { errorResponse(err, res); } @@ -2281,7 +2295,7 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // three segments); before, this host answered the // transport's unmatched 404 and a catch-all host ran // the call with the tail ignored. - sendResult(result, res); + await sendActionResult(result, res); } catch (err: any) { errorResponse(err, res); } From ac857b869cc29bd875b0ec0be78b0f6e40799736 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:55:45 +0000 Subject: [PATCH 02/12] test: pin the action door's attachment relay through the runtime door and both transports Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- ...-door-attachment-38894.conformance.test.ts | 233 ++++++++++++++++++ .../src/domains/api-action-forward.test.ts | 178 ++++++++++++- 2 files changed, 408 insertions(+), 3 deletions(-) create mode 100644 packages/qa/http-conformance/src/action-door-attachment-38894.conformance.test.ts 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 new file mode 100644 index 00000000000..33cd960bc0d --- /dev/null +++ b/packages/qa/http-conformance/src/action-door-attachment-38894.conformance.test.ts @@ -0,0 +1,233 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38894, ruling A] A declared `type: 'api'` action delivers a FILE through + * the REST action door, over a real transport. + * + * The REST door relays a target's `2xx` answer that carries + * `Content-Disposition: attachment` byte for byte; every other non-JSON `2xx` + * stays the door's `502`. The door answers such a file as a `Response` + * (`HttpDispatcherResult.result`), and each transport must write it as it is: + * + * - **self-hosted**: `HonoServerPlugin` + `createDispatcherPlugin`, the + * composition `objectstack serve` runs, where the dispatcher's own + * `/actions` mounts write the answer (`dispatcher-plugin.ts`), over a real + * socket; + * - **catch-all**: `createHonoApp` over the same kind of kernel, whose + * catch-all writes a domain's `Response` as it is (`@objectstack/hono`). + * + * The target is a plain route on the kernel's `http.server` (the forward goes + * in-process into that server's raw app), answering a binary body whose bytes + * a text decode would mangle. What this pins, on both transports: the bytes + * and the four file headers arrive unchanged; a non-attachment non-JSON `2xx` + * 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`. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +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 type { IHttpServer } from '@objectstack/spec/contracts'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const BOOT_TIMEOUT = 60_000; +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 ACTIONS = [ + { 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: 'download_gated', label: 'Gated', objectName: OBJECT, type: 'api', method: 'POST', target: `${API}/c38894/file`, + requiredPermissions: ['c38894_download'], + }, +]; + +/** + * The objects the authz resolver reads on every request, with only the columns + * it reads, registered after boot (the shape `conformance.integration.test.ts` + * spells, for the same reason: this stack stubs the `auth` service instead of + * composing the auth and security plugins). + */ +const authzResolverObjects = [ + { + owner: '@objectstack/plugin-auth', + def: { + name: 'sys_user', + label: 'User', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + email: { name: 'email', type: 'text' as const }, + }, + }, + }, + { + owner: '@objectstack/plugin-auth', + def: { + name: 'sys_member', + label: 'Member', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + user_id: { name: 'user_id', type: 'text' as const }, + organization_id: { name: 'organization_id', type: 'text' as const }, + role: { name: 'role', type: 'text' as const }, + }, + }, + }, + { + owner: '@objectstack/plugin-security', + def: { + name: 'sys_user_position', + label: 'User Position', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + user_id: { name: 'user_id', type: 'text' as const }, + position: { name: 'position', type: 'text' as const }, + organization_id: { name: 'organization_id', type: 'text' as const }, + }, + }, + }, + { + owner: '@objectstack/plugin-security', + def: { + name: 'sys_user_permission_set', + label: 'User Permission Set', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + user_id: { name: 'user_id', type: 'text' as const }, + permission_set_id: { name: 'permission_set_id', type: 'text' as const }, + organization_id: { name: 'organization_id', type: 'text' as const }, + }, + }, + }, + { + owner: '@objectstack/plugin-security', + def: { + name: 'sys_position', + label: 'Position', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + name: { name: 'name', type: 'text' as const }, + active: { name: 'active', type: 'boolean' as const }, + organization_id: { name: 'organization_id', type: 'text' as const }, + }, + }, + }, +] as const; + +interface Door { + kernel: LiteKernel; + send: (path: string, init?: RequestInit) => Promise; + targetCalls: () => number; +} + +async function boot(shape: 'self-hosted' | 'catch-all'): Promise { + let calls = 0; + const kernel = new LiteKernel(); + kernel.use(new ObjectQLPlugin()); + // Every request is a signed-in member (the transport is under test, not sign-in). + kernel.use({ + metadata: { name: 'test-auth', version: '1.0.0' }, + init: (c: any) => c.registerService('auth', { api: { getSession: async () => ({ user: { id: 'u_member' } }) } }), + } as any); + kernel.use(new HonoServerPlugin({ port: 0 })); + if (shape === 'self-hosted') kernel.use(createDispatcherPlugin({ prefix: API, securityHeaders: false })); + kernel.use({ + name: 'com.test.c38894-target', + version: '0.0.0', + init: () => undefined, + start: (c: any) => { + const server = c.getService('http.server') as IHttpServer; + server.post(`${API}/c38894/file`, async (_req, res) => { + calls++; + res.status(200); + res.header('Content-Type', 'application/pdf'); + res.header('Content-Disposition', DISPOSITION); + res.header('Cache-Control', 'no-store'); + res.header('X-Content-Type-Options', 'nosniff'); + await (res as any).send(PDF); + }); + server.post(`${API}/c38894/csv`, async (_req, res) => { + calls++; + res.status(200); + await (res as any).send('id,name\n1,ada\n'); + }); + }, + } as any); + await kernel.bootstrap(); + + const ql = kernel.getService('objectql'); + const driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + ql.registerDriver(driver as never, true); + ql.registerObject({ name: OBJECT, label: 'Doc', fields: { title: { type: 'text', label: 'Title' } }, actions: ACTIONS } as never); + await ql.syncObjectSchema(OBJECT); + for (const o of authzResolverObjects) ql.registry.registerObject(o.def as never, o.owner); + await installDefaultOrganization(ql as never); + + let send: Door['send']; + if (shape === 'catch-all') { + const app = createHonoApp({ kernel: kernel as never, prefix: API, cors: false }); + send = async (path, init) => app.request(`http://localhost${path}`, init); + } else { + const server = kernel.getService('http.server'); + const base = `http://127.0.0.1:${server.getPort!()}`; + send = (path, init) => fetch(`${base}${path}`, init); + } + return { kernel, send, targetCalls: () => calls }; +} + +const call = (body: unknown = {}): RequestInit => ({ + method: 'POST', + headers: { 'content-type': 'application/json', authorization: 'Bearer member' }, + body: JSON.stringify(body), +}); + +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); + afterAll(async () => { + await Promise.race([door?.kernel.shutdown(), new Promise((resolve) => setTimeout(resolve, 10_000))]); + }); + + it('a 2xx attachment arrives with identical bytes, status and file headers', async () => { + const before = door.targetCalls(); + const res = await door.send(`${API}/actions/${OBJECT}/download_pdf`, call()); + const bytes = new Uint8Array(await res.arrayBuffer()); + expect(res.status, new TextDecoder().decode(bytes)).toBe(200); + expect(door.targetCalls()).toBe(before + 1); + expect(bytes).toEqual(PDF); + expect(res.headers.get('content-type')).toBe('application/pdf'); + expect(res.headers.get('content-disposition')).toBe(DISPOSITION); + expect(res.headers.get('cache-control')).toBe('no-store'); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + }); + + it('a 2xx non-JSON answer that is not an attachment still answers the door\'s 502', async () => { + const res = await door.send(`${API}/actions/${OBJECT}/download_csv`, call()); + const body = (await res.json()) as any; + expect(res.status).toBe(502); + // The content type is the transport's (Hono's `send` of a string writes + // `text/html`); what the door decides is that it is not JSON. + expect(body.error.code).toBe('EXTERNAL_SERVICE_ERROR'); + expect(body.error.message).toContain('not JSON'); + expect(res.headers.get('content-disposition')).toBeNull(); + }); + + it('a caller the door refuses gets the refusal, never the file, and the target is never called', async () => { + const before = door.targetCalls(); + const res = await door.send(`${API}/actions/${OBJECT}/download_gated`, call()); + expect(res.headers.get('content-disposition')).toBeNull(); + const body = (await res.json()) as any; + expect(res.status, JSON.stringify(body)).toBe(403); + expect(body.success).toBe(false); + expect(door.targetCalls()).toBe(before); + }); +}); diff --git a/packages/runtime/src/domains/api-action-forward.test.ts b/packages/runtime/src/domains/api-action-forward.test.ts index 4b8dc8d7c4b..7feea1eee39 100644 --- a/packages/runtime/src/domains/api-action-forward.test.ts +++ b/packages/runtime/src/domains/api-action-forward.test.ts @@ -47,6 +47,7 @@ import { API_FORWARD_MARK_HEADER, apiForwardAgentOf, } from '../action-execution.js'; +import { API_FORWARD_ATTACHMENT_MAX_BYTES, isAttachmentDisposition, readForwardAttachment } from '../action-forward-attachment.js'; import { FORWARD_CREDENTIAL_HEADER, redeemForwardCredential } from '@objectstack/rest'; import { standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; import { ActionActivationProjection } from '@objectstack/objectql'; @@ -126,7 +127,7 @@ type Injected = { url: string; init: RequestInit }; function boot(opts: { disabled?: string[]; /** What the target answers: status, JSON body, extra response headers. */ - answer?: { status?: number; body?: unknown; text?: string; headers?: Array<[string, string]> }; + answer?: { status?: number; body?: unknown; text?: string; bytes?: Uint8Array; headers?: Array<[string, string]> }; noServer?: boolean; /** Actions declared on the object beside the shared roster above. */ extraActions?: unknown[]; @@ -142,8 +143,11 @@ function boot(opts: { injected.push({ url, init }); // `text` is a raw (non-JSON) body with the caller's own content-type; // otherwise the JSON `body` under `application/json`. - const raw = typeof answer.text === 'string'; - return new Response(raw ? answer.text : JSON.stringify(answer.body ?? { success: true, data: { ok: true } }), { + // [#38894] `bytes` is a raw binary body, sent as given. + const raw = typeof answer.text === 'string' || answer.bytes !== undefined; + const payload = answer.bytes !== undefined ? new Uint8Array(answer.bytes) + : raw ? answer.text : JSON.stringify(answer.body ?? { success: true, data: { ok: true } }); + return new Response(payload, { status: answer.status ?? 200, headers: [...(raw ? [] : [['content-type', 'application/json'] as [string, string]]), ...(answer.headers ?? [])], }); @@ -420,6 +424,174 @@ describe('door 1 — REST `POST /actions/:object/:action` forwards a same-origin }); }); +describe('[#38894] a target\'s 2xx `Content-Disposition: attachment` answer: the REST door relays the file, MCP keeps the 502', () => { + // Every byte value a text decode would mangle: a NUL, an invalid UTF-8 + // lead byte, a lone continuation byte, CR LF, and the PDF magic. + 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 FILE_HEADERS: Array<[string, string]> = [ + ['content-type', 'application/pdf'], + ['content-disposition', DISPOSITION], + ['cache-control', 'no-store'], + ['x-content-type-options', 'nosniff'], + ['x-unrelated', 'not relayed'], + ]; + const PRINT_LEAD = { + name: 'print_lead', label: 'Print', objectName: OBJECT, type: 'api', method: 'POST', + target: '/api/v1/print/records', recordIdParam: 'recordId', + ai: { exposed: true, description: 'Print the lead.' }, + }; + const GATED_PRINT = { ...PRINT_LEAD, name: 'print_lead_gated', requiredPermissions: ['lead_print'] }; + const bootFile = (answer: Parameters[0]['answer'], opts: Parameters[0] = {}) => + boot({ ...opts, answer, extraActions: [PRINT_LEAD, GATED_PRINT] }); + const runViaMcp = async (h: ReturnType, name: string, input: any = {}) => { + const deps: any = { + resolveService: async (_ctx: unknown, service: string) => + service === 'metadata' ? h.metadata + : service === 'automation' ? null + : service === 'http.server' ? { getRawApp: () => ({ request: h.request }) } + : h.ql, + getObjectQL: async () => h.ql, + }; + return invokeBusinessAction(deps, CTX() as any, name, input, { + driver: h.ql, + ec: { userId: 'u_agent', tenantId: 'org_1', systemPermissions: [] }, + getMeta: () => h.metadata, + callData: async (_a: string, p: any) => ({ object: p?.object, id: p?.id, record: { id: p?.id } }), + }); + }; + + it('REST: relays the status, the bytes and the four file headers exactly as the target sent them', async () => { + const { dispatcher, injected } = bootFile({ status: 200, bytes: PDF, headers: FILE_HEADERS }); + + const res: any = await dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + + expect(injected).toHaveLength(1); + expect(res?.handled).toBe(true); + expect(res?.response, 'a file is not written as a JSON envelope').toBeUndefined(); + expect(res?.result).toBeInstanceOf(Response); + const file = res.result as Response; + expect(file.status).toBe(200); + expect(new Uint8Array(await file.arrayBuffer())).toEqual(PDF); + expect(file.headers.get('content-type')).toBe('application/pdf'); + expect(file.headers.get('content-disposition')).toBe(DISPOSITION); + expect(file.headers.get('cache-control')).toBe('no-store'); + expect(file.headers.get('x-content-type-options')).toBe('nosniff'); + expect(file.headers.get('x-unrelated')).toBeNull(); + }); + + it('REST: keeps a 2xx status other than 200, and relays the credential rotation beside the file', async () => { + const { dispatcher } = bootFile({ + status: 201, bytes: PDF, + headers: [...FILE_HEADERS, ['set-cookie', 'a=1; Path=/'], ['set-cookie', 'b=2; Path=/'], ['set-auth-token', 'rotated']], + }); + + const res: any = await dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + + const file = res.result as Response; + expect(file.status).toBe(201); + expect(file.headers.getSetCookie()).toEqual(['a=1; Path=/', 'b=2; Path=/']); + expect(file.headers.get('set-auth-token')).toBe('rotated'); + expect(new Uint8Array(await file.arrayBuffer())).toEqual(PDF); + }); + + it('REST: a non-JSON 2xx that is NOT an attachment still answers the 502 (an inline PDF, a bare body)', async () => { + for (const headers of [ + [['content-type', 'application/pdf'], ['content-disposition', 'inline; filename="x.pdf"']], + [['content-type', 'application/pdf']], + ] as Array>) { + const { dispatcher } = bootFile({ status: 200, bytes: PDF, headers }); + + const res: any = await dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + + expect(res?.result, JSON.stringify(headers)).toBeUndefined(); + expect(statusOf(res)).toBe(502); + expect(codeOf(res)).toBe(standardErrorCodeForHttpStatus(502)); + expect(messageOf(res)).toContain('not JSON'); + } + }); + + it('REST: a non-2xx answer carrying an attachment header is the target\'s refusal, never a file', async () => { + const { dispatcher } = bootFile({ status: 404, text: 'gone', headers: [['content-type', 'text/plain'], ['content-disposition', DISPOSITION]] }); + + const res: any = await dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + + expect(res?.result).toBeUndefined(); + expect(statusOf(res)).toBe(404); + }); + + it('REST: a refused caller gets the refusal, and the target is never called (switched off; a capability it lacks)', async () => { + const off = bootFile({ status: 200, bytes: PDF, headers: FILE_HEADERS }, { disabled: [PRINT_LEAD.name] }); + const refusedOff: any = await off.dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + expect(refusedOff?.result).toBeUndefined(); + expect(statusOf(refusedOff)).toBe(409); + expect(codeOf(refusedOff)).toBe('ACTION_DISABLED'); + expect(off.request).not.toHaveBeenCalled(); + + const gated = bootFile({ status: 200, bytes: PDF, headers: FILE_HEADERS }); + const refusedGate: any = await gated.dispatcher.handleActions(`/${OBJECT}/${GATED_PRINT.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + expect(refusedGate?.result).toBeUndefined(); + expect(statusOf(refusedGate)).toBe(403); + expect(gated.request).not.toHaveBeenCalled(); + }); + + it('MCP `run_action`: the same attachment answer is still refused 502, and no byte of it rides the throw', async () => { + const h = bootFile({ status: 200, bytes: PDF, headers: FILE_HEADERS }); + + const thrown = await runViaMcp(h, PRINT_LEAD.name, { recordId: 'lead 7' }).catch((e) => e); + + expect(h.injected).toHaveLength(1); + expect(thrown).toBeInstanceOf(Error); + expect((thrown as any).status).toBe(502); + expect((thrown as any).code).toBe(standardErrorCodeForHttpStatus(502)); + expect(String((thrown as any).message)).toContain('application/pdf'); + expect(String((thrown as any).message)).toContain('not JSON'); + }); + + it('the size bound: a declared length over it is refused unread, a counted body once it passes, exactly the bound is read whole', async () => { + expect(API_FORWARD_ATTACHMENT_MAX_BYTES).toBe(32 * 1024 * 1024); + const declaredOver = new Response(new Uint8Array(4), { headers: { 'content-length': String(API_FORWARD_ATTACHMENT_MAX_BYTES + 1) } }); + expect(await readForwardAttachment(declaredOver)).toBeNull(); + + let pulled = 0; + const counted = new Response(new ReadableStream({ + pull(controller) { + pulled++; + controller.enqueue(new Uint8Array(4)); + if (pulled === 10) controller.close(); + }, + })); + expect(await readForwardAttachment(counted, 7)).toBeNull(); + expect(pulled, 'reading stopped once the bound was passed').toBeLessThan(10); + + const exact = await readForwardAttachment(new Response(new Uint8Array([1, 2, 3, 4, 5, 6, 7])), 7); + expect(exact?.bytes).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7])); + }); + + it('REST: a file over the bound answers the door\'s 502 naming the bound, never a truncated file', async () => { + const { dispatcher } = bootFile({ + status: 200, bytes: PDF, + headers: [...FILE_HEADERS, ['content-length', String(API_FORWARD_ATTACHMENT_MAX_BYTES + 1)]], + }); + + const res: any = await dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + + expect(res?.result).toBeUndefined(); + expect(statusOf(res)).toBe(502); + expect(messageOf(res)).toContain(String(API_FORWARD_ATTACHMENT_MAX_BYTES)); + }); + + it('isAttachmentDisposition reads the disposition type alone, case-insensitively (RFC 6266)', () => { + expect(isAttachmentDisposition('attachment')).toBe(true); + expect(isAttachmentDisposition('Attachment; filename="a.pdf"')).toBe(true); + expect(isAttachmentDisposition(' attachment ;filename=a.pdf')).toBe(true); + expect(isAttachmentDisposition('inline; filename="attachment.pdf"')).toBe(false); + expect(isAttachmentDisposition('attachments')).toBe(false); + expect(isAttachmentDisposition('')).toBe(false); + expect(isAttachmentDisposition(null)).toBe(false); + }); +}); + describe('apiActionResultOf — a 2xx answer read as the action\'s result', () => { const at200 = (body: unknown) => ({ status: 200, body, headers: {} }); From 3a1000fa59994537bedddf6d3fff367f8300d02e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:05:35 +0000 Subject: [PATCH 03/12] feat(app-shell): the console saves an action's attachment answer as a download Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- ...ActionRuntime.apiActionDoor-27611.test.tsx | 106 ++++++++++++++ .../src/hooks/useConsoleActionRuntime.tsx | 11 ++ .../app-shell/src/utils/apiActionDoor.ts | 133 +++++++++++++++++- 3 files changed, 247 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx index 406a257d6e4..e9e51c27c3e 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx @@ -360,3 +360,109 @@ describe('objectstack#34706 — the invitation inbox accept, refused for an unve expect(out).toEqual({ success: false, error: 'You are not the recipient of the invitation' }); }); }); + +describe('objectstack#38894 — a file answer is saved as a download, a JSON answer reads as before', () => { + const PRINT = { name: 'print_invoice', label: 'Generate PDF', type: 'api', target: '/api/v1/print/records', refreshAfter: true }; + const PRINT_OBJECTS = [{ name: 'showcase_invoice', actions: [PRINT] }]; + const PDF = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x00, 0xff]); + + let created: Blob[]; + let revoked: string[]; + let clicked: Array<{ href: string; download: string }>; + beforeEach(() => { + created = []; + revoked = []; + clicked = []; + (URL as any).createObjectURL = vi.fn((blob: Blob) => { + created.push(blob); + return `blob:test/${created.length}`; + }); + (URL as any).revokeObjectURL = vi.fn((url: string) => { revoked.push(url); }); + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { + clicked.push({ href: this.getAttribute('href') ?? '', download: this.download }); + }); + }); + + const fileAnswer = (headers: Record, status = 200) => + authFetchSpy.mockResolvedValue(new Response(PDF, { status, headers })); + const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + + it('the door\'s relayed attachment is saved under its RFC 5987 name, the URL revoked, and the click succeeds', async () => { + fileAnswer({ + 'content-type': 'application/pdf', + 'content-disposition': 'attachment; filename="invoice.pdf"; filename*=UTF-8\'\'%E5%8F%91%E7%A5%A8%20INV-1.pdf', + }); + const { result, onRefresh } = mount('showcase_invoice', PRINT_OBJECTS); + + const out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + await settle(); + + expect(sent().url.endsWith(`${DOOR}showcase_invoice/print_invoice`)).toBe(true); + expect(clicked).toEqual([{ href: 'blob:test/1', download: '发票 INV-1.pdf' }]); + expect(new Uint8Array(await created[0].arrayBuffer())).toEqual(PDF); + expect(revoked).toEqual(['blob:test/1']); + expect(document.querySelector('a[download]')).toBeNull(); + expect(out).toEqual({ success: true, data: undefined, reload: true }); + expect(onRefresh).toHaveBeenCalledTimes(1); + }); + + it('falls back to the plain `filename`, and to `download` when the header names none', async () => { + fileAnswer({ 'content-type': 'application/pdf', 'content-disposition': 'attachment; filename="a\\"b/c.pdf"' }); + const first = mount('showcase_invoice', PRINT_OBJECTS); + await click(first.result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + + authFetchSpy.mockReset(); + fileAnswer({ 'content-type': 'application/pdf', 'content-disposition': 'attachment' }); + const second = mount('showcase_invoice', PRINT_OBJECTS); + await click(second.result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(clicked.map((c) => c.download)).toEqual(['a"b_c.pdf', 'download']); + }); + + it('a door answer whose disposition the browser cannot read (cross-origin) is still the relayed file when it is not JSON', async () => { + fileAnswer({ 'content-type': 'application/pdf' }); + const { result } = mount('showcase_invoice', PRINT_OBJECTS); + + const out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(clicked).toEqual([{ href: 'blob:test/1', download: 'download' }]); + expect(out.success).toBe(true); + }); + + it('a JSON door answer is read as before: its data, no download', async () => { + authFetchSpy.mockResolvedValue(new Response(JSON.stringify({ success: true, data: { printed: true } }), { + status: 200, headers: { 'content-type': 'application/json; charset=UTF-8' }, + })); + const { result } = mount('showcase_invoice', PRINT_OBJECTS); + + const out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(out).toEqual({ success: true, data: { printed: true }, reload: true }); + expect(clicked).toEqual([]); + expect(URL.createObjectURL).not.toHaveBeenCalled(); + }); + + it('a door refusal is never saved, whatever its headers say', async () => { + authFetchSpy.mockResolvedValue(new Response(JSON.stringify({ success: false, error: { code: 'EXTERNAL_SERVICE_ERROR', message: 'not JSON' } }), { + status: 502, headers: { 'content-type': 'application/json', 'content-disposition': 'attachment; filename="x.pdf"' }, + })); + const { result } = mount('showcase_invoice', PRINT_OBJECTS); + + const out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(out.success).toBe(false); + expect(clicked).toEqual([]); + }); + + it('the direct fetch (a click that names no declared action) saves a target\'s attachment instead of reporting an empty success', async () => { + fileAnswer({ 'content-type': 'application/pdf', 'content-disposition': "attachment; filename*=utf-8'en'report%20Q1.pdf" }); + const { result, onRefresh } = mount('showcase_invoice', []); + + const out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + + expect(sent().url).toBe('/api/v1/print/records'); + expect(clicked).toEqual([{ href: 'blob:test/1', download: 'report Q1.pdf' }]); + expect(out).toEqual({ success: true, reload: true }); + expect(onRefresh).toHaveBeenCalledTimes(1); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx index ccb3d4916b1..a177d3337d7 100644 --- a/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx +++ b/ui/packages/app-shell/src/hooks/useConsoleActionRuntime.tsx @@ -60,7 +60,9 @@ import { invitationVerifyEmailPromptPath, isAcceptNeedsVerifiedEmail } from '../ import { findDeclaredApiAction, isSameOriginApiTarget, + isAttachmentAnswer, readApiActionDoorSuccess, + saveAttachmentAnswer, sendApiActionThroughDoor, } from '../utils/apiActionDoor.js'; import { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; @@ -624,6 +626,15 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons try { body = await res.json(); } catch { /* response body not JSON */ } return refused(res, body); } + // objectstack#38894 — a target that answers a file as an attachment + // (a print route's PDF) is saved as a download, the way the action + // door's relayed file is: reading it as JSON reported a success with + // no file. + if (isAttachmentAnswer(res)) { + await saveAttachmentAnswer(res); + if (action.refreshAfter !== false) refresh(); + return { success: true, reload: action.refreshAfter !== false }; + } const json = await res.json().catch(() => ({})); // A business rejection can arrive as HTTP 200 with `success: false` // (objectstack#3913). `res.ok` alone misses it, so the call reported diff --git a/ui/packages/app-shell/src/utils/apiActionDoor.ts b/ui/packages/app-shell/src/utils/apiActionDoor.ts index 82d30ed8bd0..a1e6dd4398e 100644 --- a/ui/packages/app-shell/src/utils/apiActionDoor.ts +++ b/ui/packages/app-shell/src/utils/apiActionDoor.ts @@ -55,6 +55,15 @@ * entitlement dialog, `apiActionFailureMessage` and `refreshAfter` — and the * raw answer is handed back here for that. A 2xx is read once, here, for both * hosts ({@link readApiActionDoorSuccess}). + * + * ## A file answer is saved, not read (objectstack#38894, ruling A) + * + * The door relays a target's `2xx` answer that carries + * `Content-Disposition: attachment` byte for byte (a print route's PDF, an + * export), and refuses every other non-JSON `2xx` as its own `502`. So a door + * answer that is an attachment is saved as a download + * ({@link saveAttachmentAnswer}) and reads as a success with no data; the + * direct fetch saves a target's own attachment answer the same way. */ import { createServerActionHandler, interpretActionResponse } from '@object-ui/core'; @@ -145,16 +154,132 @@ export interface ApiActionDoorInput { params: Record; } +/** The file a door or target answer was saved as. */ +export interface SavedAttachment { + filename: string; + size: number; +} + /** The door's answer, raw, or the dispatcher's own result when none arrived. */ export type ApiActionDoorExchange = - | { answered: true; res: { ok: boolean; status: number }; json: unknown } + | { answered: true; res: { ok: boolean; status: number }; json: unknown; download?: SavedAttachment } | { answered: false; result: ActionResult }; +/** + * The slice of an answer the attachment reader uses: a WHATWG `Response`. + * Both members are optional so a transport stand-in that has neither reads + * as a JSON answer, as before. + */ +interface AttachmentReadable { + ok: boolean; + status: number; + headers?: { get(name: string): string | null }; + blob?: () => Promise; +} + +/** + * `true` for a `2xx` answer whose `Content-Disposition` type is `attachment` + * (RFC 6266: the token before the first `;`, case-insensitive). + */ +export function isAttachmentAnswer(res: AttachmentReadable): boolean { + if (!res.ok || typeof res.headers?.get !== 'function' || typeof res.blob !== 'function') return false; + const disposition = res.headers.get('content-disposition'); + return typeof disposition === 'string' && disposition.split(';', 1)[0].trim().toLowerCase() === 'attachment'; +} + +/** + * `true` for the door's `2xx` answer that is a relayed file: an attachment, + * or, when the browser cannot read `Content-Disposition` (a cross-origin + * console whose server does not expose it), a body whose `Content-Type` is not + * JSON — the door answers nothing else that way. + */ +function isDoorFileAnswer(res: AttachmentReadable): boolean { + if (isAttachmentAnswer(res)) return true; + if (!res.ok || typeof res.headers?.get !== 'function' || typeof res.blob !== 'function') return false; + const type = res.headers.get('content-type'); + if (typeof type !== 'string' || type.trim() === '') return false; + const media = type.split(';', 1)[0].trim().toLowerCase(); + return media !== 'application/json' && !media.endsWith('+json'); +} + +const FALLBACK_FILENAME = 'download'; + +/** A filename safe to hand the browser: no path separator, no control character. */ +function safeFilename(name: string): string { + const cleaned = Array.from(name.replace(/[\\/]/g, '_')) + .filter((char) => { + const code = char.codePointAt(0) ?? 0; + return code > 0x1f && code !== 0x7f; + }) + .join('') + .trim(); + return cleaned === '' ? FALLBACK_FILENAME : cleaned; +} + +/** + * The filename a `Content-Disposition` value names: its RFC 5987 + * `filename*` (`charset'language'percent-encoded`, UTF-8 decoded), else its + * plain `filename` (quoted or a token), else `download`. + */ +export function attachmentFilename(disposition: string | null | undefined): string { + if (typeof disposition !== 'string') return FALLBACK_FILENAME; + const extended = /(?:^|;)\s*filename\*\s*=\s*("?)([^";]*)\1/i.exec(disposition); + if (extended) { + const parts = extended[2].trim().split("'"); + if (parts.length === 3) { + try { + const decoded = decodeURIComponent(parts[2]); + if (decoded.trim() !== '') return safeFilename(decoded); + } catch { + // A malformed escape: fall back to the plain parameter. + } + } + } + const plain = /(?:^|;)\s*filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]*))/i.exec(disposition); + if (plain) { + const value = plain[1] !== undefined ? plain[1].replace(/\\(.)/g, '$1') : (plain[2] ?? '').trim(); + if (value.trim() !== '') return safeFilename(value); + } + return FALLBACK_FILENAME; +} + +/** + * Save an attachment answer as a download: its body as a `Blob`, an object + * URL for it, an anchor whose `download` names the file + * ({@link attachmentFilename}), clicked, then the URL revoked. + */ +export async function saveAttachmentAnswer(res: AttachmentReadable): Promise { + const blob = await res.blob!(); + const filename = attachmentFilename(res.headers?.get('content-disposition')); + const url = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = filename; + anchor.rel = 'noopener'; + anchor.style.display = 'none'; + document.body.appendChild(anchor); + try { + anchor.click(); + } finally { + anchor.remove(); + // After the click has handed the URL to the download, never before it. + setTimeout(() => URL.revokeObjectURL(url), 0); + } + return { filename, size: blob.size }; +} + /** Send a declared same-origin api click through the action door. */ export async function sendApiActionThroughDoor(input: ApiActionDoorInput): Promise { - let answered: { res: { ok: boolean; status: number }; json: unknown } | undefined; + let answered: { res: { ok: boolean; status: number }; json: unknown; download?: SavedAttachment } | undefined; const keepAnswer: ServerActionFetch = async (url, init) => { - const res = await input.fetch(url, init); + const res: AttachmentReadable & { json(): Promise } = await input.fetch(url, init); + // A relayed file is saved and reads as a success with no data: its body + // is bytes, never handed to the JSON reader. + if (isDoorFileAnswer(res)) { + const download = await saveAttachmentAnswer(res); + answered = { res: { ok: res.ok, status: res.status }, json: null, download }; + return { ok: res.ok, status: res.status, json: async () => null }; + } const json = await res.json().catch(() => null); answered = { res: { ok: res.ok, status: res.status }, json }; return { ok: res.ok, status: res.status, json: async () => json }; @@ -182,6 +307,8 @@ export function readApiActionDoorSuccess( answer: { res: { ok: boolean; status: number }; json: unknown }, label: string, ): { ok: true; data: unknown } | { ok: false; error: string } { + // objectstack#38894 — a saved file is the success, with no data to read. + if ((answer as { download?: SavedAttachment }).download && answer.res.ok) return { ok: true, data: undefined }; const outcome = interpretActionResponse(answer.res, answer.json, label); return outcome.ok ? { ok: true, data: outcome.envelope } : { ok: false, error: outcome.error ?? `${label} failed` }; } From f4e5bf4bd257ac515e9103b8ede8fa05adf869f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:23:26 +0000 Subject: [PATCH 04/12] docs: the action door relays an attachment; changeset Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- .../38894-action-door-delivers-attachment.md | 21 +++++++++++++++++++ content/docs/ui/actions.mdx | 2 +- content/docs/ui/print-pages.mdx | 6 ++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 .changeset/38894-action-door-delivers-attachment.md diff --git a/.changeset/38894-action-door-delivers-attachment.md b/.changeset/38894-action-door-delivers-attachment.md new file mode 100644 index 00000000000..c05951b830b --- /dev/null +++ b/.changeset/38894-action-door-delivers-attachment.md @@ -0,0 +1,21 @@ +--- +'@objectstack/runtime': patch +'@object-ui/app-shell': patch +--- + +feat(runtime): a declared `type: 'api'` action delivers a file through the REST action door, and the console saves it as a download + +Clause-②: yes (widening) +Metadata-protocol: none + +**The REST action door relays a file.** `POST /api/v1/actions/...` forwards a same-origin `type: 'api'` action to its `target` in-process. A target that answered `2xx` with anything but JSON used to get the door's own `502`. One such answer is now carried: a `2xx` that carries `Content-Disposition: attachment` (a print route's PDF, an export). + +- The door answers it byte for byte: the target's status, its body, and its `Content-Type`, `Content-Disposition`, `Cache-Control` and `X-Content-Type-Options`, each as the target sent it. A credential rotation the target emits is relayed beside it, as on a JSON answer. +- The file is read whole before the door answers, and it is bounded at 32 MiB (`API_FORWARD_ATTACHMENT_MAX_BYTES`). A declared length over the bound is refused unread, and a larger body is refused once it passes the bound. Either way the answer is the door's `502`, never a cut-off file. +- Every other non-JSON `2xx` (an inline file, a page, a body with no disposition) still answers `502`, and so does every non-`2xx` non-JSON answer, as before. +- The door's gates are unchanged and run first. A caller the door refuses (signed out, an action switched off, a capability it lacks) gets the refusal, and the target is never called. +- **Only the REST door relays a file.** MCP `run_action` and the host door `dispatchAction` still answer a file with the `502`: a tool result and a `{ status, body }` answer cannot carry one. + +**The console saves it.** A click on a declared same-origin `type: 'api'` action whose door answer is a file now saves that file as a download. The name comes from the `filename*` parameter (RFC 5987, so a name such as `发票.pdf` survives), else from `filename`, else it is `download`. The click then reports success. A click the console fetches itself (an inline page button, or an api action no object declares) saves a target's own attachment answer the same way. It used to read such an answer as an empty success with no file. The record page's own action handler goes through the same door client, so its door road saves the file too. + +Nothing changes for an app whose api targets answer JSON. For an app with a target that answers a file as an attachment, the action now delivers that file where it used to answer `502`. diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index d77ba799d8d..90859b8fbb0 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -833,7 +833,7 @@ The endpoint dispatches on the **declared `type`**, exactly like the MCP |:---|:---| | `script` | Runs the registered handler / inline body. | | `flow` | Runs `target` on the automation engine, with your identity forwarded (a `runAs: 'user'` flow enforces RLS as you). Dispatches the same flow as `POST /api/v1/automation/:target/trigger`, without having to know the flow name — **and answers the same way**: a run that ran and was rejected is **400** `FLOW_FAILED`, while a dispatch that never happened is separated out (**404** unknown flow, a stored flow with no `start` node included, as it is never armed / **409** `FLOW_DISABLED` / **422** `FLOW_INPUT_SCHEMA_INVALID`). A target declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) is refused **403** `PERMISSION_DENIED` to every caller but the system principal, exactly as at the trigger door, and nothing runs; holding the action's `requiredPermissions` does not open it. A target that declares its own `requiredPermissions` is refused **403** `PERMISSION_DENIED` to a caller who does not hold every capability it names, even when the action declares none. An [AI service account](/docs/ai/agents) is refused a target declared `runAs: 'system'` **403** `PERMISSION_DENIED` unless the action declares `ai.exposed: true`: an action with the opt-in is the one way an account starts a flow that runs as the system, here and over MCP `run_action`. See [Run a flow via API](/docs/automation/flows#run-a-flow-via-api) for the full table — it is one table, read by both doors. | -| `api` | **Same-origin `target`** (a path starting with `/`): the door runs its gates — the sign-in floor, `requiredPermissions`, the packaged-action switch, the param contract, the subject-row load — and then **forwards the request in-process** to `target` with your own credentials, assembling the body exactly as the Console does (`recordIdParam` / `recordIdField` from the subject row, `bodyShape`, `bodyExtra` merged last, `organizationId` for an `/api/v1/auth/` target, `method`). The target endpoint still authorizes you itself; its status and body come back as the answer (its `data` unwrapped), and a credential rotation it emits (`Set-Cookie`, `set-auth-token`) is relayed. A `${ctx.selection.*}` or `{{page.}}` token exists only in the browser and is refused **400** by name. **Off-origin `target`** (another host): **400** — the browser calls it directly, and such an action cannot be switched off in the activation ledger (the write door refuses, **409**, with the reason). | +| `api` | **Same-origin `target`** (a path starting with `/`): the door runs its gates — the sign-in floor, `requiredPermissions`, the packaged-action switch, the param contract, the subject-row load — and then **forwards the request in-process** to `target` with your own credentials, assembling the body exactly as the Console does (`recordIdParam` / `recordIdField` from the subject row, `bodyShape`, `bodyExtra` merged last, `organizationId` for an `/api/v1/auth/` target, `method`). The target endpoint still authorizes you itself; its status and body come back as the answer (its `data` unwrapped), and a credential rotation it emits (`Set-Cookie`, `set-auth-token`) is relayed. A `2xx` answer that is not JSON is refused **502** naming its content type, with one exception: a **file** the target sends with `Content-Disposition: attachment` (a print's PDF, an export) is relayed byte for byte, with its status, `Content-Type`, `Content-Disposition`, `Cache-Control` and `X-Content-Type-Options` as the target sent them, up to 32 MiB (a larger file is the **502**), and the Console saves it as a download under the name the header gives (`filename*`, else `filename`). Only this door relays a file: MCP `run_action` and `dispatchAction` answer it **502**. A `${ctx.selection.*}` or `{{page.}}` token exists only in the browser and is refused **400** by name. **Off-origin `target`** (another host): **400** — the browser calls it directly, and such an action cannot be switched off in the activation ledger (the write door refuses, **409**, with the reason). | | `url` / `modal` / `form` | **400** — client-side navigation; there is nothing for the server to run. | ## Headless actions: declare it, then hide it diff --git a/content/docs/ui/print-pages.mdx b/content/docs/ui/print-pages.mdx index d4f2d9136ff..6af791d51e7 100644 --- a/content/docs/ui/print-pages.mdx +++ b/content/docs/ui/print-pages.mdx @@ -204,6 +204,12 @@ export const GenerateInvoicePdf = defineAction({ }); ``` +When the route answers the PDF itself as an attachment +(`Content-Disposition: attachment`), the action delivers the download: the REST +action door relays that answer 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 [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 From 1c34291dabdd14520b5c273970a9586b5798149c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:23:39 +0000 Subject: [PATCH 05/12] docs(changeset): name the record page's direct fetch as unchanged Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- .changeset/38894-action-door-delivers-attachment.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/38894-action-door-delivers-attachment.md b/.changeset/38894-action-door-delivers-attachment.md index c05951b830b..eccc72c0955 100644 --- a/.changeset/38894-action-door-delivers-attachment.md +++ b/.changeset/38894-action-door-delivers-attachment.md @@ -16,6 +16,6 @@ Metadata-protocol: none - The door's gates are unchanged and run first. A caller the door refuses (signed out, an action switched off, a capability it lacks) gets the refusal, and the target is never called. - **Only the REST door relays a file.** MCP `run_action` and the host door `dispatchAction` still answer a file with the `502`: a tool result and a `{ status, body }` answer cannot carry one. -**The console saves it.** A click on a declared same-origin `type: 'api'` action whose door answer is a file now saves that file as a download. The name comes from the `filename*` parameter (RFC 5987, so a name such as `发票.pdf` survives), else from `filename`, else it is `download`. The click then reports success. A click the console fetches itself (an inline page button, or an api action no object declares) saves a target's own attachment answer the same way. It used to read such an answer as an empty success with no file. The record page's own action handler goes through the same door client, so its door road saves the file too. +**The console saves it.** A click on a declared same-origin `type: 'api'` action whose door answer is a file now saves that file as a download. The name comes from the `filename*` parameter (RFC 5987, so a name such as `发票.pdf` survives), else from `filename`, else it is `download`. The click then reports success. The record page's own action handler sends a declared action through the same door client, so it saves the file too. A click the shared action runtime fetches itself (an inline page button, or an api action no object declares) saves a target's own attachment answer the same way; it used to read such an answer as an empty success with no file. The record page's own direct fetch is not changed here and still reads a file answer that way. Nothing changes for an app whose api targets answer JSON. For an app with a target that answers a file as an attachment, the action now delivers that file where it used to answer `502`. From aac199fe693633751266108703bbf3dfb68e1125 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 13:21:57 +0000 Subject: [PATCH 06/12] test: type the conformance rig's slot lookup; no any in the console door test Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- ...tion-door-attachment-38894.conformance.test.ts | 15 ++++++++------- ...soleActionRuntime.apiActionDoor-27611.test.tsx | 10 ++++++---- ui/packages/app-shell/src/utils/apiActionDoor.ts | 2 +- 3 files changed, 15 insertions(+), 12 deletions(-) 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 33cd960bc0d..a89b608930a 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 @@ -26,7 +26,7 @@ */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { LiteKernel } from '@objectstack/core'; +import { LiteKernel, type Plugin, type PluginContext } from '@objectstack/core'; import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; @@ -139,12 +139,12 @@ async function boot(shape: 'self-hosted' | 'catch-all'): Promise { } as any); kernel.use(new HonoServerPlugin({ port: 0 })); if (shape === 'self-hosted') kernel.use(createDispatcherPlugin({ prefix: API, securityHeaders: false })); - kernel.use({ + const target: Plugin = { name: 'com.test.c38894-target', version: '0.0.0', init: () => undefined, - start: (c: any) => { - const server = c.getService('http.server') as IHttpServer; + start: (c: PluginContext) => { + const server = c.getService('http.server'); server.post(`${API}/c38894/file`, async (_req, res) => { calls++; res.status(200); @@ -152,15 +152,16 @@ async function boot(shape: 'self-hosted' | 'catch-all'): Promise { res.header('Content-Disposition', DISPOSITION); res.header('Cache-Control', 'no-store'); res.header('X-Content-Type-Options', 'nosniff'); - await (res as any).send(PDF); + await res.send(PDF); }); server.post(`${API}/c38894/csv`, async (_req, res) => { calls++; res.status(200); - await (res as any).send('id,name\n1,ada\n'); + await res.send('id,name\n1,ada\n'); }); }, - } as any); + }; + kernel.use(target); await kernel.bootstrap(); const ql = kernel.getService('objectql'); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx index e9e51c27c3e..cdbd2334d50 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx @@ -373,11 +373,13 @@ describe('objectstack#38894 — a file answer is saved as a download, a JSON ans created = []; revoked = []; clicked = []; - (URL as any).createObjectURL = vi.fn((blob: Blob) => { - created.push(blob); - return `blob:test/${created.length}`; + Object.assign(URL, { + createObjectURL: vi.fn((blob: Blob) => { + created.push(blob); + return `blob:test/${created.length}`; + }), + revokeObjectURL: vi.fn((url: string) => { revoked.push(url); }), }); - (URL as any).revokeObjectURL = vi.fn((url: string) => { revoked.push(url); }); vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { clicked.push({ href: this.getAttribute('href') ?? '', download: this.download }); }); diff --git a/ui/packages/app-shell/src/utils/apiActionDoor.ts b/ui/packages/app-shell/src/utils/apiActionDoor.ts index a1e6dd4398e..27553c07160 100644 --- a/ui/packages/app-shell/src/utils/apiActionDoor.ts +++ b/ui/packages/app-shell/src/utils/apiActionDoor.ts @@ -272,7 +272,7 @@ export async function saveAttachmentAnswer(res: AttachmentReadable): Promise { let answered: { res: { ok: boolean; status: number }; json: unknown; download?: SavedAttachment } | undefined; const keepAnswer: ServerActionFetch = async (url, init) => { - const res: AttachmentReadable & { json(): Promise } = await input.fetch(url, init); + const res: AttachmentReadable & { json(): Promise } = await input.fetch(url, init); // A relayed file is saved and reads as a success with no data: its body // is bytes, never handed to the JSON reader. if (isDoorFileAnswer(res)) { From 8a889082eb3f58129fbcdf57ce11da05b5ea68f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 13:41:40 +0000 Subject: [PATCH 07/12] test(runtime): type the attachment harness answer through the optional boot options Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- packages/runtime/src/domains/api-action-forward.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/runtime/src/domains/api-action-forward.test.ts b/packages/runtime/src/domains/api-action-forward.test.ts index 7feea1eee39..07fea9ac74f 100644 --- a/packages/runtime/src/domains/api-action-forward.test.ts +++ b/packages/runtime/src/domains/api-action-forward.test.ts @@ -442,7 +442,7 @@ describe('[#38894] a target\'s 2xx `Content-Disposition: attachment` answer: the ai: { exposed: true, description: 'Print the lead.' }, }; const GATED_PRINT = { ...PRINT_LEAD, name: 'print_lead_gated', requiredPermissions: ['lead_print'] }; - const bootFile = (answer: Parameters[0]['answer'], opts: Parameters[0] = {}) => + const bootFile = (answer: NonNullable[0]>['answer'], opts: Parameters[0] = {}) => boot({ ...opts, answer, extraActions: [PRINT_LEAD, GATED_PRINT] }); const runViaMcp = async (h: ReturnType, name: string, input: any = {}) => { const deps: any = { From 617189a27f278192f5f9fc3cb160203b04ce6654 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:32:59 +0000 Subject: [PATCH 08/12] fix(runtime): the action door relays only a non-JSON attachment with a body; a JSON answer and a 204/205 keep the JSON path Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- ...-door-attachment-38894.conformance.test.ts | 28 +++++++- packages/runtime/src/action-execution.ts | 22 ++++--- .../runtime/src/action-forward-attachment.ts | 49 ++++++++++++-- packages/runtime/src/dispatcher-plugin.ts | 7 +- .../src/domains/api-action-forward.test.ts | 64 ++++++++++++++++++- 5 files changed, 146 insertions(+), 24 deletions(-) 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 a89b608930a..f3a2b607bb5 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 @@ -44,6 +44,7 @@ const DISPOSITION = 'attachment; filename="invoice.pdf"; filename*=UTF-8\'\'%E5% const ACTIONS = [ { 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` }, { name: 'download_gated', label: 'Gated', objectName: OBJECT, type: 'api', method: 'POST', target: `${API}/c38894/file`, requiredPermissions: ['c38894_download'], @@ -138,7 +139,9 @@ async function boot(shape: 'self-hosted' | 'catch-all'): Promise { init: (c: any) => c.registerService('auth', { api: { getSession: async () => ({ user: { id: 'u_member' } }) } }), } as any); kernel.use(new HonoServerPlugin({ port: 0 })); - if (shape === 'self-hosted') kernel.use(createDispatcherPlugin({ prefix: API, securityHeaders: false })); + // The standalone transport with its default security headers on: a relayed + // file carries them as every other answer does. + if (shape === 'self-hosted') kernel.use(createDispatcherPlugin({ prefix: API })); const target: Plugin = { name: 'com.test.c38894-target', version: '0.0.0', @@ -154,6 +157,13 @@ async function boot(shape: 'self-hosted' | 'catch-all'): Promise { res.header('X-Content-Type-Options', 'nosniff'); await res.send(PDF); }); + // The data export's `format=json` shape: JSON under an attachment disposition. + server.post(`${API}/c38894/json`, async (_req, res) => { + calls++; + res.status(200); + res.header('Content-Disposition', 'attachment; filename="rows.json"'); + res.json({ success: true, data: [{ id: 1 }, { id: 2 }] }); + }); server.post(`${API}/c38894/csv`, async (_req, res) => { calls++; res.status(200); @@ -209,6 +219,21 @@ describe.each(['self-hosted', 'catch-all'] as const)('[#38894] the REST action d expect(res.headers.get('content-disposition')).toBe(DISPOSITION); expect(res.headers.get('cache-control')).toBe('no-store'); expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + if (shape === 'self-hosted') { + // The dispatcher's security headers ride the file as every answer. + expect(res.headers.get('content-security-policy')).toContain("default-src 'none'"); + expect(res.headers.get('x-frame-options')).toBe('DENY'); + } + }); + + it('a 2xx JSON answer under an attachment disposition keeps the JSON path: the envelope, never a file', async () => { + const res = await door.send(`${API}/actions/${OBJECT}/export_json`, call()); + expect(res.headers.get('content-disposition')).toBeNull(); + expect(res.headers.get('content-type')).toContain('application/json'); + const body = (await res.json()) as any; + expect(res.status, JSON.stringify(body)).toBe(200); + expect(body.success).toBe(true); + expect(body.data).toEqual([{ id: 1 }, { id: 2 }]); }); it('a 2xx non-JSON answer that is not an attachment still answers the door\'s 502', async () => { @@ -229,6 +254,7 @@ describe.each(['self-hosted', 'catch-all'] as const)('[#38894] the REST action d const body = (await res.json()) as any; expect(res.status, JSON.stringify(body)).toBe(403); expect(body.success).toBe(false); + expect(body.error.code).toBe('PERMISSION_DENIED'); expect(door.targetCalls()).toBe(before); }); }); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 164f0bf6d92..683029549b5 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -101,7 +101,7 @@ import type { HttpProtocolContext } from './http-dispatcher.js'; // The ONE admitted sequence every action door shares; `invokeBusinessAction` // below is its MCP door (posture `ai`). import { addressedUnknownNameRefusal, refusalOfThrown, refuseDispatchToDisabledObject, runResolvedAction, type ActionRefusal } from './action-dispatch.js'; -import { apiActionAttachmentTooLargeError, isAttachmentDisposition, readForwardAttachment, type ApiActionAttachmentAnswer } from './action-forward-attachment.js'; +import { apiActionAttachmentTooLargeError, isRelayableAttachmentAnswer, readForwardAttachment, type ApiActionAttachmentAnswer } from './action-forward-attachment.js'; import { admittingCredentialKind, type AdmittingCredentialKind } from './security/admitting-credential.js'; import { ENVIRONMENT_ACTION_COORDINATE, @@ -2195,8 +2195,8 @@ export function apiActionForwardUnavailableError( * The 502 for a target that answered 2xx with something other than JSON (a * file, HTML, a stream): the door's answer is a JSON envelope and the console's * direct fetch read such a body as `{}` — a silent loss this door refuses by name. - * [#38894] The REST door relays one such answer instead, a file sent as - * `Content-Disposition: attachment` (`./action-forward-attachment.ts`). + * [#38894] The REST door relays one such answer instead, a non-JSON file + * sent as `Content-Disposition: attachment` (`./action-forward-attachment.ts`). */ export function apiActionNonJsonAnswerError(actionName: string, status: number, contentType: string | null): string { return ( @@ -2280,12 +2280,14 @@ export function apiActionForwardLoopError(action: any, mark: string): string { * is a silent loss, not a result). * * [#38894, ruling A] One 2xx non-JSON answer is carried: a file the target - * sent as `Content-Disposition: attachment`, when the door asks for files + * sent as `Content-Disposition: attachment` under a `Content-Type` that is + * not JSON, with a body (not `204` / `205`), when the door asks for files * (`answers.relayAttachment`, the REST door only). It comes back as * `attachment`, byte for byte, under the size bound of * `./action-forward-attachment.ts`, which also says what is kept of its - * headers. Every other 2xx non-JSON answer, and every answer at a door that - * does not ask (MCP, the host door), is the 502 as before. + * headers. A JSON answer keeps the JSON path whatever its disposition. Every + * other 2xx non-JSON answer, and every non-JSON answer at a door that does + * not ask (MCP, the host door), is the 502 as before. */ export async function forwardApiAction( inject: (url: string, init: RequestInit) => Promise, @@ -2352,10 +2354,10 @@ export async function forwardApiAction( ) : await inject(url, init); - // [#38894] A file the target answered as an attachment, at a door that - // carries files: read as bytes, never decoded as text. - if (answers?.relayAttachment === true && res.status >= 200 && res.status < 300 - && isAttachmentDisposition(res.headers.get('content-disposition'))) { + // [#38894] A non-JSON file the target answered as an attachment, at a + // door that carries files: read as bytes, never decoded as text. A JSON + // answer and a null-body status keep the JSON path below, as before. + if (answers?.relayAttachment === true && isRelayableAttachmentAnswer(res)) { const attachment = await readForwardAttachment(res); if (!attachment) { return { diff --git a/packages/runtime/src/action-forward-attachment.ts b/packages/runtime/src/action-forward-attachment.ts index f44a0a35ac2..caa16c7caa4 100644 --- a/packages/runtime/src/action-forward-attachment.ts +++ b/packages/runtime/src/action-forward-attachment.ts @@ -7,9 +7,19 @@ * The action doors answer JSON envelopes, and a target that answered `2xx` * with anything else was refused as the door's own `502` * (`apiActionNonJsonAnswerError`, `action-execution.ts`). The ruling keeps - * that refusal for every answer but one: a `2xx` that carries + * that refusal for every answer but one: a `2xx` NON-JSON answer that carries * `Content-Disposition: attachment` (RFC 6266) is a file the target meant the - * caller to save, and the REST door relays it byte for byte. + * caller to save, and the REST door relays it byte for byte + * ({@link isRelayableAttachmentAnswer}). + * + * ## What stays exactly as before + * + * - **A JSON answer, whatever its disposition.** A target that answers + * `application/json` or a `+json` type under `attachment` (the data export + * with `format=json` is one) keeps the JSON path: parsed, enveloped, its + * `data` unwrapped. Only an answer the door used to refuse `502` changes. + * - **A null-body status** (`204`, `205`): there is no file to relay, and the + * answer takes the JSON path as it always did (an empty body is `null`). * * ## What is relayed * @@ -53,10 +63,13 @@ export const API_FORWARD_ATTACHMENT_HEADERS: readonly string[] = [ 'x-content-type-options', ]; +/** The `2xx` statuses that carry no body (RFC 9110): no file to relay. */ +const NULL_BODY_STATUSES: ReadonlySet = new Set([204, 205]); + /** A target's `2xx` file answer, as the REST door relays it. */ export interface ApiActionAttachmentAnswer { status: number; - bytes: Uint8Array; + bytes: Uint8Array; /** {@link API_FORWARD_ATTACHMENT_HEADERS}, lower-case, each only when the target sent it. */ headers: Record; } @@ -72,6 +85,30 @@ export function isAttachmentDisposition(value: string | null | undefined): boole return value.split(';', 1)[0].trim().toLowerCase() === 'attachment'; } +/** + * `true` when a `Content-Type` value names JSON: `application/json`, or any + * `+json` structured-syntax type (RFC 6839). Parameters are ignored; an + * absent value is not JSON. + */ +export function isJsonMediaType(value: string | null | undefined): boolean { + if (typeof value !== 'string') return false; + const media = value.split(';', 1)[0].trim().toLowerCase(); + return media === 'application/json' || media.endsWith('+json'); +} + +/** + * `true` for the one answer the REST door relays as a file: a `2xx` status + * that carries a body, a `Content-Disposition` of type `attachment`, and a + * `Content-Type` that is not JSON. Every other answer takes the path it took + * before. + */ +export function isRelayableAttachmentAnswer(res: Response): boolean { + return res.status >= 200 && res.status < 300 + && !NULL_BODY_STATUSES.has(res.status) + && isAttachmentDisposition(res.headers.get('content-disposition')) + && !isJsonMediaType(res.headers.get('content-type')); +} + /** * Read a target's file answer under `maxBytes` * ({@link API_FORWARD_ATTACHMENT_MAX_BYTES}). `null` when it is over the @@ -139,8 +176,6 @@ export function apiActionAttachmentResponse( else headers.set(name, value); } for (const [name, value] of Object.entries(file.headers)) headers.set(name, value); - // A copy the Response owns, over a plain `ArrayBuffer`. - const body = new Uint8Array(file.bytes.byteLength); - body.set(file.bytes); - return new Response(body, { status: file.status, headers }); + // The read's own buffer, not a copy: nothing else holds it. + return new Response(file.bytes, { status: file.status, headers }); } diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index afeffd46d4f..831a228f4c3 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -2223,9 +2223,10 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu // [#38894, ruling A] The `/actions` door's answer: a file an api // action's target sent as an attachment comes back from the domain // as a `Response` (`HttpDispatcherResult.result`), written here as - // it is, status, headers and bytes, after the security headers, so - // the target's own `X-Content-Type-Options` / `Cache-Control` stand. - // `sendResult` writes every other answer as JSON, as before. + // it is, status, headers and bytes. The security headers are + // written on it too (a relayed file keeps the CSP and + // `X-Frame-Options` every other answer carries). `sendResult` writes + // every other answer as JSON, as before. const sendActionResult = async (result: HttpDispatcherResult, res: any): Promise => { if (result.handled && result.result instanceof Response) { if (securityHeaders) for (const [k, v] of Object.entries(securityHeaders)) res.header(k, v); diff --git a/packages/runtime/src/domains/api-action-forward.test.ts b/packages/runtime/src/domains/api-action-forward.test.ts index 07fea9ac74f..fe37f941945 100644 --- a/packages/runtime/src/domains/api-action-forward.test.ts +++ b/packages/runtime/src/domains/api-action-forward.test.ts @@ -47,7 +47,9 @@ import { API_FORWARD_MARK_HEADER, apiForwardAgentOf, } from '../action-execution.js'; -import { API_FORWARD_ATTACHMENT_MAX_BYTES, isAttachmentDisposition, readForwardAttachment } from '../action-forward-attachment.js'; +import { + API_FORWARD_ATTACHMENT_MAX_BYTES, isAttachmentDisposition, isJsonMediaType, isRelayableAttachmentAnswer, readForwardAttachment, +} from '../action-forward-attachment.js'; import { FORWARD_CREDENTIAL_HEADER, redeemForwardCredential } from '@objectstack/rest'; import { standardErrorCodeForHttpStatus } from '@objectstack/spec/api'; import { ActionActivationProjection } from '@objectstack/objectql'; @@ -145,11 +147,18 @@ function boot(opts: { // otherwise the JSON `body` under `application/json`. // [#38894] `bytes` is a raw binary body, sent as given. const raw = typeof answer.text === 'string' || answer.bytes !== undefined; - const payload = answer.bytes !== undefined ? new Uint8Array(answer.bytes) + // A null-body status (204 / 205) cannot be built with a body at all. + const payload = answer.status === 204 || answer.status === 205 ? null + : answer.bytes !== undefined ? new Uint8Array(answer.bytes) : raw ? answer.text : JSON.stringify(answer.body ?? { success: true, data: { ok: true } }); return new Response(payload, { status: answer.status ?? 200, - headers: [...(raw ? [] : [['content-type', 'application/json'] as [string, string]]), ...(answer.headers ?? [])], + headers: [ + // A caller-given content type replaces the JSON default (never appended beside it). + ...(raw || (answer.headers ?? []).some(([k]) => k.toLowerCase() === 'content-type') + ? [] : [['content-type', 'application/json'] as [string, string]]), + ...(answer.headers ?? []), + ], }); }); const server = { getRawApp: () => ({ request }) }; @@ -578,9 +587,58 @@ describe('[#38894] a target\'s 2xx `Content-Disposition: attachment` answer: the expect(res?.result).toBeUndefined(); expect(statusOf(res)).toBe(502); + expect(codeOf(res)).toBe(standardErrorCodeForHttpStatus(502)); expect(messageOf(res)).toContain(String(API_FORWARD_ATTACHMENT_MAX_BYTES)); }); + it('REST: a 2xx JSON answer under an attachment disposition keeps the JSON path, exactly as without the disposition', async () => { + // The data export with `format=json` answers this shape: JSON, as `attachment`. + for (const type of ['application/json; charset=utf-8', 'application/vnd.api+json']) { + const rows = { success: true, data: [{ id: 1 }, { id: 2 }] }; + const withDisposition = bootFile({ status: 200, body: rows, headers: [['content-type', type], ['content-disposition', 'attachment; filename="rows.json"']] }); + const without = bootFile({ status: 200, body: rows, headers: [['content-type', type]] }); + + const res: any = await withDisposition.dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + const control: any = await without.dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + + expect(res?.result, type).toBeUndefined(); + expect(statusOf(res)).toBe(200); + expect(res?.response?.body?.data).toEqual([{ id: 1 }, { id: 2 }]); + expect(res?.response, type).toEqual(control?.response); + } + }); + + it('REST: a 204 / 205 under an attachment disposition has no file to relay and answers as without the disposition, never a throw', async () => { + for (const status of [204, 205]) { + const withDisposition = bootFile({ status, headers: [['content-disposition', 'attachment; filename="empty.pdf"']] }); + const without = bootFile({ status }); + + const res: any = await withDisposition.dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + const control: any = await without.dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); + + expect(res?.result, String(status)).toBeUndefined(); + expect(statusOf(res)).toBe(200); + expect(res?.response, String(status)).toEqual(control?.response); + } + }); + + it('isRelayableAttachmentAnswer: a 2xx non-JSON attachment with a body, and nothing else', () => { + const at = (status: number, headers: Record) => + isRelayableAttachmentAnswer(new Response(status === 204 || status === 205 ? null : 'x', { status, headers })); + const ATT = 'attachment; filename="a.pdf"'; + expect(at(200, { 'content-type': 'application/pdf', 'content-disposition': ATT })).toBe(true); + expect(at(201, { 'content-disposition': ATT })).toBe(true); + expect(at(200, { 'content-type': 'application/json', 'content-disposition': ATT })).toBe(false); + expect(at(200, { 'content-type': 'application/problem+json', 'content-disposition': ATT })).toBe(false); + expect(at(204, { 'content-disposition': ATT })).toBe(false); + expect(at(205, { 'content-disposition': ATT })).toBe(false); + expect(at(200, { 'content-type': 'application/pdf', 'content-disposition': 'inline' })).toBe(false); + expect(at(404, { 'content-type': 'application/pdf', 'content-disposition': ATT })).toBe(false); + expect(isJsonMediaType('Application/JSON ; charset=utf-8')).toBe(true); + expect(isJsonMediaType('text/json')).toBe(false); + expect(isJsonMediaType(null)).toBe(false); + }); + it('isAttachmentDisposition reads the disposition type alone, case-insensitively (RFC 6266)', () => { expect(isAttachmentDisposition('attachment')).toBe(true); expect(isAttachmentDisposition('Attachment; filename="a.pdf"')).toBe(true); From 9463775cd24132f33de7bde4a6f1f5bd2c338034 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:33:55 +0000 Subject: [PATCH 09/12] test(runtime): the 204/205 pin answers a file's content type, so only the null-body rule decides it Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- packages/runtime/src/domains/api-action-forward.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/runtime/src/domains/api-action-forward.test.ts b/packages/runtime/src/domains/api-action-forward.test.ts index fe37f941945..3261484191f 100644 --- a/packages/runtime/src/domains/api-action-forward.test.ts +++ b/packages/runtime/src/domains/api-action-forward.test.ts @@ -610,8 +610,9 @@ describe('[#38894] a target\'s 2xx `Content-Disposition: attachment` answer: the it('REST: a 204 / 205 under an attachment disposition has no file to relay and answers as without the disposition, never a throw', async () => { for (const status of [204, 205]) { - const withDisposition = bootFile({ status, headers: [['content-disposition', 'attachment; filename="empty.pdf"']] }); - const without = bootFile({ status }); + // A file's own content type, so only the null-body rule keeps it off the relay. + const withDisposition = bootFile({ status, headers: [['content-type', 'application/pdf'], ['content-disposition', 'attachment; filename="empty.pdf"']] }); + const without = bootFile({ status, headers: [['content-type', 'application/pdf']] }); const res: any = await withDisposition.dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); const control: any = await without.dispatcher.handleActions(`/${OBJECT}/${PRINT_LEAD.name}`, 'POST', { recordId: 'lead 7' }, CTX()); From 13028ce9fab1a91f956751104d9eef2bfdfd2b53 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:35:43 +0000 Subject: [PATCH 10/12] fix(app-shell): a JSON or null-body answer is never saved as a file; the object URL is revoked well after the click Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- ...ActionRuntime.apiActionDoor-27611.test.tsx | 37 +++++++++++++-- .../app-shell/src/utils/apiActionDoor.ts | 45 ++++++++++++++----- 2 files changed, 66 insertions(+), 16 deletions(-) diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx index cdbd2334d50..9a5c400a79b 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx @@ -83,6 +83,7 @@ vi.mock('sonner', () => { }); import { useConsoleActionRuntime } from '../useConsoleActionRuntime'; +import { OBJECT_URL_REVOKE_DELAY_MS } from '../../utils/apiActionDoor'; registerBuiltInLocales(); @@ -387,17 +388,26 @@ describe('objectstack#38894 — a file answer is saved as a download, a JSON ans const fileAnswer = (headers: Record, status = 200) => authFetchSpy.mockResolvedValue(new Response(PDF, { status, headers })); - const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); - it('the door\'s relayed attachment is saved under its RFC 5987 name, the URL revoked, and the click succeeds', async () => { + it('the door\'s relayed attachment is saved under its RFC 5987 name, the URL revoked on a later tick, and the click succeeds', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); fileAnswer({ 'content-type': 'application/pdf', 'content-disposition': 'attachment; filename="invoice.pdf"; filename*=UTF-8\'\'%E5%8F%91%E7%A5%A8%20INV-1.pdf', }); const { result, onRefresh } = mount('showcase_invoice', PRINT_OBJECTS); - const out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); - await settle(); + let out: any; + try { + out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + // Not on the click's own tick, nor just before the delay runs out. + expect(revoked).toEqual([]); + vi.advanceTimersByTime(OBJECT_URL_REVOKE_DELAY_MS - 1); + expect(revoked).toEqual([]); + vi.advanceTimersByTime(1); + } finally { + vi.useRealTimers(); + } expect(sent().url.endsWith(`${DOOR}showcase_invoice/print_invoice`)).toBe(true); expect(clicked).toEqual([{ href: 'blob:test/1', download: '发票 INV-1.pdf' }]); @@ -444,6 +454,25 @@ describe('objectstack#38894 — a file answer is saved as a download, a JSON ans expect(URL.createObjectURL).not.toHaveBeenCalled(); }); + it('a JSON answer under an attachment disposition is read as data on both roads, never saved', async () => { + const jsonAttachment = () => authFetchSpy.mockResolvedValue(new Response(JSON.stringify({ success: true, data: [{ id: 1 }] }), { + status: 200, headers: { 'content-type': 'application/json', 'content-disposition': 'attachment; filename="rows.json"' }, + })); + jsonAttachment(); + const viaDoor = mount('showcase_invoice', PRINT_OBJECTS); + const doorOut = await click(viaDoor.result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + expect(doorOut).toEqual({ success: true, data: [{ id: 1 }], reload: true }); + + authFetchSpy.mockReset(); + jsonAttachment(); + const direct = mount('showcase_invoice', []); + const directOut = await click(direct.result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); + expect(directOut).toEqual({ success: true, data: [{ id: 1 }], reload: true }); + + expect(clicked).toEqual([]); + expect(URL.createObjectURL).not.toHaveBeenCalled(); + }); + it('a door refusal is never saved, whatever its headers say', async () => { authFetchSpy.mockResolvedValue(new Response(JSON.stringify({ success: false, error: { code: 'EXTERNAL_SERVICE_ERROR', message: 'not JSON' } }), { status: 502, headers: { 'content-type': 'application/json', 'content-disposition': 'attachment; filename="x.pdf"' }, diff --git a/ui/packages/app-shell/src/utils/apiActionDoor.ts b/ui/packages/app-shell/src/utils/apiActionDoor.ts index 27553c07160..a4ab47992c7 100644 --- a/ui/packages/app-shell/src/utils/apiActionDoor.ts +++ b/ui/packages/app-shell/src/utils/apiActionDoor.ts @@ -58,10 +58,11 @@ * * ## A file answer is saved, not read (objectstack#38894, ruling A) * - * The door relays a target's `2xx` answer that carries + * The door relays a target's `2xx` non-JSON answer that carries * `Content-Disposition: attachment` byte for byte (a print route's PDF, an - * export), and refuses every other non-JSON `2xx` as its own `502`. So a door - * answer that is an attachment is saved as a download + * export), and refuses every other non-JSON `2xx` as its own `502`; a JSON + * answer stays JSON whatever its disposition. So a door answer that is a + * non-JSON attachment is saved as a download * ({@link saveAttachmentAnswer}) and reads as a success with no data; the * direct fetch saves a target's own attachment answer the same way. */ @@ -177,14 +178,27 @@ interface AttachmentReadable { blob?: () => Promise; } +/** `true` when a `Content-Type` value names JSON: `application/json` or a `+json` type (RFC 6839). */ +function isJsonMediaType(type: string | null): boolean { + if (typeof type !== 'string') return false; + const media = type.split(';', 1)[0].trim().toLowerCase(); + return media === 'application/json' || media.endsWith('+json'); +} + /** - * `true` for a `2xx` answer whose `Content-Disposition` type is `attachment` - * (RFC 6266: the token before the first `;`, case-insensitive). + * `true` for a file to save: a `2xx` answer with a body (not `204` / `205`) + * whose `Content-Disposition` type is `attachment` (RFC 6266: the token + * before the first `;`, case-insensitive) and whose `Content-Type` is not + * JSON. A JSON answer is read as data whatever its disposition (the data + * export's `format=json` answers JSON as `attachment`), exactly as the + * action door reads it. */ export function isAttachmentAnswer(res: AttachmentReadable): boolean { - if (!res.ok || typeof res.headers?.get !== 'function' || typeof res.blob !== 'function') return false; + if (!res.ok || res.status === 204 || res.status === 205) return false; + if (typeof res.headers?.get !== 'function' || typeof res.blob !== 'function') return false; const disposition = res.headers.get('content-disposition'); - return typeof disposition === 'string' && disposition.split(';', 1)[0].trim().toLowerCase() === 'attachment'; + if (typeof disposition !== 'string' || disposition.split(';', 1)[0].trim().toLowerCase() !== 'attachment') return false; + return !isJsonMediaType(res.headers.get('content-type')); } /** @@ -195,15 +209,22 @@ export function isAttachmentAnswer(res: AttachmentReadable): boolean { */ function isDoorFileAnswer(res: AttachmentReadable): boolean { if (isAttachmentAnswer(res)) return true; - if (!res.ok || typeof res.headers?.get !== 'function' || typeof res.blob !== 'function') return false; + if (!res.ok || res.status === 204 || res.status === 205) return false; + if (typeof res.headers?.get !== 'function' || typeof res.blob !== 'function') return false; const type = res.headers.get('content-type'); if (typeof type !== 'string' || type.trim() === '') return false; - const media = type.split(';', 1)[0].trim().toLowerCase(); - return media !== 'application/json' && !media.endsWith('+json'); + return !isJsonMediaType(type); } const FALLBACK_FILENAME = 'download'; +/** + * How long a saved file's object URL lives after the click. Some engines + * (older Safari and Firefox) lose a blob download whose URL is revoked on the + * same tick, so it is revoked well after the browser has taken the file. + */ +export const OBJECT_URL_REVOKE_DELAY_MS = 10_000; + /** A filename safe to hand the browser: no path separator, no control character. */ function safeFilename(name: string): string { const cleaned = Array.from(name.replace(/[\\/]/g, '_')) @@ -262,8 +283,8 @@ export async function saveAttachmentAnswer(res: AttachmentReadable): Promise URL.revokeObjectURL(url), 0); + // Well after the click has handed the URL to the download, never before it. + setTimeout(() => URL.revokeObjectURL(url), OBJECT_URL_REVOKE_DELAY_MS); } return { filename, size: blob.size }; } From 0411c6d4cbc6d3abf0780ff8f8810a4821af181a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:36:20 +0000 Subject: [PATCH 11/12] docs: the action door relays a non-JSON attachment; a JSON answer and a non-2xx keep their paths Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- .changeset/38894-action-door-delivers-attachment.md | 9 +++++---- content/docs/ui/actions.mdx | 2 +- content/docs/ui/print-pages.mdx | 11 ++++++----- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/.changeset/38894-action-door-delivers-attachment.md b/.changeset/38894-action-door-delivers-attachment.md index eccc72c0955..163fb9ca835 100644 --- a/.changeset/38894-action-door-delivers-attachment.md +++ b/.changeset/38894-action-door-delivers-attachment.md @@ -8,14 +8,15 @@ feat(runtime): a declared `type: 'api'` action delivers a file through the REST Clause-②: yes (widening) Metadata-protocol: none -**The REST action door relays a file.** `POST /api/v1/actions/...` forwards a same-origin `type: 'api'` action to its `target` in-process. A target that answered `2xx` with anything but JSON used to get the door's own `502`. One such answer is now carried: a `2xx` that carries `Content-Disposition: attachment` (a print route's PDF, an export). +**The REST action door relays a file.** `POST /api/v1/actions/...` forwards a same-origin `type: 'api'` action to its `target` in-process. A target that answered `2xx` with anything but JSON used to get the door's own `502`. One such answer is now carried: a non-JSON `2xx` with a body that carries `Content-Disposition: attachment` (a print route's PDF, a CSV export). - The door answers it byte for byte: the target's status, its body, and its `Content-Type`, `Content-Disposition`, `Cache-Control` and `X-Content-Type-Options`, each as the target sent it. A credential rotation the target emits is relayed beside it, as on a JSON answer. - The file is read whole before the door answers, and it is bounded at 32 MiB (`API_FORWARD_ATTACHMENT_MAX_BYTES`). A declared length over the bound is refused unread, and a larger body is refused once it passes the bound. Either way the answer is the door's `502`, never a cut-off file. -- Every other non-JSON `2xx` (an inline file, a page, a body with no disposition) still answers `502`, and so does every non-`2xx` non-JSON answer, as before. +- A JSON answer keeps the JSON path whatever its disposition: an `application/json` or `+json` answer sent as `attachment` (the data export with `format=json` is one) is parsed and answered as the same envelope as before. A `204` or `205` has no file to relay and answers as before too. +- Every other non-JSON `2xx` (an inline file, a page, a body with no disposition) still answers `502`. Every non-`2xx` answer is still the target's refusal under its own status, as before. - The door's gates are unchanged and run first. A caller the door refuses (signed out, an action switched off, a capability it lacks) gets the refusal, and the target is never called. - **Only the REST door relays a file.** MCP `run_action` and the host door `dispatchAction` still answer a file with the `502`: a tool result and a `{ status, body }` answer cannot carry one. -**The console saves it.** A click on a declared same-origin `type: 'api'` action whose door answer is a file now saves that file as a download. The name comes from the `filename*` parameter (RFC 5987, so a name such as `发票.pdf` survives), else from `filename`, else it is `download`. The click then reports success. The record page's own action handler sends a declared action through the same door client, so it saves the file too. A click the shared action runtime fetches itself (an inline page button, or an api action no object declares) saves a target's own attachment answer the same way; it used to read such an answer as an empty success with no file. The record page's own direct fetch is not changed here and still reads a file answer that way. +**The console saves it.** A click on a declared same-origin `type: 'api'` action whose door answer is a file now saves that file as a download; a JSON answer is read as data, as before, whatever its disposition. The name comes from the `filename*` parameter (RFC 5987, so a name such as `发票.pdf` survives), else from `filename`, else it is `download`. The click then reports success. The record page's own action handler sends a declared action through the same door client, so it saves the file too. A click the shared action runtime fetches itself (an inline page button, or an api action no object declares) saves a target's own attachment answer the same way; it used to read such an answer as an empty success with no file. The record page's own direct fetch is not changed here and still reads a file answer that way. -Nothing changes for an app whose api targets answer JSON. For an app with a target that answers a file as an attachment, the action now delivers that file where it used to answer `502`. +Nothing changes for an app whose api targets answer JSON, with or without an attachment disposition. For an app with a target that answers a non-JSON file as an attachment, the action now delivers that file where it used to answer `502`. diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 90859b8fbb0..e61397d846a 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -833,7 +833,7 @@ The endpoint dispatches on the **declared `type`**, exactly like the MCP |:---|:---| | `script` | Runs the registered handler / inline body. | | `flow` | Runs `target` on the automation engine, with your identity forwarded (a `runAs: 'user'` flow enforces RLS as you). Dispatches the same flow as `POST /api/v1/automation/:target/trigger`, without having to know the flow name — **and answers the same way**: a run that ran and was rejected is **400** `FLOW_FAILED`, while a dispatch that never happened is separated out (**404** unknown flow, a stored flow with no `start` node included, as it is never armed / **409** `FLOW_DISABLED` / **422** `FLOW_INPUT_SCHEMA_INVALID`). A target declared `runAs: 'system'` whose type is self-triggered (`autolaunched`, `record_change`, `schedule`) is refused **403** `PERMISSION_DENIED` to every caller but the system principal, exactly as at the trigger door, and nothing runs; holding the action's `requiredPermissions` does not open it. A target that declares its own `requiredPermissions` is refused **403** `PERMISSION_DENIED` to a caller who does not hold every capability it names, even when the action declares none. An [AI service account](/docs/ai/agents) is refused a target declared `runAs: 'system'` **403** `PERMISSION_DENIED` unless the action declares `ai.exposed: true`: an action with the opt-in is the one way an account starts a flow that runs as the system, here and over MCP `run_action`. See [Run a flow via API](/docs/automation/flows#run-a-flow-via-api) for the full table — it is one table, read by both doors. | -| `api` | **Same-origin `target`** (a path starting with `/`): the door runs its gates — the sign-in floor, `requiredPermissions`, the packaged-action switch, the param contract, the subject-row load — and then **forwards the request in-process** to `target` with your own credentials, assembling the body exactly as the Console does (`recordIdParam` / `recordIdField` from the subject row, `bodyShape`, `bodyExtra` merged last, `organizationId` for an `/api/v1/auth/` target, `method`). The target endpoint still authorizes you itself; its status and body come back as the answer (its `data` unwrapped), and a credential rotation it emits (`Set-Cookie`, `set-auth-token`) is relayed. A `2xx` answer that is not JSON is refused **502** naming its content type, with one exception: a **file** the target sends with `Content-Disposition: attachment` (a print's PDF, an export) is relayed byte for byte, with its status, `Content-Type`, `Content-Disposition`, `Cache-Control` and `X-Content-Type-Options` as the target sent them, up to 32 MiB (a larger file is the **502**), and the Console saves it as a download under the name the header gives (`filename*`, else `filename`). Only this door relays a file: MCP `run_action` and `dispatchAction` answer it **502**. A `${ctx.selection.*}` or `{{page.}}` token exists only in the browser and is refused **400** by name. **Off-origin `target`** (another host): **400** — the browser calls it directly, and such an action cannot be switched off in the activation ledger (the write door refuses, **409**, with the reason). | +| `api` | **Same-origin `target`** (a path starting with `/`): the door runs its gates — the sign-in floor, `requiredPermissions`, the packaged-action switch, the param contract, the subject-row load — and then **forwards the request in-process** to `target` with your own credentials, assembling the body exactly as the Console does (`recordIdParam` / `recordIdField` from the subject row, `bodyShape`, `bodyExtra` merged last, `organizationId` for an `/api/v1/auth/` target, `method`). The target endpoint still authorizes you itself; its status and body come back as the answer (its `data` unwrapped), and a credential rotation it emits (`Set-Cookie`, `set-auth-token`) is relayed. A `2xx` answer that is not JSON is refused **502** naming its content type, with one exception: a non-JSON **file** the target sends with `Content-Disposition: attachment` (a print's PDF, a CSV export) is relayed byte for byte, with its status, `Content-Type`, `Content-Disposition`, `Cache-Control` and `X-Content-Type-Options` as the target sent them, up to 32 MiB (a larger file is the **502**), and the Console saves it as a download under the name the header gives (`filename*`, else `filename`). A JSON answer is read as JSON whatever its disposition, and a `204` / `205` has no file to relay. Only this door relays a file: MCP `run_action` and `dispatchAction` answer it **502**. A `${ctx.selection.*}` or `{{page.}}` token exists only in the browser and is refused **400** by name. **Off-origin `target`** (another host): **400** — the browser calls it directly, and such an action cannot be switched off in the activation ledger (the write door refuses, **409**, with the reason). | | `url` / `modal` / `form` | **400** — client-side navigation; there is nothing for the server to run. | ## Headless actions: declare it, then hide it diff --git a/content/docs/ui/print-pages.mdx b/content/docs/ui/print-pages.mdx index 6af791d51e7..b1ac607b5a6 100644 --- a/content/docs/ui/print-pages.mdx +++ b/content/docs/ui/print-pages.mdx @@ -204,11 +204,12 @@ export const GenerateInvoicePdf = defineAction({ }); ``` -When the route answers the PDF itself as an attachment -(`Content-Disposition: attachment`), the action delivers the download: the REST -action door relays that answer 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 [Call it over REST](/docs/ui/actions#call-it-over-rest). +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 +[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 From 291a2c6f9eb7a07f3ab03cd2896e9cf78813ecd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:57:46 +0000 Subject: [PATCH 12/12] test(app-shell): no any in the revoke-delay pin Claude-Session: https://claude.ai/code/session_01QSeKYpEYuQLqepCv5Ubf9g Co-authored-by: Claude --- .../useConsoleActionRuntime.apiActionDoor-27611.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx index 9a5c400a79b..1005265ae6d 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.apiActionDoor-27611.test.tsx @@ -397,7 +397,7 @@ describe('objectstack#38894 — a file answer is saved as a download, a JSON ans }); const { result, onRefresh } = mount('showcase_invoice', PRINT_OBJECTS); - let out: any; + let out: unknown; try { out = await click(result, { ...PRINT, params: { _rowRecord: { id: 'inv_1' } } }); // Not on the click's own tick, nor just before the delay runs out.