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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .changeset/38894-action-door-delivers-attachment.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@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 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.
- 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; 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, 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`.
2 changes: 1 addition & 1 deletion content/docs/ui/actions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.<var>}}` 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.<var>}}` 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
Expand Down
7 changes: 7 additions & 0 deletions content/docs/ui/print-pages.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,13 @@ export const GenerateInvoicePdf = defineAction({
});
```

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
the policy's own code); a request from an **impersonation session** — an
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
// 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, 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';
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: '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'],
},
];

/**
* 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<Response>;
targetCalls: () => number;
}

async function boot(shape: 'self-hosted' | 'catch-all'): Promise<Door> {
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 }));
// 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',
init: () => undefined,
start: (c: PluginContext) => {
const server = c.getService<IHttpServer>('http.server');
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.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);
await res.send('id,name\n1,ada\n');
});
},
};
kernel.use(target);
await kernel.bootstrap();

const ql = kernel.getService<ObjectQL>('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<IHttpServer>('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<void>((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');
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 () => {
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(body.error.code).toBe('PERMISSION_DENIED');
expect(door.targetCalls()).toBe(before);
});
});
Loading
Loading