Skip to content

Commit bd46e3d

Browse files
fix(runtime,hono): a returned error answer carrying a userMessage says it varies by Accept-Language (#38274)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao2nxJ1WFfhVcttSAtWX2GTp)_ Fixes #38123 repo:objectstack#3 · os-tesla · session_01L9qibxRYWXrA8r7F5oJ2mH Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户看不到变化:调度器各模块自己接住错误后返回的提示本来就按请求语言给出,现在响应头也写明它随请求语言变化,和上一张卡修好的那几条出口一致。 - 属于界面多语言这条线,替用多种语言访问同一部署的用户解决:缓存可能把一种语言的错误提示交给说另一种语言的人。 - 只多一个响应头,状态码、错误码和正文都不变;不带提示文字的错误应答不加;有问题可以直接撤回。 - 无 ## What changes - `packages/runtime/src/dispatcher-plugin.ts`, `sendResultBase`'s `response` arm: when `answerVariesByLanguage(result.response.body)` (`@objectstack/types`, landed with #38114) is true, it writes `res.header('Vary', ['Accept-Language'])`. That is the contract's multi-value form, which the hosts append. It is written after the route's own headers, so nothing after it can replace it. - `packages/adapters/hono/src/index.ts`, `createHonoApp`'s `toResponse`, `response` arm: the same question of the body, answered with `c.header('Vary', 'Accept-Language', { append: true })`, after the dispatcher's own headers. - `packages/types/src/localized-answer-vary.ts`: docblock only. Its "Who asks" list now names the two returning exits beside the three throwing ones. No new export. - Changeset: `@objectstack/runtime`, `@objectstack/hono`, `@objectstack/types` patch. ## Why A shared cache in front of the server must never hand a user an error message in someone else's language, so every localized error answer says it varies by `Accept-Language`. The rule sits on the exits rather than in `errorFromThrown`: #38114 put the rule on the three exits that answer a THROW. An answer a dispatcher domain catches and composes itself is RETURNED as `{ handled: true, response }` and leaves only through these two exits, which until now wrote nothing but `response.headers`. Per the claim (route A, bounded in-place widening of the same defect class), the one exit rule covers every producer of a returned `userMessage`, each named here: - `HttpDispatcher.errorFromThrown`, the card's own case (for example `POST /automation/_record-starts`, whose catch hands over the `/data` read's localized `recordNotFoundError`); - `deps.error` carrying a `userMessage` (ruling B′ on #24914): the automation resume door's and trigger door's `400 FLOW_FAILED`; - the `/actions` door's `apiErrorResponse` (`action-dispatch.ts`, `actionsDoorAnswerOf`); - the dispatch foot's marked `PERMISSION_DENIED` 403 (`http-dispatcher.ts`, `declaredUserMessage`). ## Tests Each pin goes into the existing harness file for its exit, as a top-level `describe`: - `packages/runtime/src/dispatcher-plugin.declared-user-message.test.ts`, `[#38123] the dispatcher RETURNED exit`. Every case drives a REAL route mounted by `createDispatcherPlugin` and reads the fake response's header writes: - `errorFromThrown`: `POST /api/v1/automation/_record-starts`, with the `/data` read throwing the real `recordNotFoundError(object, id, context)`. For `en`, `zh-CN` and `ja-JP` callers: 404 `RECORD_NOT_FOUND`, the `userMessage` in that language, exactly one `Vary` write of `['Accept-Language']`, and it is the last header written. Control: the same route's unmarked `400 VALIDATION_FAILED` writes no `Vary`. - the resume door (`deps.error` with a `userMessage`), the trigger door and the `/actions` door: `400 FLOW_FAILED` from a scripted engine whose result carries an app hook's mark. Marked: the mark on the wire and one `Vary` write, last. Control: the unmarked result writes no `Vary`. - the dispatch foot: a marked `PERMISSION_DENIED` 403 gets the `Vary` write; the unmarked one does not. - `packages/adapters/hono/src/hono-response-header-array.test.ts` (the `toResponse` header harness), `[#38123] the returned answer`. One row per producer above, with the nested ADR-0112 body that producer composes, written out because this package's `@objectstack/runtime` is a stub: marked ⇒ `Vary: Accept-Language`, unmarked ⇒ no `Vary`. Appended, not set: a route's own `Vary: Accept-Encoding` keeps its token beside `Accept-Language`, and with CORS on, `Origin` keeps its place. <details><summary>Readings (base origin/main bd5407e, head e6eed88)</summary> - Before the change, through the real mounted `POST /api/v1/automation/_record-starts` (probe in the card's pre-claim report): `404 RECORD_NOT_FOUND`, `userMessage` in en / zh-CN / ja-JP, and the only header written was `X-Request-Id`. No `Vary`. - Ablation through `scripts/ablation-replace.mjs` on the committed fix, deleting one exit's line, then restoring it; each restore was checked as `blob == HEAD` with an empty `git diff HEAD`. Both suites import their exit from source. - runtime: `Tests 7 failed | 28 passed (35)`. The seven marked rows of the new describe failed (three languages, three flow doors, the foot 403), and every control passed. - hono: `Tests 6 failed | 7 passed (13)`. The four marked producer rows and the two "appended" rows failed, and every control passed. - Package suites, each `pnpm --filter PKG test` under the verify lock, exit 0: - types: 42 files, 963 tests. - hono: 14 files, 272 tests. - runtime: 655 files, 12455 passed and 25 skipped. - `typecheck` exit 0 on types, hono and runtime. - `eslint --no-inline-config` exit 0 on the five touched `.ts` files. - Derived local gate set at `e6eed882`: `dispatch-gates --ran` reconciles 71 derived, 70 run with `exit 0`, 1 NOT MEASURED, 0 unrun. The NOT MEASURED one is `check:dual-build-cjs-loads`, which exited 3 (PREREQUISITE NOT MET): it reads every package's `dist/`, and this tree built only the runtime and hono closures. CI's `Lint & Repo Gates` runs it. `check-plugin-teardown-shape --self-test` needed its fixture commit fetched into the shallow clone, then exited 0. - `overlap-check` before the first push was not run; it was run right after it on e6eed88: clean against origin/main and against #38185, the one open PR sharing `dispatcher-plugin.ts`. </details> ## Acceptance notes - Correction to the pre-claim report: `mcp.ts` is not one of these producers. Its `deps.error` with a `userMessage` (`resumeDoorError`) answers `dispatchActionResume`, the kernel's in-process host API (`action-dispatch.ts`), not an HTTP route, so no response header applies. - No dedupe of the token. No producer today returns both a `userMessage` body and its own `Vary: Accept-Language` header: `localizedNotImplemented` localizes `message`, not `userMessage`, and the `/meta` reads that set the header answer success bodies. `Vary` is a list, so a repeated token is harmless. - The hono pins live in `hono-response-header-array.test.ts`, the `toResponse` header harness, rather than `hono-thrown-message-disclosure.test.ts`, which the claim named: that file pins `thrownJson`, the throw arm, and this change is the returned arm. ## Verification Read first, by risk: 1. `packages/runtime/src/dispatcher-plugin.ts`: the end of `sendResultBase`'s `response` arm (the exit `os dev` serves for every dispatcher-mounted route). 2. `packages/adapters/hono/src/index.ts`: `toResponse`'s `response` arm. Two-minute check: `pnpm --filter @objectstack/runtime exec vitest run src/dispatcher-plugin.declared-user-message.test.ts` shows 35 passing. Delete the `res.header('Vary', …)` line in `sendResultBase` and the same command shows 7 failing. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic (not touched). - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; lint passes on the touched files. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibxRYWXrA8r7F5oJ2mH --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibxRYWXrA8r7F5oJ2mH)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b503291 commit bd46e3d

6 files changed

Lines changed: 298 additions & 1 deletion

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/hono': patch
4+
'@objectstack/types': patch
5+
---
6+
7+
fix(runtime,hono): an error answer a dispatcher domain returns with a `userMessage` says it varies by `Accept-Language`
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
An error answer whose body carries a `userMessage` is in the caller's language, so it now carries `Vary: Accept-Language`, as the thrown refusals already do. This covers the answers a dispatcher domain catches and composes itself: `HttpDispatcher.errorFromThrown`, a `deps.error` call carrying a `userMessage` (the automation resume and trigger doors' `FLOW_FAILED`), the `/actions` door, and the dispatch foot's marked `PERMISSION_DENIED`. Both exits that send such an answer ask the body: `@objectstack/runtime`'s dispatcher plugin and `@objectstack/hono`'s `createHonoApp`. The token is appended, so a `Vary` that CORS, compression or the route writes keeps its own tokens. Status codes, error codes and bodies are unchanged, and an answer with no `userMessage` gets no new header.

