Skip to content

Commit ac43336

Browse files
os-warrenclaude
andauthored
fix(runtime): comment doors answer on an objectstack serve / objectstack dev multi-tenant host instead of 404 ENDPOINT_NOT_FOUND (#36712)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8RVgGNY8UtzQKECmEjFw5Pi)_ Part of #36469 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户看到的变化:在本机托管环境(`objectstack dev` 启动的云端运行时)里,取消表情回应、标记已解决、删除自己的评论不再报「接口不存在」。 - 原因:上一个修复(#36539)只接通了生产那种启动方式;本机开发启动方式少一层兜底路由,请求到不了那条修复。 - 坏了会怎样:只影响这三个评论操作在多租户主机上的转发;单机自部署不受影响,其他找不到的路径照旧返回原来的 404。 - 需要你做什么:无;合并后云端下次升级平台版本即生效。 ## What changes **Measured finding.** Cloud's local rig runs `apps/objectos` under `objectstack dev`, the framework CLI's composition, which mounts no `createHonoApp` catch-all. On that host the three comment doors answer `404 {"success":false,"error":{"code":"ENDPOINT_NOT_FOUND","message":"Not found"}}` whatever the framework pin, because #36539's `/comments` domain is reachable only through `dispatch()`. The gap is in this repo's `DispatcherPlugin`, so it reaches any multi-tenant host composed by `objectstack serve` / `objectstack dev`, not only cloud's rig. The card's hosted reading was a literal `404 {"success":false,"error":{"code":"ENDPOINT_NOT_FOUND","message":"Not found"}}` on `DELETE /api/v1/comments/reactions/:id`. #36539 left that spelling unexplained. This PR explains it and closes the gap it came from. **Two host shapes serve a hosted environment.** - Production and staging run cloud's `apps/objectos/server/serve-node.ts`. It mounts `createHonoApp({ prefix: '/api/v1' })` under the `HonoServerPlugin` raw app, so an unclaimed `/api/v1/comments/**` request reaches `dispatch()` and #36539's `/comments` domain. Cloud's `main` pin moved to objectstack `ed0edb1b5` on 2026-11-23 04:35Z (cloud#4929), which contains #36539 (`d463c46f64`). Whether that pin is deployed is cloud's fact and is not read here. - Cloud's local rig (`scripts/dev-local/run-stack.sh`, default `START_CMD=dev`) runs `apps/objectos` under `objectstack dev`: the framework CLI's composition, which is `HonoServerPlugin` + `DispatcherPlugin` with a `kernel-resolver` and **no** `createHonoApp` catch-all. `AuditPlugin` runs on the per-environment kernel (cloud's `hosted-slate.ts` forces `audit`), which owns no `http.server`, so nothing mounts the doors on the host's route table. `DispatcherPlugin`'s fallback seam hands on only domain-decided paths (`/actions`, `/keys`, `/notifications`, `/mcp`) and app-endpoint paths, so it declined, and the transport's `unmatchedResponse` answered. That is the card's exact body. The card was measured on this rig. **The fix**, in `@objectstack/runtime` only: - `forwarded-door-fallback.ts` (new, internal): `matchForwardedDoorPath` says whether an unrouted request is exactly one of the three comment door shapes, bare or `/environments/:id`-scoped (it reuses `matchCommentDoorPath` from `domains/comments.ts`). `toWebRequest` rebuilds the fallback's `IHttpRequest` as a Web `Request` (headers, query, original body bytes via `rawBody()`). `sendWebResponse` writes the member's `Response` back unchanged, `Set-Cookie` lines kept separate. - `DispatcherPlugin`'s fallback gains one arm, before the app-endpoint step: on a multi-tenant host, an exact door shape goes to `dispatch()` with the rebuilt request, and a `Response` result is written through. Everything after `dispatch()` is #36539's `/comments` domain, unchanged, including its authentication and membership gates. What does not change: - Any other shape still writes nothing in the fallback, so the transport's own 404/405 stands (#5090). - A single-kernel host (no `kernel-resolver`) keeps today's answers byte for byte. - The fallback runs only after every mounted route missed, so a kernel that mounts the doors itself (the self-hosted shape) is never reached here (ADR-0076 D11). - No spec, contract or plugin change; no export added. Clause-② is `no`: the arm routes only the three door shapes #36539 already declared (route ledger rows, `/comments` domain, `ICommentDoorsService`), with no new route, export or contract. ## Why Card #36469 acceptance asks for the reaction removal, resolve/reopen and own-comment delete to work on a hosted environment, "本机 cloud rig 或 staging". After #36539 the staging shape works by construction, but the local rig, where the card was measured, still answered `ENDPOINT_NOT_FOUND`. ## Verification - `packages/runtime/src/dispatcher-plugin.comment-doors-multi-tenant.test.ts` (new, 9): a real `HonoServerPlugin` + `DispatcherPlugin` over a socket with a `kernel-resolver` and a stub tenant member. Each door reaches the placed tenant's member, with the PUT body intact and the member's own headers on the answer. The environment-scoped spelling forwards at the wire path. Three non-door shapes (an extra segment, the wrong verb, GET) keep `404 ENDPOINT_NOT_FOUND` and reach no member. An unplaced request is never served out of a tenant. A host with no resolver keeps `404 ENDPOINT_NOT_FOUND`. - `packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts` (+3, 9 total): the `objectstack serve` shape over the REAL `AuditPlugin` on a real store. A member removes their own reaction (200, row gone on the tenant). A member resolves, reopens, then removes their own comment (200 each, store follows). The anonymous refusal and the two refused bodies are byte-identical to the self-hosted mount. - Red before the fix (the `dispatcher-plugin.ts` hunk removed, restore proved by `sha1 c3ac20dc…` before and after): - runtime file: 4 of 9 red (the 3 doors + the scoped spelling). The 5 that stay green are the miss and guard cases, which hold without the arm. - conformance file, runtime `dist` rebuilt without the arm: the 3 new cases red. Each answered `404 {"success":false,"error":{"code":"ENDPOINT_NOT_FOUND","message":"Not found"}}`, the card's body byte for byte. Rebuilt with the arm: green. - Suites: runtime `dispatcher-plugin*`, `*fallback*` and `route-ledger*`: 25 files, 205 tests green. `domains/comments.test.ts` + `dispatcher-plugin.multi-tenant-endpoint.integration.test.ts` green. http-conformance `hono-comment-doors` 9/9. - Typecheck: http-conformance `typecheck` exit 0. Runtime `tsc --noEmit` exit 0 and the new test file clean under `tsconfig.test.json`. Runtime `check:test-typecheck` names 3 untouched files (TS2307 on the unbuilt `@objectstack/driver-turso`, not built in this worktree). The previous round on this card recorded the same 3. - eslint `--no-inline-config` on the 4 changed source files: exit 0. - overlap-check: `origin/main` merges cleanly, 0 open PR heads share a file. - `dispatch-gates --commands` at the base `4034a6d2f8` plus this diff: 68 derived, all run. 66 exited 0. `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET: it needs every package's `dist/`), so it is NOT MEASURED here and left to CI. `check:test-source-alias` caught the new runtime test reaching `@objectstack/metadata` lazily inside a clocked case; fixed with a module-top import, now green. ## Not done here - **Same class, same host shape, unmeasured:** every other dispatcher domain that only forwards to a tenant member has the same gap on an `objectstack dev` host: `/webhooks/redeliver`, `/approvals/act`, and the `/personal-views` and `/attachments` doors open in #36690. Each would be one matcher row in `FORWARDED_DOOR_MATCHERS`. This PR does not add them; the seat decides whether to file them or let #36690 add its own rows. - **Live probe:** no hosted account here. The card's live acceptance (a reaction removed on the local rig or staging, and the `comment doors mounted` boot line) stays with the seat and the cloud lane. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [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` touched: its generated artifacts are regenerated and committed. (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. https://claude.ai/code/session_01JQwxbZu8LTZdVjqiEi4pci --- _Generated by [Claude Code](https://claude.ai/code)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 338ef35 commit ac43336

5 files changed

Lines changed: 425 additions & 4 deletions

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+
---
4+
5+
fix(comments): unreact, resolve and own-comment delete answer on an `objectstack serve` / `objectstack dev` multi-tenant host instead of `404 ENDPOINT_NOT_FOUND`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On a multi-tenant host composed the way the framework CLI composes one (`HonoServerPlugin` + `DispatcherPlugin`, a `kernel-resolver`, and no `createHonoApp` catch-all), the three comment doors, `DELETE /api/v1/comments/reactions/:id`, `PUT /api/v1/comments/:id/resolution` and `DELETE /api/v1/comments/:id`, never reached the dispatcher's `/comments` domain: `AuditPlugin` runs on the per-environment kernel, which owns no `http.server`, and `DispatcherPlugin`'s fallback seam handed on only domain-decided and app-endpoint paths. So the transport answered its own `404 ENDPOINT_NOT_FOUND`.
11+
12+
`DispatcherPlugin`'s fallback now hands exactly those three method and path shapes (bare or environment-scoped) to `dispatch()` on a multi-tenant host, with the transport's request rebuilt as a Web `Request` carrying its original body, and writes the door's `Response` back unchanged. Any other shape still writes nothing, so the transport's own miss stands; a single-kernel host keeps today's answers; and the fallback runs only after every mounted route missed, so a kernel that mounts the doors itself is never reached here.

‎packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts‎

Lines changed: 105 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
* which this kernel does not have, and the catch-all's `dispatch()` had no
1212
* domain for them. The first pin here asserts no door answers a route miss
1313
* any more, door by door. (The card's hosted reading spelled the miss
14-
* `ENDPOINT_NOT_FOUND`, the transport's own; this tree does not explain that
15-
* spelling, so the pin refuses both.)
14+
* `ENDPOINT_NOT_FOUND`, the transport's own: item 4 below explains it.)
1615
*
1716
* What this pins:
1817
* 1. on the hosted shape, a member removes their own reaction, resolves and
@@ -22,20 +21,28 @@
2221
* anonymous refusal and a refused body — because the member runs the very
2322
* registration the self-hosted mount runs;
2423
* 3. a hosted kernel without plugin-audit answers a typed
25-
* `501 NOT_IMPLEMENTED`, never a route miss.
24+
* `501 NOT_IMPLEMENTED`, never a route miss;
25+
* 4. on the `objectstack serve` / `objectstack dev` host shape (HonoServerPlugin
26+
* + DispatcherPlugin on the host, a kernel-resolver, NO catch-all) the same
27+
* member answers, with the same bytes, through DispatcherPlugin's fallback.
28+
* Without that fallback arm this shape answered the transport's own
29+
* `{"success":false,"error":{"code":"ENDPOINT_NOT_FOUND","message":"Not found"}}`,
30+
* byte for byte the card's hosted reading (cloud's local rig runs
31+
* `apps/objectos` under `objectstack dev`).
2632
*
2733
* The domain's own claim, gates and faults are pinned on the real dispatcher
2834
* in `packages/runtime/src/domains/comments.test.ts`.
2935
*/
3036

