Skip to content

Commit 8eccf51

Browse files
fix(runtime): on the standalone server, an anonymous request whose JSON body cannot be parsed gets the domain's 401, not the transport's 400 (#24250)
Fixes #24151 Clause-②: no ## What On the standalone server (`os dev`, `os serve`: `HonoServerPlugin` + the dispatcher plugin), every mount in `packages/runtime/src/dispatcher-plugin.ts` that handed `dispatch()` `req.body` now hands it `deferRequestBody(req)`, and each domain reads the body with `readDispatchedBody(body)` once its anonymous decision (ADR-0138 D2) has admitted the caller. An anonymous caller's answer no longer depends on whether its JSON body parses; an admitted caller with an unparseable body still gets the transport's `400 INVALID_REQUEST`. - `packages/runtime/src/deferred-request-body.ts` (new, module-private to the package, not exported from the index): the two halves. `deferRequestBody(req)` returns a value that holds the request and reads nothing; `readDispatchedBody(body)` reads `req.body` for a deferred value and returns any other value unchanged (what `createHonoApp`, tests and internal callers hand `dispatch()`). A deferred value read WITHOUT being resolved throws an `UnresolvedRequestBodyRead` error on every trap, so a domain that forgets the resolve fails loudly at its first read instead of acting on an invented empty body. - `dispatcher-plugin.ts`: 24 call sites, `req.body` becomes `deferRequestBody(req)` (the card's 20, plus 4 the card's grep missed, below). One note at the shared `sendResult` / `errorResponse` helpers says why. - Nine domains, one statement each, right after the anonymous decision: `analytics`, `mcp`, `keys`, `notifications`, `automation` (after the inbound-hook hand-off, which verifies raw bytes and never reads a parsed body), `actions`, `ai`, `packages`, `security`. `ai` decides per route: an admitted caller's body is read at the domain-wide decision, and an anonymous caller a route's `auth: false` admits has it read in the route loop. - Untouched: `packages/spec` (`IHttpRequest`'s body contract), `packages/adapters/hono`, `plugin-hono-server`'s adapter, PR #24244's fallback path, the domains' logic beyond when they read the body. ## H1: domain by domain (measured on a real socket, base `cbfa5e433`, head `8e9fd41b2`) Anonymous request, `content-type: application/json`, body `{"name": "probe"` (closing brace missing). "Anonymous first?" is read in the domain's source on `cbfa5e433`. | site(s) on `cbfa5e433` | domain | anonymous decided first? | base | head | |---|---|---|---|---| | `:1282` `POST /analytics/query`, `:1300` `POST /analytics/sql` | `analytics` | yes, first statement | 400 `INVALID_REQUEST` | 401 `UNAUTHENTICATED` | | `:1326` `/mcp` (POST, GET, DELETE) | `mcp` | **no**: `isMcpServerEnabled()` 404 and the service probe 501 come first (finding below) | 400 | 401 (MCP on and installed); 404 / 501 otherwise, body unread | | `:1362` `/mcp/skill` (POST, GET, DELETE) | `mcp/skill` | no anonymous decision: public by design ("Served PUBLIC like `/discovery`") | 400 | 405 `METHOD_NOT_ALLOWED`, its own answer to any non-GET | | `:1395` `POST /keys`, `:1409` `/keys` (GET, PUT, PATCH, DELETE) | `keys` | yes, first statement | 400 | 401 | | `:1447` `POST /notifications/read`, `:1456` `POST /notifications/read/all` | `notifications` | yes, first statement | 400 | 401 | | `:1676`–`:1857`, the nine `/automation` mounts | `automation` | yes, first statement | 400 | 401 | | `:1947`, `:1955`, `:1963`, the three `POST /actions/...` shapes | `actions` | yes, first statement | 400 | 401 | | `:1909` the `/ai/*` wildcards (GET, POST, PUT, PATCH, DELETE), not in the card's grep | `ai` | yes, decided once ahead of every capability answer; a route's `auth: false` opens it | 400 | 401 | | `:1553` the `/packages` registrar (16 mounts), not in the card's grep | `packages` | yes, first statement | 400 | 401 | | `:2006` `POST /security/_activation/:type/:name`, `:2020` `POST /security/permission-sets/:name/clone`, not in the card's grep | `security` | yes, first statement | 400 | 401 | At base the same anonymous requests with a well-formed body answered 401 everywhere (405 on `/mcp/skill`): only the parse decided the 400. Base was measured on the unscoped prefix; the scoped (`/environments/:environmentId`) mounts are the same registrar code, and head pins both prefixes. ## H2, H3, H4 - **H2, partly falsified.** `createHonoApp` answers 401 because `readDispatchBody` hands `dispatch()` either the parsed value or `refusedOnRead(...)`: a Proxy over `Object.create(null)` whose every trap throws the refusal and records the read, which the arm then answers. Not a getter or a thunk. `dispatch()`'s `body` parameter is `any` and `dispatch()` never reads it (it passes it to `domainRoute.handler`), so the shape is accepted. But a standalone mount cannot build it: it can learn whether the body parsed only by reading `req.body`, the one door `IHttpRequest` declares, and that read IS the refusal. A lazily forwarding Proxy would have needed no domain change, but it is not faithful: `Array.isArray`, `typeof` and `== null` read the target, fixed at creation, so a JSON array (an MCP JSON-RPC batch; `@objectstack/mcp` passes `parsedBody` to the SDK, which branches on `Array.isArray`), `null` or a primitive would reach the domain as an object. So the domains read the body explicitly, one statement each. - **H3, confirmed.** The adapter's `get body()` throws the refusal and records `refusedBodyRead`; the adapter then answers that refusal whatever the handler did. Deferring the read into the domain needs no adapter change: all anonymous pins are green with `adapter.ts` untouched. - **H4, confirmed with two named exceptions.** A signed-in caller with the same body gets `400 INVALID_REQUEST`, message "The request body could not be parsed as JSON …" (the transport's refusal, unchanged) on every site whose domain reads a body once it admits the caller. Exceptions, both answers the domain gives without reading a body, as on `createHonoApp`: `/mcp/skill` (its 405; base answered 400, measured) and `/mcp` where MCP is switched off or not installed (404 / 501; base answered 400 by construction, the mount reading the body before `dispatch()`). ## The four mounts outside the card's grep (bounded in-place fix) The card's grep `dispatcher\.dispatch\([^)]*req\.body` stops at the first `)`, so it missed the `/ai/*` wildcard (`method.toUpperCase()` precedes `req.body`) and the three registrars that spell the call over several lines (`/packages`, `/security/_activation`, `/security/permission-sets/:name/clone`). Same defect class, same mechanical change, same file, same gate families. Evidence, base `cbfa5e433`, anonymous: `POST /ai/chat`, `PUT` and `PATCH /ai/conversations/c1`, `POST /packages`, `PATCH /packages/pkg_x`, `PATCH /packages/pkg_x/enable`, `POST /packages/pkg_x/publish`, `POST /packages/pkg_x/rollback`, `POST /security/_activation/permission_set/ps_x`, `POST /security/permission-sets/ps_x/clone`: each 400 `INVALID_REQUEST` with the unparseable body, 401 `UNAUTHENTICATED` with the well-formed one. Head: 401 for both. Pinned below. Two `req.body` reads remain in the file, both deliberately: the service-emitted route mount (the mount decides `route.auth` before it reads the body, so an anonymous answer never depends on it), and the declarative-endpoint fallback, which is not a `dispatch()` mount (see Acceptance notes). ## Tests - `packages/runtime/src/dispatcher-body-after-anonymous-floor.hono.integration.test.ts` (new): real Hono socket, `LiteKernel`, both prefixes for the registrars `enableProjectScoping` mounts twice. 60 URLs, two pins each: anonymous + unparseable gets the domain's anonymous answer in the dispatcher's envelope, equal to the anonymous + well-formed answer; signed-in + unparseable gets the transport's refusal (or `/mcp/skill`'s 405). 120 tests. - `packages/runtime/src/deferred-request-body.test.ts` (new): the value's own contract, 5 tests: nothing is read until it is resolved; resolving returns the exact value (object, array, `null`, string, number, boolean); the transport's refusal propagates as the same object; values it did not defer pass through untouched; an unresolved read throws `UnresolvedRequestBodyRead` on every trap and never reads the request. - `pnpm --filter @objectstack/runtime exec vitest run --project local --maxWorkers=2`: 415 files passed, 6536 tests passed, 19 skipped (run at `bde3873ed`; `8e9fd41b2` adds only the changeset). - `--project repo` (it reads `dispatcher-plugin.ts` as text): 3 files, 808 tests passed at `8e9fd41b2`. - `pnpm --filter @objectstack/runtime typecheck`: exit 0; `check:test-typecheck` OK, the two new test files add no debt. **Ablation (one, as asked).** `deferRequestBody` mutated to `return req.body;` (eager read again) through `scripts/ablation-replace.mjs`: anchor 1 to 0, blob `7d7452c90112` to `dfaf76e93a8e`. The test imports `./dispatcher-plugin.js` from `src` by relative path, so no `dist/` is on the path. Result: 62 failed, 58 passed of 120. Red: all 60 anonymous pins, and the two signed-in `/mcp/skill` pins, whose expected answer is the domain's own 405, which an eager read pre-empts with 400. Green: the 58 signed-in refusal controls. Restore proven: blob back to `7d7452c90112` equal to HEAD, `git diff HEAD` empty. ## Gates (at `8e9fd41b2`) `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 65 commands. 64 exit 0. 1 NOT MEASURED: `pnpm check:dual-build-cjs-loads` exit 3, PREREQUISITE NOT MET (it reads every package's `dist/`; only the runtime closure is built here). `--ran` with exit codes: "65 derived famil(ies) accounted for — 64 run, 1 NOT-MEASURED". Also, for the roster families whose list lives under a changed directory: `check:route-ledger-census`, `check:error-code-casing`, `check:authz-resolver`, `check:filter-alias-parity`, `check-changeset-fixed.mjs`, each exit 0. `pnpm exec eslint --no-inline-config` over the 13 changed `.ts` files: exit 0. The repo-wide `pnpm lint`, the type-check lanes, Test Core, Build Core and dogfood are CI's. ## Acceptance notes - **`/mcp` does not decide anonymous first (H1).** `handleMcpRequest` answers `404` when `OS_MCP_SERVER_ENABLED` is off and `501` when no MCP service is installed, both ahead of its `401`. Measured in process on the standalone composition: anonymous `POST /api/v1/mcp` answers `501 NOT_IMPLEMENTED` with no MCP service and `404 RESOURCE_NOT_FOUND` with MCP off, for a well-formed and an unparseable body alike. Not changed here: the dispatch order says a domain that does not decide anonymous first is a finding, not something to add a check for. - **The declarative-endpoint fallback reads the body before its own decisions.** The fallback seam builds `execution.request.body` from `req.body` before `runAppEndpointStep` matches an endpoint or applies `authRequired`. Measured: anonymous `POST /api/v1/apps/ns/x` answers `400 INVALID_REQUEST` with an unparseable body and `404 ENDPOINT_NOT_FOUND` with a well-formed one; signed in, the same. A declared `authRequired: true` endpoint was not driven, so whether an anonymous caller gets 400 where 401 is owed there is inferred, NOT MEASURED. Not a `dispatch()` mount, so outside this change. - `/mcp/skill` is public by design and reads no body, so its row pins its own 405 rather than 401. - A signed-in caller's answer moved only where the domain answers without reading a body (the two H4 exceptions); everywhere else it is byte-for-byte what base answered. --- _Generated by [Claude Code](https://claude.ai/code/session_01QyoWKK9RwUNxBxmevy9Neb)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e74ec56 commit 8eccf51

14 files changed

Lines changed: 521 additions & 25 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
fix(runtime): on the standalone server, an anonymous request whose JSON body cannot be parsed gets the domain's `401`, not the transport's `400`
6+
7+
Clause-②: no
8+
9+
On the standalone server (`os dev`, `os serve`: `HonoServerPlugin` with the dispatcher plugin), the routes the dispatcher mounts read the request body before handing the request to `dispatch()`. The transport refuses a body it cannot parse when the body is read, so the refusal answered first: an anonymous `POST /api/v1/keys` with `{"name": "probe"` (the closing brace missing) got `400 INVALID_REQUEST`, while the same request with a well-formed body got the promised `401 UNAUTHENTICATED`. The anonymous answer depended on whether the body parsed.
10+
11+
The mounts now hand the body on unread, and each domain reads it once its anonymous decision has admitted the caller. An anonymous caller gets the same answer whatever its body, on every mounted route that reads one, unscoped and `/environments/:environmentId`-scoped:
12+
13+
- `401 UNAUTHENTICATED` on `POST /analytics/query` and `/analytics/sql`; `/keys` (every verb); `POST /notifications/read` and `/notifications/read/all`; `POST /automation`, `PUT /automation/:name` and the two `trigger` doors, `toggle`, `clone`, `resume`, `cancel` and `restore-suspension`; the three `POST /actions/...` shapes; the `/ai/*` routes; the `/packages` routes; `POST /security/_activation/:type/:name` and `POST /security/permission-sets/:name/clone`.
14+
- `/mcp` answers its own `401`, or, ahead of it, its `404` when MCP is switched off and its `501` when no MCP service is installed. None of the three reads the body, so a signed-in caller gets the `404` or `501` too.
15+
- `/mcp/skill` is public and reads no body: a `POST` or `DELETE` gets its own `405` + `Allow: GET`, signed in or not.
16+
17+
Otherwise a signed-in caller with an unparseable body still gets the transport's `400 INVALID_REQUEST`: the body is read after the anonymous decision, not dropped. A `createHonoApp` host (`@objectstack/hono`) is unchanged; it already raised the refusal only when a domain read the body.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect } from 'vitest';
4+
5+
import { deferRequestBody, readDispatchedBody, UNRESOLVED_REQUEST_BODY_READ } from './deferred-request-body.js';
6+
7+
/**
8+
* The two halves of a body handed to `dispatch()` unread (#24151): the mount
9+
* defers, the domain reads once it has admitted the caller. The socket-level
10+
* pins are `dispatcher-body-after-anonymous-floor.hono.integration.test.ts`;
11+
* these hold the value's own contract.
12+
*/
13+
14+
/** A request whose `body` getter counts its reads and answers `value`, or throws `refusal`. */
15+
function requestWith(value: unknown, refusal?: Error): { req: { readonly body: unknown }; reads: () => number } {
16+
let reads = 0;
17+
const req = {
18+
get body(): unknown {
19+
reads += 1;
20+
if (refusal) throw refusal;
21+
return value;
22+
},
23+
};
24+
return { req, reads: () => reads };
25+
}
26+
27+
describe('deferRequestBody / readDispatchedBody', () => {
28+
it('defers: building, holding and passing the value along reads nothing', () => {
29+
const { req, reads } = requestWith({ name: 'probe' });
30+
const deferred = deferRequestBody(req);
31+
32+
expect(typeof deferred).toBe('object');
33+
expect(deferred ?? 'nullish').toBe(deferred);
34+
const carried = [deferred][0];
35+
expect(carried).toBe(deferred);
36+
expect(reads()).toBe(0);
37+
});
38+
39+
it('reads the request body when the domain resolves it, returning that exact value', () => {
40+
for (const value of [{ name: 'probe' }, [{ jsonrpc: '2.0' }], null, 'text', 0, false]) {
41+
const { req, reads } = requestWith(value);
42+
const deferred = deferRequestBody(req);
43+
44+
expect(readDispatchedBody(deferred)).toBe(value);
45+
expect(reads()).toBe(1);
46+
}
47+
});
48+
49+
it("lets the transport's refusal out of the resolving read, unchanged", () => {
50+
const refusal = Object.assign(new Error('The request body could not be parsed as JSON'), { status: 400, code: 'INVALID_REQUEST' });
51+
const { req, reads } = requestWith(undefined, refusal);
52+
const deferred = deferRequestBody(req);
53+
54+
expect(reads()).toBe(0);
55+
let thrown: unknown;
56+
try {
57+
readDispatchedBody(deferred);
58+
} catch (err) {
59+
thrown = err;
60+
}
61+
// The very object the transport threw: its `status` and `code` are what it answers.
62+
expect(thrown).toBe(refusal);
63+
expect(reads()).toBe(1);
64+
});
65+
66+
it('hands every value it did not defer back as it is, reading nothing from it', () => {
67+
const refusedOnRead = new Proxy(Object.create(null) as object, {
68+
get: () => { throw new Error('read'); },
69+
has: () => { throw new Error('read'); },
70+
ownKeys: () => { throw new Error('read'); },
71+
getOwnPropertyDescriptor: () => { throw new Error('read'); },
72+
getPrototypeOf: () => { throw new Error('read'); },
73+
});
74+
const parsed = { name: 'probe' };
75+
for (const value of [parsed, refusedOnRead, undefined, null, 'text', 0, [1]]) {
76+
expect(readDispatchedBody(value)).toBe(value);
77+
}
78+
});
79+
80+
it('refuses loudly when a deferred body is read without being resolved, and never reads the request', () => {
81+
const { req, reads } = requestWith({ name: 'probe' });
82+
const deferred = deferRequestBody(req) as Record<string, unknown>;
83+
84+
/** The name of what `read` threw, or `'nothing'` when it returned. */
85+
const thrownName = (read: () => unknown): string => {
86+
try {
87+
read();
88+
} catch (err) {
89+
return (err as Error).name;
90+
}
91+
return 'nothing';
92+
};
93+
for (const read of [
94+
() => deferred.name,
95+
() => 'name' in deferred,
96+
() => Object.keys(deferred),
97+
() => ({ ...deferred }),
98+
() => JSON.stringify(deferred),
99+
]) {
100+
expect(thrownName(read)).toBe(UNRESOLVED_REQUEST_BODY_READ);
101+
}
102+
expect(reads()).toBe(0);
103+
});
104+
});
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A request body handed to `dispatch()` UNREAD, so the domain reads it only
5+
* after its anonymous decision (ADR-0138 D2) — never the mount ahead of it.
6+
*
7+
* ## Why the mount cannot read it
8+
*
9+
* `IHttpRequest.body` may REFUSE when it is read: the standard transport
10+
* (`@objectstack/plugin-hono-server`) throws its `400 INVALID_REQUEST` from the
11+
* read of a body it could not parse, and answers the request with that refusal
12+
* whatever the handler then does. The standalone mounts in
13+
* `dispatcher-plugin.ts` used to read `req.body` to build `dispatch()`'s
14+
* arguments, so the refusal fired before `dispatch()` ran — ahead of the
15+
* domain's anonymous floor, which ADR-0138 D2 makes the domain's FIRST
16+
* statement. An anonymous caller sending an unparseable JSON body was answered
17+
* `400` where the same request with a readable body is answered `401`: the
18+
* anonymous answer depended on whether the body parsed. `createHonoApp`
19+
* (`@objectstack/hono`) never had this order, because it hands `dispatch()` a
20+
* body whose refusal is raised only when a domain reads it.
21+
*
22+
* ## The two halves
23+
*
24+
* - {@link deferRequestBody} (the mount): the `body` argument for `dispatch()`,
25+
* holding the request and reading nothing.
26+
* - {@link readDispatchedBody} (the domain): called once the domain's anonymous
27+
* decision has admitted the caller. A deferred body is read there, from the
28+
* request, so a refusal is the transport's, unchanged; any other value (what
29+
* `createHonoApp`, a test, or an internal caller hands `dispatch()`) is
30+
* returned as it is.
31+
*
32+
* Reading the body THEN — rather than handing the domain no body at all, the
33+
* shape the bodiless doors use — is what keeps the admitted caller's answer: a
34+
* signed-in request with an unparseable body still gets the transport's
35+
* refusal, and a readable one the domain's answer to what it says.
36+
*
37+
* ## A deferred body read without being resolved is a programming error
38+
*
39+
* The value {@link deferRequestBody} returns throws on every read — a
40+
* property, `in`, its keys, a spread, `JSON.stringify` — with a message naming
41+
* the missing {@link readDispatchedBody} call. Holding it is not a read:
42+
* `typeof` is `'object'`, and passing it along or testing it with `??` touch
43+
* nothing, so `dispatch()` and a domain's own gates carry it untouched. A
44+
* domain that forgot to resolve it fails loudly on its first read instead of
45+
* acting on an invented empty body.
46+
*/
47+
48+
/** The request a deferred body is read from: the transport's `IHttpRequest` (`body` may throw on read). */
49+
interface BodyBearingRequest {
50+
readonly body?: unknown;
51+
}
52+
53+
/** Deferred bodies → their request. Keyed by identity, so recognising one touches none of its traps. */
54+
const DEFERRED_BODIES = new WeakMap<object, BodyBearingRequest>();
55+
56+
/** The `name` of the error a read of an unresolved deferred body throws: a programming error, never a request's. */
57+
export const UNRESOLVED_REQUEST_BODY_READ = 'UnresolvedRequestBodyRead';
58+
59+
const UNRESOLVED_READ_MESSAGE =
60+
'A request body handed to dispatch() unread was read before the domain resolved it. '
61+
+ 'A domain resolves the body with readDispatchedBody(body) once its anonymous decision has admitted the caller, '
62+
+ 'and reads only the value that call returns.';
63+
64+
/**
65+
* The `body` argument a mount hands `dispatch()`: `req.body`, NOT yet read.
66+
* The domain reads it with {@link readDispatchedBody} after its anonymous
67+
* decision; until then nothing reads it, so a body the transport refuses is
68+
* refused only for a caller the domain admitted.
69+
*/
70+
export function deferRequestBody(req: BodyBearingRequest): unknown {
71+
const unresolved = (): never => {
72+
const error = new Error(UNRESOLVED_READ_MESSAGE);
73+
error.name = UNRESOLVED_REQUEST_BODY_READ;
74+
throw error;
75+
};
76+
const deferred = new Proxy(Object.create(null) as object, {
77+
get: unresolved,
78+
has: unresolved,
79+
ownKeys: unresolved,
80+
getOwnPropertyDescriptor: unresolved,
81+
getPrototypeOf: unresolved,
82+
set: unresolved,
83+
defineProperty: unresolved,
84+
deleteProperty: unresolved,
85+
});
86+
DEFERRED_BODIES.set(deferred, req);
87+
return deferred;
88+
}
89+
90+
/**
91+
* The body a domain acts on, read once its anonymous decision has admitted the
92+
* caller. A body {@link deferRequestBody} deferred is read now, from its
93+
* request — which may throw the transport's refusal, and must be left to
94+
* propagate (`IHttpRequest.body`: a handler never carries on past it). Any
95+
* other value is returned unchanged.
96+
*/
97+
export function readDispatchedBody(body: unknown): unknown {
98+
if (typeof body !== 'object' || body === null) return body;
99+
const req = DEFERRED_BODIES.get(body);
100+
return req === undefined ? body : req.body;
101+
}

0 commit comments

Comments
 (0)