‎packages/adapters/hono/src/hono-response-header-array.test.ts‎

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616
* real door produces.
1717
*/
1818

19-
import { describe, it, expect, vi, beforeEach } from 'vitest';
19+
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
2020
import type { Hono } from 'hono';
21+
import { LOCALIZED_ANSWER_VARY } from '@objectstack/types';
2122

2223
const mockDispatcher = {
2324
getDiscoveryInfo: vi.fn().mockReturnValue({ version: '1.0', routes: {} }),
@@ -102,3 +103,85 @@ describe('#27506: a string[] header value is one header line per element', () =>
102103
expect(res.headers.get('x-one')).toBe('line');
103104
});
104105
});
106+
107+
/**
108+
* [#38123] `toResponse`'s `response` arm asks #37828's rule of the body it
109+
* sends: an answer a dispatcher domain caught and composed itself never reaches
110+
* `thrownJson`, and a `userMessage` in its body is in the caller's language.
111+
*
112+
* Each row is the nested ADR-0112 body one of the dispatcher's returning
113+
* producers composes, written out because this package's `@objectstack/runtime`
114+
* is a stub (the real producers are driven through their mounted routes in
115+
* `@objectstack/runtime`'s `dispatcher-plugin.declared-user-message.test.ts`):
116+
* `errorFromThrown` over the real `recordNotFoundError` for a zh-CN caller, the
117+
* resume door's `deps.error` and the `/actions` door's `FLOW_FAILED` with an
118+
* app hook's mark, and the dispatch foot's marked `PERMISSION_DENIED`.
119+
*/
120+
describe('[#38123] the returned answer: a userMessage varies by Accept-Language', () => {
121+
const ORIG_CORS_ORIGIN = process.env.OS_CORS_ORIGIN;
122+
afterAll(() => {
123+
if (ORIG_CORS_ORIGIN === undefined) delete process.env.OS_CORS_ORIGIN;
124+
else process.env.OS_CORS_ORIGIN = ORIG_CORS_ORIGIN;
125+
});
126+
beforeEach(() => {
127+
vi.clearAllMocks();
128+
mockDispatcher.handleAuth.mockResolvedValue({ handled: false });
129+
});
130+
131+
const MARK = '该客户名称已被另一位销售代表占用,请联系主管。';
132+
const refusal = (status: number, code: string, message: string, userMessage?: string) => ({
133+
handled: true,
134+
response: {
135+
status,
136+
body: { success: false, error: { code, message, httpStatus: status, ...(userMessage !== undefined ? { userMessage } : {}) } },
137+
},
138+
});
139+
const PRODUCERS: Array<[string, number, string, string, string]> = [
140+
['errorFromThrown', 404, 'RECORD_NOT_FOUND', 'Record l_nowhere not found in crm_lead', '该记录不存在,或您无权访问它。'],
141+
['deps.error, the resume door', 400, 'FLOW_FAILED', "Node 'create_account' failed", MARK],
142+
['the /actions door', 400, 'FLOW_FAILED', "Flow 'crm_convert_lead_wizard' failed", MARK],
143+
['the dispatch foot', 403, 'PERMISSION_DENIED', 'principal lacks cube_read on pipeline', 'Ask an admin for the Reporting role.'],
144+
];
145+
const varyTokens = (res: Response): string[] =>
146+
(res.headers.get('vary') ?? '').split(',').map((token) => token.trim()).filter(Boolean);
147+
const noCors = (): Hono => createHonoApp({ kernel, prefix: PREFIX, cors: false });
148+
149+
for (const [producer, status, code, message, mark] of PRODUCERS) {
150+
it(`${producer}: ${status} ${code} with its userMessage on the wire, and Vary: Accept-Language`, async () => {
151+
mockDispatcher.dispatch.mockResolvedValueOnce(refusal(status, code, message, mark));
152+
const res = await noCors().request(`http://localhost${PATH}`, { method: 'POST', headers: { 'Accept-Language': 'zh-CN' } });
153+
const body = await res.json() as any;
154+
expect(res.status, JSON.stringify(body)).toBe(status);
155+
expect(body.error.code).toBe(code);
156+
expect(body.error.userMessage).toBe(mark);
157+
expect(varyTokens(res)).toEqual([LOCALIZED_ANSWER_VARY]);
158+
});
159+
160+
it(`CONTROL ${producer}: the unmarked ${status} gets no Vary`, async () => {
161+
mockDispatcher.dispatch.mockResolvedValueOnce(refusal(status, code, message));
162+
const res = await noCors().request(`http://localhost${PATH}`, { method: 'POST' });
163+
expect(res.status).toBe(status);
164+
expect(res.headers.get('vary')).toBeNull();
165+
});
166+
}
167+
168+
it('appended, not set: a Vary the route wrote keeps its token beside Accept-Language', async () => {
169+
const answer = refusal(404, 'RECORD_NOT_FOUND', 'Record l_nowhere not found in crm_lead', '该记录不存在,或您无权访问它。');
170+
mockDispatcher.dispatch.mockResolvedValueOnce({ ...answer, response: { ...answer.response, headers: { Vary: 'Accept-Encoding' } } });
171+
const res = await noCors().request(`http://localhost${PATH}`, { method: 'POST' });
172+
expect(res.status).toBe(404);
173+
expect(varyTokens(res)).toEqual(['Accept-Encoding', LOCALIZED_ANSWER_VARY]);
174+
});
175+
176+
it('appended, not set: with CORS on, Origin keeps its place beside Accept-Language', async () => {
177+
process.env.OS_CORS_ORIGIN = 'https://app.example.com';
178+
mockDispatcher.dispatch.mockResolvedValueOnce(refusal(404, 'RECORD_NOT_FOUND', 'Record l_nowhere not found in crm_lead', '该记录不存在,或您无权访问它。'));
179+
const res = await createHonoApp({ kernel, prefix: PREFIX }).request(`http://localhost${PATH}`, {
180+
method: 'POST',
181+
headers: { Origin: 'https://app.example.com' },
182+
});
183+
expect(res.status).toBe(404);
184+
expect(varyTokens(res)).toContain(LOCALIZED_ANSWER_VARY);
185+
expect(varyTokens(res)).toContain('Origin');
186+
});
187+
});