3137
import { describe, it, expect, afterEach } from 'vitest';
32-
import { ObjectKernel } from '@objectstack/core';
38+
import { ObjectKernel, LiteKernel } from '@objectstack/core';
3339
import type { Plugin, PluginContext } from '@objectstack/core';
3440
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
3541
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
3642
import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm';
3743
import { AuditPlugin } from '@objectstack/plugin-audit';
3844
import { createHonoApp } from '@objectstack/hono';
45+
import { createDispatcherPlugin } from '@objectstack/runtime';
3946
import type { IHttpServer } from '@objectstack/spec/contracts';
4047
import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-organization.testkit.js';
4148

@@ -284,3 +291,97 @@ describe('[#36469] a hosted kernel without plugin-audit answers a typed 501, nev
284291
}
285292
});
286293
});
294+
295+
/**
296+
* [#36469] The `objectstack serve` / `objectstack dev` host shape: the HOST
297+
* kernel has `HonoServerPlugin` and `DispatcherPlugin` but NO `createHonoApp`
298+
* catch-all, and a `kernel-resolver` places each request on a per-environment
299+
* kernel that runs the real AuditPlugin with no `http.server` (cloud's local
300+
* rig runs this way, `apps/objectos` under `objectstack dev`). Before
301+
* `DispatcherPlugin`'s fallback handed the door shapes on, every request below
302+
* answered the transport's own `404 ENDPOINT_NOT_FOUND`: the card's literal
303+
* hosted reading.
304+
*/
305+
async function serveShapedHost() {
306+
const tenant = await hostedDoor();
307+
// A host kernel with no data engine of its own, as the runtime's
308+
// multi-tenant fallback tests compose one: the doors' data is the tenant's.
309+
const host = new LiteKernel({ logger: { level: 'silent' } } as any);
310+
liveKernels.push(host as unknown as ObjectKernel);
311+
await host.use(new HonoServerPlugin({ port: 0, cors: false }));
312+
await host.use(new TestAuth());
313+
await host.use({
314+
name: 'test.comment-doors-kernel-resolver',
315+
version: '1.0.0',
316+
type: 'standard',
317+
init: async (ctx: PluginContext) => {
318+
ctx.registerService('kernel-resolver', {
319+
resolveKernel: async (context: any) => {
320+
const headers = context?.request?.headers;
321+
const envId = typeof headers?.get === 'function' ? headers.get(ENVIRONMENT) : headers?.[ENVIRONMENT];
322+
if (envId !== TENANT_ENV) return undefined;
323+
context.environmentId = TENANT_ENV;
324+
return tenant.kernel;
325+
},
326+
});
327+
},
328+
} as Plugin);
329+
await host.use(createDispatcherPlugin({ prefix: PREFIX, securityHeaders: false }) as any);
330+
await host.bootstrap();
331+
const base = `http://127.0.0.1:${host.getService<IHttpServer>('http.server').getPort!()}`;
332+
const send = (path: string, init: RequestInit = {}) =>
333+
fetch(`${base}${path}`, { ...init, headers: { ...(init.headers as Record<string, string>), [ENVIRONMENT]: TENANT_ENV } });
334+
return { ...tenant, send };
335+
}
336+
337+
const ENVIRONMENT = 'x-environment-id';
338+
const TENANT_ENV = 'env_tenant';
339+
340+
describe('[#36469] the comment doors answer on an `objectstack serve`-shaped multi-tenant host (no catch-all)', () => {
341+
it('a member removes their own reaction: 200, and the row is gone on the tenant', async () => {
342+
const door = await serveShapedHost();
343+
const { reactionId } = await door.seed();
344+
345+
const res = await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' }));
346+
347+
expect(await res.clone().text()).not.toContain('ENDPOINT_NOT_FOUND');
348+
expect(res.status, await res.clone().text()).toBe(200);
349+
expect(await res.json()).toEqual({ success: true, data: { id: reactionId, deleted: true } });
350+
expect(await door.stored(REACTION, reactionId)).toBeNull();
351+
});
352+
353+
it('a member resolves and reopens a thread, then removes their own comment', async () => {
354+
const door = await serveShapedHost();
355+
const { commentId, reactionId } = await door.seed();
356+
const resolution = `${PREFIX}/comments/${commentId}/resolution`;
357+
358+
const resolved = await door.send(resolution, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: true }) }));
359+
expect(resolved.status, await resolved.clone().text()).toBe(200);
360+
expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeTruthy();
361+
362+
const reopened = await door.send(resolution, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: false }) }));
363+
expect(reopened.status, await reopened.clone().text()).toBe(200);
364+
expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeFalsy();
365+
366+
await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' }));
367+
const removed = await door.send(`${PREFIX}/comments/${commentId}`, as(ALICE, { method: 'DELETE' }));
368+
expect(removed.status, await removed.clone().text()).toBe(200);
369+
expect(await door.stored(COMMENT, commentId)).toBeNull();
370+
});
371+
372+
it('the anonymous refusal and the refused body are byte-identical to the self-hosted mount', async () => {
373+
const host = await serveShapedHost();
374+
const selfHosted = await selfHostedDoor();
375+
const cases: Array<[label: string, path: string, init: RequestInit]> = [
376+
['anonymous unreact', `${PREFIX}/comments/reactions/rx_missing`, as(undefined, { method: 'DELETE' })],
377+
['a body that is not JSON', `${PREFIX}/comments/c_missing/resolution`, as(ALICE, { method: 'PUT', body: '{resolved:' })],
378+
['a body that is not exactly { resolved }', `${PREFIX}/comments/c_missing/resolution`, as(ALICE, { method: 'PUT', body: '{"resolved":"yes"}' })],
379+
];
380+
for (const [label, path, init] of cases) {
381+
const viaHost = await snapshot(await host.send(path, init));
382+
const viaMount = await snapshot(await selfHosted.send(path, init));
383+
expect(viaHost.status, label).not.toBe(404);
384+
expect(viaHost, label).toEqual(viaMount);
385+
}
386+
});
387+
});
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#36469] The comment doors on a multi-tenant host composed the way
5+
* `objectstack serve` / `objectstack dev` composes one: `HonoServerPlugin`
6+
* plus `DispatcherPlugin` on the HOST kernel, a `kernel-resolver` that places
7+
* each request on a per-environment kernel, and NO `createHonoApp` catch-all.
8+
*
9+
* `plugin-audit` runs on the tenant kernels, which own no `http.server`, so
10+
* its doors are never mounted on the host's route table. #36539 gave them a
11+
* `/comments` dispatcher domain, but on this shape nothing routes the request
12+
* into `dispatch()`: `DispatcherPlugin`'s fallback seam hands on only
13+
* domain-decided and app-endpoint paths, so the transport's own
14+
* `404 ENDPOINT_NOT_FOUND` stood — the card's exact hosted reading.
15+
*/
16+
17+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
18+
import { LiteKernel, Plugin, PluginContext } from '@objectstack/core';
19+
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
20+
import type { IHttpServer } from '@objectstack/spec/contracts';
21+
22+
import { createDispatcherPlugin } from './dispatcher-plugin.js';
23+
// Paid during collection, not inside a case's clock: `standalone-stack.ts`,
24+
// reached through the dispatcher, loads it lazily (`check:test-source-alias`).
25+
import '@objectstack/metadata';
26+
27+
/** Every request the tenant's comment-doors member received. */
28+
const served: Array<{ tenant: string; method: string; path: string; body?: string }> = [];
29+
30+
function makeTenantKernel(tenant: string) {
31+
const services: Record<string, unknown> = {
32+
comments: {
33+
handleCommentDoor: async (request: Request) => {
34+
const body = request.method === 'PUT' ? await request.text() : undefined;
35+
served.push({ tenant, method: request.method, path: new URL(request.url).pathname, ...(body !== undefined ? { body } : {}) });
36+
return Response.json(
37+
{ success: true, data: { servedBy: tenant } },
38+
{ headers: { 'x-door-answer': tenant, 'cache-control': 'no-store' } },
39+
);
40+
},
41+
},
42+
};
43+
return {
44+
__tag: tenant,
45+
getServiceAsync: async (name: string) => services[name] ?? null,
46+
getService: (name: string) => services[name] ?? null,
47+
context: { getService: (name: string) => services[name] ?? null },
48+
};
49+
}
50+
51+
const TENANTS: Record<string, ReturnType<typeof makeTenantKernel>> = {
52+
'env-1': makeTenantKernel('env-1'),
53+
};
54+
55+
function tenantResolverPlugin(): Plugin {
56+
return {
57+
name: 'com.objectstack.test.kernel-resolver',
58+
version: '1.0.0',
59+
init: async (ctx: PluginContext) => {
60+
ctx.registerService('kernel-resolver', {
61+
resolveKernel: async (context: any) => {
62+
// Fetch `Headers` or a plain record, as the cloud host's
63+
// resolver reads them (`headerAccessor`, objectos-runtime).
64+
const headers = context?.request?.headers;
65+
const envId: string | undefined = typeof headers?.get === 'function'
66+
? headers.get('x-environment-id') ?? undefined
67+
: headers?.['x-environment-id'];
68+
const kernel = envId ? TENANTS[envId] : undefined;
69+
if (!kernel) return undefined;
70+
context.environmentId = envId;
71+
return kernel;
72+
},
73+
});
74+
},
75+
};
76+
}
77+
78+
let kernel: LiteKernel | undefined;
79+
let baseUrl = '';
80+
81+
beforeAll(async () => {
82+
kernel = new LiteKernel();
83+
kernel.use(new HonoServerPlugin({ port: 0, cors: false }));
84+
kernel.use(tenantResolverPlugin());
85+
kernel.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false }));
86+
await kernel.bootstrap();
87+
const httpServer = kernel.getService<IHttpServer>('http.server');
88+
baseUrl = `http://127.0.0.1:${httpServer.getPort!()}`;
89+
}, 60_000);
90+
91+
afterAll(async () => {
92+
if (!kernel) return;
93+
await Promise.race([kernel.shutdown(), new Promise<void>((resolve) => setTimeout(resolve, 10_000))]);
94+
}, 60_000);
95+
96+
/** The envelope fields these assertions read. */
97+
type Answer = { success?: boolean; data?: unknown; error?: { code?: string } };
98+
99+
const SIGNED_IN = { 'X-Environment-Id': 'env-1', 'content-type': 'application/json' };
100+
101+
describe('[#36469] comment doors on an `objectstack serve`-shaped multi-tenant host', () => {
102+
it.each([
103+
['DELETE', '/api/v1/comments/reactions/rxn_1'],
104+
['PUT', '/api/v1/comments/cmt_1/resolution'],
105+
['DELETE', '/api/v1/comments/cmt_1'],
106+
])('%s %s reaches the placed tenant\'s comments member', async (method, path) => {
107+
served.length = 0;
108+
const res = await fetch(`${baseUrl}${path}`, {
109+
method,
110+
headers: SIGNED_IN,
111+
...(method === 'PUT' ? { body: JSON.stringify({ resolved: true }) } : {}),
112+
});
113+
const body = await res.json() as Answer;
114+
// Before the bridge: the transport's own unmatched answer, the card's reading.
115+
expect(body?.error?.code).not.toBe('ENDPOINT_NOT_FOUND');
116+
expect(res.status).toBe(200);
117+
expect(body).toEqual({ success: true, data: { servedBy: 'env-1' } });
118+
// The member's own headers reach the client.
119+
expect(res.headers.get('x-door-answer')).toBe('env-1');
120+
expect(res.headers.get('cache-control')).toBe('no-store');
121+
expect(served).toEqual([
122+
{ tenant: 'env-1', method, path, ...(method === 'PUT' ? { body: JSON.stringify({ resolved: true }) } : {}) },
123+
]);
124+
}, 60_000);
125+
126+
it('serves the environment-scoped spelling at the door\'s wire path', async () => {
127+
served.length = 0;
128+
const res = await fetch(`${baseUrl}/api/v1/environments/env-1/comments/reactions/rxn_2`, {
129+
method: 'DELETE',
130+
headers: SIGNED_IN,
131+
});
132+
expect(res.status).toBe(200);
133+
expect(served).toEqual([{ tenant: 'env-1', method: 'DELETE', path: '/api/v1/comments/reactions/rxn_2' }]);
134+
}, 60_000);
135+
136+
it.each([
137+
['DELETE', '/api/v1/comments/reactions/rxn_1/extra'],
138+
['PUT', '/api/v1/comments/cmt_1'],
139+
['GET', '/api/v1/comments/reactions/rxn_1'],
140+
])('%s %s is not a door: the transport\'s own miss stands', async (method, path) => {
141+
served.length = 0;
142+
const res = await fetch(`${baseUrl}${path}`, { method, headers: SIGNED_IN });
143+
const body = await res.json() as Answer;
144+
expect(res.status).toBe(404);
145+
expect(body?.error?.code).toBe('ENDPOINT_NOT_FOUND');
146+
expect(served).toEqual([]);
147+
}, 60_000);
148+
149+
it('an unplaced request is never served out of a tenant kernel', async () => {
150+
served.length = 0;
151+
const res = await fetch(`${baseUrl}/api/v1/comments/reactions/rxn_1`, { method: 'DELETE' });
152+
expect(res.status).not.toBe(200);
153+
expect(served).toEqual([]);
154+
}, 60_000);
155+
});
156+
157+
describe('[#36469] a single-kernel host keeps today\'s answer', () => {
158+
let single: LiteKernel | undefined;
159+
let singleUrl = '';
160+
beforeAll(async () => {
161+
single = new LiteKernel();
162+
single.use(new HonoServerPlugin({ port: 0, cors: false }));
163+
single.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false }));
164+
await single.bootstrap();
165+
singleUrl = `http://127.0.0.1:${single.getService<IHttpServer>('http.server').getPort!()}`;
166+
}, 60_000);
167+
afterAll(async () => {
168+
if (!single) return;
169+
await Promise.race([single.shutdown(), new Promise<void>((resolve) => setTimeout(resolve, 10_000))]);
170+
}, 60_000);
171+
172+
it('no kernel-resolver: an unmounted door is the transport\'s miss, not handed to dispatch()', async () => {
173+
const res = await fetch(`${singleUrl}/api/v1/comments/reactions/rxn_1`, { method: 'DELETE' });
174+
expect(res.status).toBe(404);
175+
expect(((await res.json()) as Answer)?.error?.code).toBe('ENDPOINT_NOT_FOUND');
176+
}, 60_000);
177+
});

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { deferRequestBody } from './deferred-request-body.js';
1010
import { validationFailureDetails, VALIDATION_FAILED_STATUS } from './validation-failure.js';
1111
import { buildApiError } from './error-envelope.js';
1212
import { appEndpointMountPrefix, isAppEndpointPath, runAppEndpointStep } from './api-endpoint-step.js';
13+
import { matchForwardedDoorPath, sendWebResponse, toWebRequest } from './forwarded-door-fallback.js';
1314
import type { EndpointExecutorDeps } from './endpoint-executor.js';
1415
import { callData } from './action-execution.js';
1516
import { createEndpointRateLimiterRegistry } from './endpoint-policy.js';
@@ -2470,6 +2471,30 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu
24702471
sendResult(result, res);
24712472
return;
24722473
}
2474+
// ── [#36469] A forwarded door on a multi-tenant host ────
2475+
// A door whose plugin lives on the per-environment
2476+
// kernel (the comment doors) is mounted on no route table
2477+
// here, and this host has no `createHonoApp` catch-all to
2478+
// carry it into `dispatch()`. Exact door shapes only, so
2479+
// a miss still writes nothing; multi-tenant only, so a
2480+
// single-kernel host keeps today's answers byte for byte.
2481+
// See `forwarded-door-fallback.ts`.
2482+
if (dispatcher.isMultiTenantHost() && matchForwardedDoorPath(req.method, path, prefix)) {
2483+
const result = await dispatcher.dispatch(
2484+
req.method,
2485+
path.substring(prefix.length),
2486+
undefined,
2487+
req.query,
2488+
{ request: await toWebRequest(req) },
2489+
prefix,
2490+
);
2491+
if (result.handled && result.result instanceof Response) {
2492+
await sendWebResponse(result.result, res);
2493+
return;
2494+
}
2495+
sendResult(result, res);
2496+
return;
2497+
}
24732498
// ── Scoping test FIRST, before any resolution ────────
24742499
// Everything below costs something (a kernel resolve, a
24752500
// session lookup), and an unmatched request that is not

0 commit comments

Comments
 (0)