diff --git a/.changeset/36469-comment-doors-serve-host.md b/.changeset/36469-comment-doors-serve-host.md new file mode 100644 index 00000000000..3b95976d3f6 --- /dev/null +++ b/.changeset/36469-comment-doors-serve-host.md @@ -0,0 +1,12 @@ +--- +'@objectstack/runtime': patch +--- + +fix(comments): unreact, resolve and own-comment delete answer on an `objectstack serve` / `objectstack dev` multi-tenant host instead of `404 ENDPOINT_NOT_FOUND` + +Clause-②: no +Metadata-protocol: none + +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`. + +`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. diff --git a/packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts b/packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts index 40f22911647..4f17402a211 100644 --- a/packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts +++ b/packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts @@ -11,8 +11,7 @@ * which this kernel does not have, and the catch-all's `dispatch()` had no * domain for them. The first pin here asserts no door answers a route miss * any more, door by door. (The card's hosted reading spelled the miss - * `ENDPOINT_NOT_FOUND`, the transport's own; this tree does not explain that - * spelling, so the pin refuses both.) + * `ENDPOINT_NOT_FOUND`, the transport's own: item 4 below explains it.) * * What this pins: * 1. on the hosted shape, a member removes their own reaction, resolves and @@ -22,20 +21,28 @@ * anonymous refusal and a refused body — because the member runs the very * registration the self-hosted mount runs; * 3. a hosted kernel without plugin-audit answers a typed - * `501 NOT_IMPLEMENTED`, never a route miss. + * `501 NOT_IMPLEMENTED`, never a route miss; + * 4. on the `objectstack serve` / `objectstack dev` host shape (HonoServerPlugin + * + DispatcherPlugin on the host, a kernel-resolver, NO catch-all) the same + * member answers, with the same bytes, through DispatcherPlugin's fallback. + * Without that fallback arm this shape answered the transport's own + * `{"success":false,"error":{"code":"ENDPOINT_NOT_FOUND","message":"Not found"}}`, + * byte for byte the card's hosted reading (cloud's local rig runs + * `apps/objectos` under `objectstack dev`). * * The domain's own claim, gates and faults are pinned on the real dispatcher * in `packages/runtime/src/domains/comments.test.ts`. */ import { describe, it, expect, afterEach } from 'vitest'; -import { ObjectKernel } from '@objectstack/core'; +import { ObjectKernel, LiteKernel } from '@objectstack/core'; import type { Plugin, PluginContext } from '@objectstack/core'; import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import { AuditPlugin } from '@objectstack/plugin-audit'; import { createHonoApp } from '@objectstack/hono'; +import { createDispatcherPlugin } from '@objectstack/runtime'; import type { IHttpServer } from '@objectstack/spec/contracts'; import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-organization.testkit.js'; @@ -284,3 +291,97 @@ describe('[#36469] a hosted kernel without plugin-audit answers a typed 501, nev } }); }); + +/** + * [#36469] The `objectstack serve` / `objectstack dev` host shape: the HOST + * kernel has `HonoServerPlugin` and `DispatcherPlugin` but NO `createHonoApp` + * catch-all, and a `kernel-resolver` places each request on a per-environment + * kernel that runs the real AuditPlugin with no `http.server` (cloud's local + * rig runs this way, `apps/objectos` under `objectstack dev`). Before + * `DispatcherPlugin`'s fallback handed the door shapes on, every request below + * answered the transport's own `404 ENDPOINT_NOT_FOUND`: the card's literal + * hosted reading. + */ +async function serveShapedHost() { + const tenant = await hostedDoor(); + // A host kernel with no data engine of its own, as the runtime's + // multi-tenant fallback tests compose one: the doors' data is the tenant's. + const host = new LiteKernel({ logger: { level: 'silent' } } as any); + liveKernels.push(host as unknown as ObjectKernel); + await host.use(new HonoServerPlugin({ port: 0, cors: false })); + await host.use(new TestAuth()); + await host.use({ + name: 'test.comment-doors-kernel-resolver', + version: '1.0.0', + type: 'standard', + init: async (ctx: PluginContext) => { + ctx.registerService('kernel-resolver', { + resolveKernel: async (context: any) => { + const headers = context?.request?.headers; + const envId = typeof headers?.get === 'function' ? headers.get(ENVIRONMENT) : headers?.[ENVIRONMENT]; + if (envId !== TENANT_ENV) return undefined; + context.environmentId = TENANT_ENV; + return tenant.kernel; + }, + }); + }, + } as Plugin); + await host.use(createDispatcherPlugin({ prefix: PREFIX, securityHeaders: false }) as any); + await host.bootstrap(); + const base = `http://127.0.0.1:${host.getService('http.server').getPort!()}`; + const send = (path: string, init: RequestInit = {}) => + fetch(`${base}${path}`, { ...init, headers: { ...(init.headers as Record), [ENVIRONMENT]: TENANT_ENV } }); + return { ...tenant, send }; +} + +const ENVIRONMENT = 'x-environment-id'; +const TENANT_ENV = 'env_tenant'; + +describe('[#36469] the comment doors answer on an `objectstack serve`-shaped multi-tenant host (no catch-all)', () => { + it('a member removes their own reaction: 200, and the row is gone on the tenant', async () => { + const door = await serveShapedHost(); + const { reactionId } = await door.seed(); + + const res = await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' })); + + expect(await res.clone().text()).not.toContain('ENDPOINT_NOT_FOUND'); + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toEqual({ success: true, data: { id: reactionId, deleted: true } }); + expect(await door.stored(REACTION, reactionId)).toBeNull(); + }); + + it('a member resolves and reopens a thread, then removes their own comment', async () => { + const door = await serveShapedHost(); + const { commentId, reactionId } = await door.seed(); + const resolution = `${PREFIX}/comments/${commentId}/resolution`; + + const resolved = await door.send(resolution, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: true }) })); + expect(resolved.status, await resolved.clone().text()).toBe(200); + expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeTruthy(); + + const reopened = await door.send(resolution, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: false }) })); + expect(reopened.status, await reopened.clone().text()).toBe(200); + expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeFalsy(); + + await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' })); + const removed = await door.send(`${PREFIX}/comments/${commentId}`, as(ALICE, { method: 'DELETE' })); + expect(removed.status, await removed.clone().text()).toBe(200); + expect(await door.stored(COMMENT, commentId)).toBeNull(); + }); + + it('the anonymous refusal and the refused body are byte-identical to the self-hosted mount', async () => { + const host = await serveShapedHost(); + const selfHosted = await selfHostedDoor(); + const cases: Array<[label: string, path: string, init: RequestInit]> = [ + ['anonymous unreact', `${PREFIX}/comments/reactions/rx_missing`, as(undefined, { method: 'DELETE' })], + ['a body that is not JSON', `${PREFIX}/comments/c_missing/resolution`, as(ALICE, { method: 'PUT', body: '{resolved:' })], + ['a body that is not exactly { resolved }', `${PREFIX}/comments/c_missing/resolution`, as(ALICE, { method: 'PUT', body: '{"resolved":"yes"}' })], + ]; + for (const [label, path, init] of cases) { + const viaHost = await snapshot(await host.send(path, init)); + const viaMount = await snapshot(await selfHosted.send(path, init)); + expect(viaHost.status, label).not.toBe(404); + expect(viaHost, label).toEqual(viaMount); + } + }); +}); diff --git a/packages/runtime/src/dispatcher-plugin.comment-doors-multi-tenant.test.ts b/packages/runtime/src/dispatcher-plugin.comment-doors-multi-tenant.test.ts new file mode 100644 index 00000000000..69e7d0e6041 --- /dev/null +++ b/packages/runtime/src/dispatcher-plugin.comment-doors-multi-tenant.test.ts @@ -0,0 +1,177 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36469] The comment doors on a multi-tenant host composed the way + * `objectstack serve` / `objectstack dev` composes one: `HonoServerPlugin` + * plus `DispatcherPlugin` on the HOST kernel, a `kernel-resolver` that places + * each request on a per-environment kernel, and NO `createHonoApp` catch-all. + * + * `plugin-audit` runs on the tenant kernels, which own no `http.server`, so + * its doors are never mounted on the host's route table. #36539 gave them a + * `/comments` dispatcher domain, but on this shape nothing routes the request + * into `dispatch()`: `DispatcherPlugin`'s fallback seam hands on only + * domain-decided and app-endpoint paths, so the transport's own + * `404 ENDPOINT_NOT_FOUND` stood — the card's exact hosted reading. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { LiteKernel, Plugin, PluginContext } from '@objectstack/core'; +import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; +import type { IHttpServer } from '@objectstack/spec/contracts'; + +import { createDispatcherPlugin } from './dispatcher-plugin.js'; +// Paid during collection, not inside a case's clock: `standalone-stack.ts`, +// reached through the dispatcher, loads it lazily (`check:test-source-alias`). +import '@objectstack/metadata'; + +/** Every request the tenant's comment-doors member received. */ +const served: Array<{ tenant: string; method: string; path: string; body?: string }> = []; + +function makeTenantKernel(tenant: string) { + const services: Record = { + comments: { + handleCommentDoor: async (request: Request) => { + const body = request.method === 'PUT' ? await request.text() : undefined; + served.push({ tenant, method: request.method, path: new URL(request.url).pathname, ...(body !== undefined ? { body } : {}) }); + return Response.json( + { success: true, data: { servedBy: tenant } }, + { headers: { 'x-door-answer': tenant, 'cache-control': 'no-store' } }, + ); + }, + }, + }; + return { + __tag: tenant, + getServiceAsync: async (name: string) => services[name] ?? null, + getService: (name: string) => services[name] ?? null, + context: { getService: (name: string) => services[name] ?? null }, + }; +} + +const TENANTS: Record> = { + 'env-1': makeTenantKernel('env-1'), +}; + +function tenantResolverPlugin(): Plugin { + return { + name: 'com.objectstack.test.kernel-resolver', + version: '1.0.0', + init: async (ctx: PluginContext) => { + ctx.registerService('kernel-resolver', { + resolveKernel: async (context: any) => { + // Fetch `Headers` or a plain record, as the cloud host's + // resolver reads them (`headerAccessor`, objectos-runtime). + const headers = context?.request?.headers; + const envId: string | undefined = typeof headers?.get === 'function' + ? headers.get('x-environment-id') ?? undefined + : headers?.['x-environment-id']; + const kernel = envId ? TENANTS[envId] : undefined; + if (!kernel) return undefined; + context.environmentId = envId; + return kernel; + }, + }); + }, + }; +} + +let kernel: LiteKernel | undefined; +let baseUrl = ''; + +beforeAll(async () => { + kernel = new LiteKernel(); + kernel.use(new HonoServerPlugin({ port: 0, cors: false })); + kernel.use(tenantResolverPlugin()); + kernel.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false })); + await kernel.bootstrap(); + const httpServer = kernel.getService('http.server'); + baseUrl = `http://127.0.0.1:${httpServer.getPort!()}`; +}, 60_000); + +afterAll(async () => { + if (!kernel) return; + await Promise.race([kernel.shutdown(), new Promise((resolve) => setTimeout(resolve, 10_000))]); +}, 60_000); + +/** The envelope fields these assertions read. */ +type Answer = { success?: boolean; data?: unknown; error?: { code?: string } }; + +const SIGNED_IN = { 'X-Environment-Id': 'env-1', 'content-type': 'application/json' }; + +describe('[#36469] comment doors on an `objectstack serve`-shaped multi-tenant host', () => { + it.each([ + ['DELETE', '/api/v1/comments/reactions/rxn_1'], + ['PUT', '/api/v1/comments/cmt_1/resolution'], + ['DELETE', '/api/v1/comments/cmt_1'], + ])('%s %s reaches the placed tenant\'s comments member', async (method, path) => { + served.length = 0; + const res = await fetch(`${baseUrl}${path}`, { + method, + headers: SIGNED_IN, + ...(method === 'PUT' ? { body: JSON.stringify({ resolved: true }) } : {}), + }); + const body = await res.json() as Answer; + // Before the bridge: the transport's own unmatched answer, the card's reading. + expect(body?.error?.code).not.toBe('ENDPOINT_NOT_FOUND'); + expect(res.status).toBe(200); + expect(body).toEqual({ success: true, data: { servedBy: 'env-1' } }); + // The member's own headers reach the client. + expect(res.headers.get('x-door-answer')).toBe('env-1'); + expect(res.headers.get('cache-control')).toBe('no-store'); + expect(served).toEqual([ + { tenant: 'env-1', method, path, ...(method === 'PUT' ? { body: JSON.stringify({ resolved: true }) } : {}) }, + ]); + }, 60_000); + + it('serves the environment-scoped spelling at the door\'s wire path', async () => { + served.length = 0; + const res = await fetch(`${baseUrl}/api/v1/environments/env-1/comments/reactions/rxn_2`, { + method: 'DELETE', + headers: SIGNED_IN, + }); + expect(res.status).toBe(200); + expect(served).toEqual([{ tenant: 'env-1', method: 'DELETE', path: '/api/v1/comments/reactions/rxn_2' }]); + }, 60_000); + + it.each([ + ['DELETE', '/api/v1/comments/reactions/rxn_1/extra'], + ['PUT', '/api/v1/comments/cmt_1'], + ['GET', '/api/v1/comments/reactions/rxn_1'], + ])('%s %s is not a door: the transport\'s own miss stands', async (method, path) => { + served.length = 0; + const res = await fetch(`${baseUrl}${path}`, { method, headers: SIGNED_IN }); + const body = await res.json() as Answer; + expect(res.status).toBe(404); + expect(body?.error?.code).toBe('ENDPOINT_NOT_FOUND'); + expect(served).toEqual([]); + }, 60_000); + + it('an unplaced request is never served out of a tenant kernel', async () => { + served.length = 0; + const res = await fetch(`${baseUrl}/api/v1/comments/reactions/rxn_1`, { method: 'DELETE' }); + expect(res.status).not.toBe(200); + expect(served).toEqual([]); + }, 60_000); +}); + +describe('[#36469] a single-kernel host keeps today\'s answer', () => { + let single: LiteKernel | undefined; + let singleUrl = ''; + beforeAll(async () => { + single = new LiteKernel(); + single.use(new HonoServerPlugin({ port: 0, cors: false })); + single.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false })); + await single.bootstrap(); + singleUrl = `http://127.0.0.1:${single.getService('http.server').getPort!()}`; + }, 60_000); + afterAll(async () => { + if (!single) return; + await Promise.race([single.shutdown(), new Promise((resolve) => setTimeout(resolve, 10_000))]); + }, 60_000); + + it('no kernel-resolver: an unmounted door is the transport\'s miss, not handed to dispatch()', async () => { + const res = await fetch(`${singleUrl}/api/v1/comments/reactions/rxn_1`, { method: 'DELETE' }); + expect(res.status).toBe(404); + expect(((await res.json()) as Answer)?.error?.code).toBe('ENDPOINT_NOT_FOUND'); + }, 60_000); +}); diff --git a/packages/runtime/src/dispatcher-plugin.ts b/packages/runtime/src/dispatcher-plugin.ts index cd4840fd9e4..18b9f712fff 100644 --- a/packages/runtime/src/dispatcher-plugin.ts +++ b/packages/runtime/src/dispatcher-plugin.ts @@ -10,6 +10,7 @@ import { deferRequestBody } from './deferred-request-body.js'; import { validationFailureDetails, VALIDATION_FAILED_STATUS } from './validation-failure.js'; import { buildApiError } from './error-envelope.js'; import { appEndpointMountPrefix, isAppEndpointPath, runAppEndpointStep } from './api-endpoint-step.js'; +import { matchForwardedDoorPath, sendWebResponse, toWebRequest } from './forwarded-door-fallback.js'; import type { EndpointExecutorDeps } from './endpoint-executor.js'; import { callData } from './action-execution.js'; import { createEndpointRateLimiterRegistry } from './endpoint-policy.js'; @@ -2470,6 +2471,30 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu sendResult(result, res); return; } + // ── [#36469] A forwarded door on a multi-tenant host ──── + // A door whose plugin lives on the per-environment + // kernel (the comment doors) is mounted on no route table + // here, and this host has no `createHonoApp` catch-all to + // carry it into `dispatch()`. Exact door shapes only, so + // a miss still writes nothing; multi-tenant only, so a + // single-kernel host keeps today's answers byte for byte. + // See `forwarded-door-fallback.ts`. + if (dispatcher.isMultiTenantHost() && matchForwardedDoorPath(req.method, path, prefix)) { + const result = await dispatcher.dispatch( + req.method, + path.substring(prefix.length), + undefined, + req.query, + { request: await toWebRequest(req) }, + prefix, + ); + if (result.handled && result.result instanceof Response) { + await sendWebResponse(result.result, res); + return; + } + sendResult(result, res); + return; + } // ── Scoping test FIRST, before any resolution ──────── // Everything below costs something (a kernel resolve, a // session lookup), and an unmatched request that is not diff --git a/packages/runtime/src/forwarded-door-fallback.ts b/packages/runtime/src/forwarded-door-fallback.ts new file mode 100644 index 00000000000..6b44dc5615f --- /dev/null +++ b/packages/runtime/src/forwarded-door-fallback.ts @@ -0,0 +1,106 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36469] Forwarded doors on a host with no `createHonoApp` catch-all. + * + * Some dispatcher domains do nothing but forward the transport's request to a + * member on the REQUEST kernel's slot and hand back the member's `Response` + * (ruling A on #22438). The comment doors are one: `plugin-audit` mounts them + * on its own kernel's `http.server`, and a per-environment kernel owns none, + * so on a multi-tenant host the `/comments` domain is the only way in. + * + * `createHonoApp`'s catch-all reaches that domain through `dispatch()`. A host + * composed the way `objectstack serve` / `objectstack dev` composes one — + * `HonoServerPlugin` + `DispatcherPlugin`, no catch-all — does not: before this + * file, `DispatcherPlugin`'s fallback seam handed on only domain-decided and + * app-endpoint paths, so these doors answered the transport's own + * `404 ENDPOINT_NOT_FOUND` there (the card's hosted reading). + * + * This module is the fallback's half of the bridge: + * - {@link matchForwardedDoorPath} says whether an unrouted request is exactly + * one of the forwarded door shapes (bare or environment-scoped); + * - {@link toWebRequest} rebuilds the transport's request as a Web `Request`, + * because the seam hands the fallback an `IHttpRequest`, not the raw one; + * - {@link sendWebResponse} writes the member's `Response` back as it is. + * + * Only EXACT door shapes are handed on, so a miss still writes nothing and the + * transport's unmatched answer stands (#5090), and the fallback runs only after + * every mounted route missed, so a kernel that mounted the doors itself (the + * self-hosted shape) is never reached here (ADR-0076 D11). + */ + +import { matchCommentDoorPath } from './domains/comments.js'; + +/** The door matchers the fallback hands on. Each takes the dispatcher's clean path. */ +const FORWARDED_DOOR_MATCHERS: ReadonlyArray<(method: string, cleanPath: string) => boolean> = [ + matchCommentDoorPath, +]; + +/** `/environments/:id` at the head of a sub-path (the environment-scoped spelling). */ +const SCOPED_HEAD = /^\/environments\/[^/]+(?=\/)/; + +/** + * Is `method path` exactly one forwarded door? `path` is the wire path, + * `prefix` included; anything outside the prefix is not a door. + */ +export function matchForwardedDoorPath(method: string, path: string, prefix: string): boolean { + if (!path.startsWith(prefix + '/')) return false; + const clean = path.substring(prefix.length).replace(SCOPED_HEAD, '').replace(/\/$/, ''); + return FORWARDED_DOOR_MATCHERS.some((matches) => matches(method, clean)); +} + +/** The slice of `IHttpRequest` the rebuild reads. */ +export interface FallbackRequestLike { + method: string; + path: string; + query?: Record; + headers?: Record; + rawBody?: () => Promise; +} + +/** + * The transport's request as a Web `Request` at its own wire path, headers + * and query carried, and its ORIGINAL body bytes for a verb that has one. + */ +export async function toWebRequest(req: FallbackRequestLike): Promise { + const headers = new Headers(); + for (const [name, value] of Object.entries(req.headers ?? {})) { + if (value === undefined) continue; + if (Array.isArray(value)) for (const v of value) headers.append(name, v); + else headers.set(name, value); + } + const url = new URL(req.path, `http://${headers.get('host') ?? 'localhost'}`); + for (const [name, value] of Object.entries(req.query ?? {})) { + if (value === undefined || value === null) continue; + if (Array.isArray(value)) for (const v of value) url.searchParams.append(name, String(v)); + else url.searchParams.set(name, String(value)); + } + const method = req.method.toUpperCase(); + const init: RequestInit = { method, headers }; + if (method !== 'GET' && method !== 'HEAD' && typeof req.rawBody === 'function') { + const bytes = await req.rawBody(); + // Copied into a plain `ArrayBuffer`-backed view: `BodyInit` does not + // take a view over a possibly shared buffer. + if (bytes.byteLength > 0) init.body = new Uint8Array(bytes); + } + return new Request(url, init); +} + +/** The slice of `IHttpResponse` the write uses. */ +export interface FallbackResponseLike { + status(code: number): unknown; + header(name: string, value: string | string[]): unknown; + send(data: string | Uint8Array | ArrayBuffer): void | Promise; +} + +/** Write a member's `Response` through the transport: status, headers and body bytes, unchanged. */ +export async function sendWebResponse(response: Response, res: FallbackResponseLike): Promise { + res.status(response.status); + const cookies = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []; + response.headers.forEach((value, name) => { + if (name.toLowerCase() === 'set-cookie') return; + res.header(name, value); + }); + if (cookies.length > 0) res.header('set-cookie', cookies); + await res.send(new Uint8Array(await response.arrayBuffer())); +}