‎packages/adapters/hono/src/index.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,15 @@ export function createHonoApp(options: ObjectStackHonoOptions): Hono {
854854
if (result.response.headers) {
855855
Object.entries(result.response.headers).forEach(([k, v]) => setResponseHeader(c, k, v));
856856
}
857+
// [#38123] The RETURNED answer's half of #37828's rule: an answer a
858+
// dispatcher domain caught and composed itself (`errorFromThrown`, a
859+
// `deps.error` carrying a `userMessage`, the `/actions` door) never
860+
// reaches `thrownJson`. A `userMessage` in its body is in the caller's
861+
// language, so the answer varies by `Accept-Language`
862+
// (`answerVariesByLanguage`, `@objectstack/types`). Appended after the
863+
// dispatcher's own headers, so CORS's `Vary: Origin` and a route's own
864+
// `Vary` keep their tokens.
865+
if (answerVariesByLanguage(result.response.body)) c.header('Vary', LOCALIZED_ANSWER_VARY, { append: true });
857866
return c.json(result.response.body, result.response.status);
858867
}
859868
if (result.result) {

‎packages/runtime/src/dispatcher-plugin.declared-user-message.test.ts‎

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,3 +508,173 @@ describe('[#37828] the dispatcher throw-transparent exit: a userMessage varies b
508508
expect(varyWrites(res)).toEqual([]);
509509
});
510510
});
511+
512+
/**
513+
* [#38123] The RETURNED exit (`sendResultBase`) asks #37828's rule of the body
514+
* it sends. A domain that catches its own fault composes the answer and RETURNS
515+
* it, so it never reaches the throw-transparent exit above: every producer of a
516+
* returned `userMessage` leaves through the plugin's `sendResult`, and each is
517+
* driven here through its REAL mounted route:
518+
*
519+
* - `errorFromThrown`: `POST /automation/_record-starts`, whose catch hands the
520+
* `/data` read's throw over; the throw is the real `recordNotFoundError` with
521+
* the caller's own context, so its sentence follows `Accept-Language`;
522+
* - `deps.error` carrying a `userMessage`: the resume door's `FLOW_FAILED`
523+
* (`POST /automation/:name/runs/:runId/resume`, ruling B′ on #24914);
524+
* - the trigger door's `FLOW_FAILED` (`POST /automation/:name/trigger`);
525+
* - the `/actions` door (`POST /actions/:object/:action`, a flow action);
526+
* - the dispatch foot's `PERMISSION_DENIED` 403, answered with its mark.
527+
*
528+
* Each case reads the one `Vary` write, in the contract's multi-value form (the
529+
* form the hosts APPEND), written after every other header the answer carries;
530+
* each producer's unmarked answer writes none.
531+
*/
532+
describe('[#38123] the dispatcher RETURNED exit: a userMessage varies by Accept-Language', () => {
533+
let errSpy: ReturnType<typeof vi.spyOn>;
534+
beforeEach(() => { errSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); });
535+
afterEach(() => { errSpy.mockRestore(); });
536+
537+
const varyWrites = (res: any) => res.headers.filter(([name]: [string]) => name.toLowerCase() === 'vary');
538+
/** The Vary write is the LAST header written: nothing after it can replace it. */
539+
const lastHeaderName = (res: any) => res.headers[res.headers.length - 1]?.[0];
540+
541+
const FLOW = 'crm_convert_lead_wizard';
542+
const MARK = '该客户名称已被另一位销售代表占用,请联系主管。';
543+
const failed = (mark?: string) => ({
544+
success: false, status: 'failed', error: `Node 'create_account' failed`, durationMs: 9,
545+
...(mark !== undefined ? { userMessage: mark } : {}),
546+
});
547+
548+
/**
549+
* One kernel serving the routes above, from one scripted engine and one
550+
* `/data` read that refuses every id with the protocol's own error.
551+
*/
552+
async function mount(result: Record<string, unknown>) {
553+
const { server, handlers } = makeFakeServer();
554+
const automation = {
555+
handlerReady: true,
556+
execute: vi.fn(async () => result),
557+
resume: vi.fn(async () => ({ ...result, status: 'stranded' })),
558+
getFlow: vi.fn(async (name: string) => (name === FLOW ? { name } : null)),
559+
listRecordUpdateStarts: vi.fn(() => []),
560+
};
561+
const flowAction = { name: 'convert_lead', label: 'Convert Lead', objectName: 'crm_lead', type: 'flow', target: FLOW };
562+
const objects: Record<string, any> = {
563+
crm_lead: { name: 'crm_lead', actions: [flowAction], fields: { status: {} } },
564+
};
565+
const objectql: any = {
566+
executeAction: vi.fn(),
567+
getSchema: (n: string) => objects[n],
568+
registry: { getObject: (n: string) => objects[n], getItem: () => undefined },
569+
find: vi.fn(async () => []),
570+
insert: vi.fn(), update: vi.fn(), delete: vi.fn(),
571+
};
572+
const metadata: any = {
573+
load: vi.fn(async () => null),
574+
loadDiagnosed: vi.fn(async () => ({ data: null, degraded: false, errors: [] })),
575+
listObjects: vi.fn(async () => Object.values(objects)),
576+
getObject: vi.fn(async (n: string) => objects[n]),
577+
};
578+
const protocol = { getData: vi.fn(async ({ object, id, context }: any) => { throw recordNotFoundError(object, id, context); }) };
579+
const services: Record<string, unknown> = { automation, objectql, data: objectql, metadata, protocol, auth: SIGNED_IN_AUTH };
580+
const resolve = (name: string) => services[name];
581+
const kernel = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } };
582+
const plugin = createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false });
583+
await plugin.start?.({
584+
getKernel: () => kernel,
585+
getService: (name: string) => (name === 'http.server' ? server : undefined),
586+
environmentId: undefined,
587+
logger: { info() {}, warn() {}, error() {}, debug() {} },
588+
hook: () => {},
589+
on: () => {},
590+
} as any);
591+
return async (route: string, params: Record<string, string>, body: unknown, lang = 'en') => {
592+
const handler = handlers[`POST /api/v1${route}`];
593+
expect(handler, `POST /api/v1${route} must be mounted`).toBeTypeOf('function');
594+
const res = makeRes();
595+
await handler({ body, query: {}, params, headers: { 'accept-language': lang } }, res);
596+
return res;
597+
};
598+
}
599+
600+
const RECORD_STARTS = { object: 'crm_lead', recordId: 'l_nowhere', changes: { status: 'won' } };
601+
602+
describe('errorFromThrown — the record-update preview refusing an id the caller cannot read', () => {
603+
const SENTENCES: Array<[string, string]> = [
604+
['en', 'This record does not exist, or you do not have access to it.'],
605+
['zh-CN', '该记录不存在,或您无权访问它。'],
606+
['ja-JP', 'このレコードは存在しないか、アクセスする権限がありません。'],
607+
];
608+
for (const [lang, sentence] of SENTENCES) {
609+
it(`${lang}: 404 RECORD_NOT_FOUND in that language, and Vary: Accept-Language appended last`, async () => {
610+
const send = await mount(failed());
611+
const res = await send('/automation/_record-starts', {}, RECORD_STARTS, lang);
612+
expect(res.statusCode).toBe(404);
613+
expect(res.body.error.code).toBe('RECORD_NOT_FOUND');
614+
expect(res.body.error.userMessage).toBe(sentence);
615+
expect(varyWrites(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
616+
expect(lastHeaderName(res)).toBe('Vary');
617+
});
618+
}
619+
620+
it('CONTROL the same route\'s unmarked 400 VALIDATION_FAILED writes no Vary', async () => {
621+
const send = await mount(failed());
622+
const res = await send('/automation/_record-starts', {}, { object: 'crm_lead', recordId: 'l_nowhere' }, 'zh-CN');
623+
expect(res.statusCode).toBe(400);
624+
expect(res.body.error.code).toBe('VALIDATION_FAILED');
625+
expectNoUserMessageAnywhere(res);
626+
expect(varyWrites(res)).toEqual([]);
627+
});
628+
});
629+
630+
/** Each door's MOUNTED route pattern, and the params its handler reads. */
631+
const FLOW_DOORS: Array<[string, string, Record<string, string>]> = [
632+
['deps.error with a userMessage — the resume door', '/automation/:name/runs/:runId/resume', { name: FLOW, runId: 'run_1' }],
633+
['the trigger door', '/automation/:name/trigger', { name: FLOW }],
634+
['the /actions door', '/actions/:object/:action', { object: 'crm_lead', action: 'convert_lead' }],
635+
];
636+
for (const [door, route, params] of FLOW_DOORS) {
637+
describe(`${door}: 400 FLOW_FAILED`, () => {
638+
it('marked: the userMessage on the wire, and Vary: Accept-Language appended last', async () => {
639+
const send = await mount(failed(MARK));
640+
const res = await send(route, params, {});
641+
expect(res.statusCode).toBe(400);
642+
expect(res.body.error.code).toBe('FLOW_FAILED');
643+
expect(res.body.error.userMessage).toBe(MARK);
644+
expect(varyWrites(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
645+
expect(lastHeaderName(res)).toBe('Vary');
646+
});
647+
648+
it('CONTROL unmarked: no userMessage, no Vary', async () => {
649+
const send = await mount(failed());
650+
const res = await send(route, params, {});
651+
expect(res.statusCode).toBe(400);
652+
expect(res.body.error.code).toBe('FLOW_FAILED');
653+
expectNoUserMessageAnywhere(res);
654+
expect(varyWrites(res)).toEqual([]);
655+
});
656+
});
657+
}
658+
659+
describe('the dispatch foot\'s PERMISSION_DENIED 403', () => {
660+
it('marked: the userMessage on the wire, and Vary: Accept-Language appended last', async () => {
661+
const res = await throwFromAnalyticsQuery(
662+
declaring({ status: 403, code: 'PERMISSION_DENIED', userMessage: 'Ask an admin for the Reporting role.' }, 'principal lacks cube_read on pipeline'),
663+
);
664+
expect(res.statusCode).toBe(403);
665+
expect(res.body.error.code).toBe('PERMISSION_DENIED');
666+
expect(res.body.error.userMessage).toBe('Ask an admin for the Reporting role.');
667+
expect(varyWrites(res)).toEqual([['Vary', [LOCALIZED_ANSWER_VARY]]]);
668+
expect(lastHeaderName(res)).toBe('Vary');
669+
});
670+
671+
it('CONTROL unmarked: no userMessage, no Vary', async () => {
672+
const res = await throwFromAnalyticsQuery(
673+
declaring({ status: 403, code: 'PERMISSION_DENIED' }, 'principal lacks cube_read on pipeline'),
674+
);
675+
expect(res.statusCode).toBe(403);
676+
expectNoUserMessageAnywhere(res);
677+
expect(varyWrites(res)).toEqual([]);
678+
});
679+
});
680+
});

‎packages/runtime/src/dispatcher-plugin.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,20 @@ function sendResultBase(
493493
res.header(k, v);
494494
}
495495
}
496+
// [#38123] The RETURNED exit's half of #37828's rule. A domain that
497+
// catches its own fault answers through `errorFromThrown`, `deps.error`
498+
// with a `userMessage` (the automation resume and trigger doors), the
499+
// dispatch foot's `PERMISSION_DENIED` or the `/actions` door, and every
500+
// one of those HTTP answers leaves here, never through
501+
// `errorResponseBase`. (mcp.ts's `resumeDoorError` answers the in-process
502+
// `dispatchActionResume`, not a route, so no header applies to it.)
503+
// When the body carries a `userMessage` it is in the caller's
504+
// language, so the answer varies by `Accept-Language`
505+
// (`answerVariesByLanguage`, `@objectstack/types`, asked of the body
506+
// actually sent). Written after the route's own
507+
// headers and in the contract's multi-value form, which the hosts
508+
// APPEND, so a `Vary` the route or another layer wrote keeps its tokens.
509+
if (answerVariesByLanguage(result.response.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]);
496510
res.json(result.response.body);
497511
return;
498512
}

‎packages/types/src/localized-answer-vary.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@
3838
* - `@objectstack/hono`: `thrownJson`, both of `createHonoApp`'s catch arms;
3939
* - `@objectstack/runtime`: `dispatcher-plugin`'s `errorResponseBase`.
4040
*
41+
* Those three answer a THROW. An answer a dispatcher domain catches and composes
42+
* itself is RETURNED instead (`HttpDispatcher.errorFromThrown`, `deps.error`
43+
* with a `userMessage`, the dispatch foot's `PERMISSION_DENIED`, the `/actions`
44+
* door), and it leaves through the two exits that send a returned answer, which
45+
* ask the same question of its body (#38123):
46+
*
47+
* - `@objectstack/runtime`: `dispatcher-plugin`'s `sendResultBase`;
48+
* - `@objectstack/hono`: `createHonoApp`'s `toResponse`.
49+
*
4150
* Each exit adds the token with its host's APPEND form, never a set, so a `Vary`
4251
* already on the response (CORS's `Origin`, compression's `Accept-Encoding`)
4352
* keeps its tokens.

0 commit comments

Comments
 (0)