From b4353a0f0821c61fe41aeb2b46c7468fc6fdf789 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:35:54 +0000 Subject: [PATCH 01/12] feat(spec): ICommentDoorsService declares the comment doors transport-neutrally on the comments slot Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/spec/api-surface/contracts.json | 1 + packages/spec/export-origins/contracts.json | 1 + .../contracts/comment-doors-service.test.ts | 43 ++++++++++ .../src/contracts/comment-doors-service.ts | 83 +++++++++++++++++++ .../contracts/core-service-contracts.test.ts | 9 +- .../src/contracts/core-service-contracts.ts | 11 +++ packages/spec/src/contracts/index.ts | 2 + 7 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 packages/spec/src/contracts/comment-doors-service.test.ts create mode 100644 packages/spec/src/contracts/comment-doors-service.ts diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index d33bacc4712..6b7e9a78ae1 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -175,6 +175,7 @@ "ICacheService (interface)", "ICloudBindingService (interface)", "IClusterService (interface)", + "ICommentDoorsService (interface)", "ICounter (interface)", "ICryptoProvider (interface)", "IDataDriver (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index b44cd720196..951a7fc810f 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -175,6 +175,7 @@ "ICacheService": "src/contracts/cache-service.ts#ICacheService (interface)", "ICloudBindingService": "src/contracts/cloud-binding-service.ts#ICloudBindingService (interface)", "IClusterService": "src/contracts/cluster-service.ts#IClusterService (interface)", + "ICommentDoorsService": "src/contracts/comment-doors-service.ts#ICommentDoorsService (interface)", "ICounter": "src/contracts/cluster-service.ts#ICounter (interface)", "ICryptoProvider": "src/contracts/crypto-provider.ts#ICryptoProvider (interface)", "IDataDriver": "src/contracts/data-driver.ts#IDataDriver (interface)", diff --git a/packages/spec/src/contracts/comment-doors-service.test.ts b/packages/spec/src/contracts/comment-doors-service.test.ts new file mode 100644 index 00000000000..17c00a61af5 --- /dev/null +++ b/packages/spec/src/contracts/comment-doors-service.test.ts @@ -0,0 +1,43 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#36469] `ICommentDoorsService.handleCommentDoor`: the three comment doors, +// declared on the `comments` slot's contract transport-neutrally, so the +// runtime dispatcher can reach them on a kernel with no `http.server`. +// +// Type-level pins, the shape `webhook-service.test.ts` uses: the member is +// OPTIONAL, at the web-standard `(request: Request) => Promise` +// shape, the barrel exports the same contract, and the `comments` slot is +// typed by it. The aliases are exported so TS6196 does not flag them as +// unused; `check:test-typecheck` compiles this file. + +import { describe, it, expect } from 'vitest'; +import type { ICommentDoorsService } from './comment-doors-service'; +import type { ICommentDoorsService as ICommentDoorsServiceFromBarrel, ServiceSlotContract } from './index'; + +type Eq = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; +type Assert = T; + +type HandleCommentDoor = NonNullable; + +/** Optional: a service may omit it. A required member turns this alias red. */ +export type CommentDoorIsOptional = Assert<{} extends Pick ? true : false>; + +/** One web-standard `Request` in: the whole input, with no execution context beside it. */ +export type CommentDoorTakesOneRequest = Assert, [request: Request]>>; + +/** A web-standard `Response` out, asynchronously. */ +export type CommentDoorAnswersAResponse = Assert, Promise>>; + +/** The barrel (`@objectstack/spec/contracts`) exports this contract, not a look-alike. */ +export type BarrelExportsTheContract = Assert>; + +/** The `comments` slot is typed by this contract, so the dispatcher's probe is typed. */ +export type CommentsSlotIsTheContract = Assert, ICommentDoorsService>>; + +describe('ICommentDoorsService.handleCommentDoor: the comment doors, declared transport-neutrally', () => { + it('is optional: a service object without it still satisfies ICommentDoorsService', () => { + const service: ICommentDoorsService = {}; + + expect(service.handleCommentDoor).toBeUndefined(); + }); +}); diff --git a/packages/spec/src/contracts/comment-doors-service.ts b/packages/spec/src/contracts/comment-doors-service.ts new file mode 100644 index 00000000000..cd28dfc89f0 --- /dev/null +++ b/packages/spec/src/contracts/comment-doors-service.ts @@ -0,0 +1,83 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * @objectstack/spec/contracts/comment-doors-service + * + * Cross-package contract for the comment doors' service slot. The + * implementation lives in `@objectstack/plugin-audit`, which owns the comment + * objects (`sys_comment`, `sys_comment_reaction`), and is registered as the + * `comments` service. + * + * The comment doors are the three server doors a member reaches without an + * object-level grant for the write they make: + * + * - `DELETE /api/v1/comments/reactions/:id` — remove your own reaction; + * - `PUT /api/v1/comments/:id/resolution` — resolve or reopen a thread you + * can read; + * - `DELETE /api/v1/comments/:id` — remove a comment you wrote. + * + * A self-hosted kernel serves them from the plugin's own mount on the + * kernel's `http.server`. A hosted tenant kernel owns no socket and so has no + * `http.server`, and the runtime dispatcher reaches it instead (#36469; the + * bridge the maintainer's ruling A on #22438 directs for every member of this + * class, as `IWebhookService.handleRedeliver` and + * `IApprovalService.handleActionPage` are bridged). This slot is what the + * dispatcher forwards to. + */ + +/** + * The comment doors' service: the occupant of the `comments` slot. + * + * Every member is optional. A kernel without `@objectstack/plugin-audit` + * leaves the slot empty, and a caller probes for the member it needs before + * calling it. + */ +export interface ICommentDoorsService { + /** + * **The three comment doors, served transport-neutrally.** One member for + * the three routes, because they are one family with one caller rule: the + * member matches the request's method and path against the three routes + * and runs the door that owns it. + * + * What it serves, exactly as the plugin's self-hosted mount serves it (one + * body, two faces): + * - It resolves the caller from the request's own credentials, through the + * kernel's `auth` service, the rule every own-row door applies. With no + * signed-in caller it answers `401`; a sign-in that still owes an + * authentication step answers `403`. + * - Every refusal and answer is the door's own, in the + * `{ success, data | error: { code, message } }` envelope: the unreact + * door and the own-comment delete door answer `{ id, deleted: true }`, + * the resolution door `{ id, is_resolved, resolved_by, resolved_at }`. + * - A request whose method and path match none of the three routes answers + * `404 ENDPOINT_NOT_FOUND`; the dispatcher never forwards one. + * + * **Transport-neutral, deliberately.** A web-standard `Request` goes in and + * a `Response` comes out: no Hono context, no raw app, no `http.server` + * type. The request's URL path is the door's own wire path + * (`/api/v1/comments/…`). + * + * **It takes no `ExecutionContext`.** It resolves the caller from the + * request, so both kernel shapes judge the same caller by one rule, in one + * place. + * + * **Its one caller** is the runtime `HttpDispatcher`'s `/comments` domain, + * which claims exactly the three method and path shapes and forwards the + * request with its body unread. The paths are not on the ADR-0069 + * auth-gate allow-list and the project-membership gate does not skip them, + * so on that shape the dispatcher door is stricter than the self-hosted + * mount, never looser. The self-hosted mount is not a caller, and no path is + * mounted twice. + * + * **Optional, and its absence is loud.** An empty `comments` slot or an + * absent member answers a typed `501`, ⛔ never `ENDPOINT_NOT_FOUND`: that + * answer would tell a member the URL is wrong, when what is missing is the + * service behind it. + * + * @param request - The forwarded request: the caller's credentials are in + * its headers, the comment or reaction id in its path, and the + * resolution door's `{ "resolved": boolean }` in its JSON body + * @returns The door's JSON answer + */ + handleCommentDoor?(request: Request): Promise; +} diff --git a/packages/spec/src/contracts/core-service-contracts.test.ts b/packages/spec/src/contracts/core-service-contracts.test.ts index b3486dfd4f4..7f38cc7ca73 100644 --- a/packages/spec/src/contracts/core-service-contracts.test.ts +++ b/packages/spec/src/contracts/core-service-contracts.test.ts @@ -21,6 +21,7 @@ import type { ISecurityService } from './security-service'; import type { IShareLinkService } from './share-link-service'; import type { IWebhookService } from './webhook-service'; import type { ITriggerApiService } from './trigger-api-service'; +import type { ICommentDoorsService } from './comment-doors-service'; /** Compile-time assertion helper: fails to typecheck unless `T` is exactly `true`. */ type Expect = T; @@ -128,6 +129,10 @@ describe('slot → contract ledger beyond the enum', () => { expectTypeOf(getService('trigger-api')).toEqualTypeOf(); expectTypeOf(getService('trigger-api')?.handleInboundHook) .toEqualTypeOf(); + // [#36469] The comment doors' slot, probed for its one member. + expectTypeOf(getService('comments')).toEqualTypeOf(); + expectTypeOf(getService('comments')?.handleCommentDoor) + .toEqualTypeOf(); // CONTROL: the same lookup resolves the slots that were already // mapped exactly as before. @@ -139,7 +144,7 @@ describe('slot → contract ledger beyond the enum', () => { it('holds exactly the non-core slots whose contract is written', () => { const extra = [ - 'security', 'shareLinks', 'objectql', 'http.server', 'http-server', 'webhooks', 'trigger-api', + 'security', 'shareLinks', 'objectql', 'http.server', 'http-server', 'webhooks', 'trigger-api', 'comments', ] as const; // Exact, not merely a subset: a key added to or dropped from the // non-core ledger without this list changing is a type error here. @@ -152,7 +157,7 @@ describe('slot → contract ledger beyond the enum', () => { // into `CoreServiceContracts` and this assertion is what catches it. expect(slots.has(key), `'${key}' is a CoreServiceName — move its entry into CoreServiceContracts`).toBe(false); } - expect(extra).toHaveLength(7); + expect(extra).toHaveLength(8); }); it('still resolves a slot with no written contract to unknown', () => { diff --git a/packages/spec/src/contracts/core-service-contracts.ts b/packages/spec/src/contracts/core-service-contracts.ts index 13ce41bf32e..e4b2b594f50 100644 --- a/packages/spec/src/contracts/core-service-contracts.ts +++ b/packages/spec/src/contracts/core-service-contracts.ts @@ -43,6 +43,7 @@ import type { IHttpServer } from './http-server'; import type { IObjectQLEngine } from './objectql-engine'; import type { IWebhookService } from './webhook-service'; import type { ITriggerApiService } from './trigger-api-service'; +import type { ICommentDoorsService } from './comment-doors-service'; /** * The evidenced slot → contract bindings. @@ -197,6 +198,16 @@ export interface ServiceSlotContracts extends CoreServiceContracts { * leaving the slot `unknown`. */ 'trigger-api': ITriggerApiService; + /** + * {@link ICommentDoorsService}, registered by `@objectstack/plugin-audit`: + * `AuditPlugin` registers its comment doors under `comments`, typed as + * this contract, so the runtime dispatcher's `/comments` domain reaches + * them on a kernel with no `http.server` (#36469). + * + * Every member is optional, so a reader still probes for the one it calls + * (`handleCommentDoor`). + */ + comments: ICommentDoorsService; } /** diff --git a/packages/spec/src/contracts/index.ts b/packages/spec/src/contracts/index.ts index 49e930a2554..37ba4152690 100644 --- a/packages/spec/src/contracts/index.ts +++ b/packages/spec/src/contracts/index.ts @@ -68,6 +68,8 @@ export * from './share-link-service.js'; // ListView. export * from './approval-service.js'; export * from './webhook-service.js'; +// [#36469] The comment doors' slot (`comments`), for the dispatcher's hosted door. +export * from './comment-doors-service.js'; export * from './package-service.js'; export * from './knowledge-service.js'; export * from './knowledge-adapter.js'; From aca81450bc71146760292d17cc621dd44fcaeff9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:39:12 +0000 Subject: [PATCH 02/12] feat(plugin-audit): serve the comment doors on the comments slot for a kernel with no http.server Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/plugins/plugin-audit/package.json | 1 + .../plugins/plugin-audit/src/audit-plugin.ts | 77 +++++++++---- .../plugin-audit/src/comment-doors-member.ts | 103 ++++++++++++++++++ pnpm-lock.yaml | 3 + 4 files changed, 163 insertions(+), 21 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/comment-doors-member.ts diff --git a/packages/plugins/plugin-audit/package.json b/packages/plugins/plugin-audit/package.json index d9fd9b88a5e..44a7b8bd121 100644 --- a/packages/plugins/plugin-audit/package.json +++ b/packages/plugins/plugin-audit/package.json @@ -30,6 +30,7 @@ "@objectstack/metadata-core": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", + "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/spec": "workspace:*", "@objectstack/types": "workspace:*" }, diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 6f043bfbbb0..d9a10e74db2 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -12,6 +12,7 @@ import type { IAuditCheckpointSink, IAuthService, IClusterService, + ICommentDoorsService, ICryptoProvider, IDataEngine, IHttpServer, @@ -70,6 +71,7 @@ import { type CommentDoorsEngine, type CommentPostingGate, } from './comment-routes.js'; +import { createCommentDoorMember } from './comment-doors-member.js'; import { admitMentionRecipients } from './mention-recipient-gate.js'; import { installActivityReadVisibility } from './activity-read-visibility.js'; import { installActivityFieldRedaction } from './activity-field-redaction.js'; @@ -528,6 +530,16 @@ export class AuditPlugin implements Plugin { ...createAppActivityWriter({ getEngine: getLedgerEngine, getActorSnapshot: () => this.actorSnapshotOf }), }); + // [#36469] The comment doors on the `comments` slot, transport-neutrally + // (`ICommentDoorsService.handleCommentDoor`): the runtime dispatcher's + // `/comments` domain forwards to it on a kernel with no `http.server` (a + // hosted tenant kernel), where `mountCommentDoors` has nothing to mount + // on. Same registration as the mount; nothing is read until a request. + const commentDoors: ICommentDoorsService = { + handleCommentDoor: createCommentDoorMember((http) => registerCommentDoors(http, ctx)), + }; + ctx.registerService('comments', commentDoors); + // ADR-0029 D8 — contribute this plugin's object translations to the i18n // service on kernel:ready (the i18n plugin may register after this one). if (typeof (ctx as any).hook === 'function') { @@ -1081,8 +1093,9 @@ export class AuditPlugin implements Plugin { * grant. * * Every service the doors read is read per request, so a provider that - * registers after this hook is still seen. A kernel with no HTTP server - * mounts nothing, and says so. + * registers after this hook is still seen. A kernel with no HTTP server (a + * hosted tenant kernel) mounts nothing here: the `comments` slot serves the + * same doors to the dispatcher (#36469), and the line says so. */ private mountCommentDoors(ctx: PluginContext): void { const optional = (name: string): T | undefined => { @@ -1095,28 +1108,18 @@ export class AuditPlugin implements Plugin { // `http.server` is the canonical name; `http-server` the deprecated alias. const http = optional('http.server') ?? optional('http-server'); if (!http) { - ctx.logger.warn( - `AuditPlugin: no HTTP server is registered, so the comment doors (DELETE ${COMMENT_REACTION_REMOVE_ROUTE}, ` + - `PUT ${COMMENT_RESOLUTION_ROUTE}, DELETE ${COMMENT_REMOVE_ROUTE}) are not mounted: a member whose grants carry ` + - 'no delete cannot remove their own reaction or comment, and resolves only the threads they started.', + // [#36469] The hosted shape: a tenant kernel owns no socket. The doors + // are not lost there: the `comments` slot (registered in `init()`) serves + // them to the runtime dispatcher's `/comments` domain, which the host's + // `createHonoApp` reaches. + ctx.logger.info( + `AuditPlugin: comment doors mounted on the 'comments' service for the dispatcher's /comments domain ` + + `(no HTTP server on this kernel): DELETE ${COMMENT_REACTION_REMOVE_ROUTE}, PUT ${COMMENT_RESOLUTION_ROUTE} ` + + `and DELETE ${COMMENT_REMOVE_ROUTE}`, ); return; } - const getEngine = () => optional('objectql') ?? optional('data'); - const resolveCaller = platformCallerResolver({ - getEngine, - getAuth: () => optional('auth'), - tenancy: tenancyServiceResolver(ctx), - }); - registerCommentReactionRoutes(http, { - getEngine: () => getEngine() as unknown as CommentReactionEngine | undefined, - resolveCaller, - }); - registerCommentDoorsRoutes(http, { - getEngine: () => getEngine() as unknown as CommentDoorsEngine | undefined, - resolveCaller, - getSecurity: () => optional('security'), - }); + registerCommentDoors(http, ctx); ctx.logger.info( `AuditPlugin: comment doors mounted at DELETE ${COMMENT_REACTION_REMOVE_ROUTE}, PUT ${COMMENT_RESOLUTION_ROUTE} ` + `and DELETE ${COMMENT_REMOVE_ROUTE}`, @@ -1148,6 +1151,38 @@ export class AuditPlugin implements Plugin { } } +/** + * Register the three comment doors on `http`, over this kernel's services, each + * read per request. The ONE registration both faces run: the self-hosted mount + * on the kernel's `http.server` (`mountCommentDoors`) and the private table + * behind the `comments` slot's `handleCommentDoor` (`comment-doors-member.ts`), + * so the two cannot answer a request differently. + */ +function registerCommentDoors(http: IHttpServer, ctx: PluginContext): void { + const optional = (name: string): T | undefined => { + try { + return ctx.getService(name) ?? undefined; + } catch { + return undefined; + } + }; + const getEngine = () => optional('objectql') ?? optional('data'); + const resolveCaller = platformCallerResolver({ + getEngine, + getAuth: () => optional('auth'), + tenancy: tenancyServiceResolver(ctx), + }); + registerCommentReactionRoutes(http, { + getEngine: () => getEngine() as unknown as CommentReactionEngine | undefined, + resolveCaller, + }); + registerCommentDoorsRoutes(http, { + getEngine: () => getEngine() as unknown as CommentDoorsEngine | undefined, + resolveCaller, + getSecurity: () => optional('security'), + }); +} + /** * How the unreact door reaches the `tenancy` service: the kernel's async * accessor, read per request and classified by the composition diff --git a/packages/plugins/plugin-audit/src/comment-doors-member.ts b/packages/plugins/plugin-audit/src/comment-doors-member.ts new file mode 100644 index 00000000000..822bb68744b --- /dev/null +++ b/packages/plugins/plugin-audit/src/comment-doors-member.ts @@ -0,0 +1,103 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36469] The comment doors, served transport-neutrally: + * `ICommentDoorsService.handleCommentDoor` (`@objectstack/spec/contracts`). + * + * ## Why this exists + * + * `AuditPlugin` mounts the three comment doors on the kernel's `http.server` + * (`mountCommentDoors`). A hosted tenant kernel owns no socket and registers no + * `http.server`, so on that shape the doors were never mounted, and the host's + * catch-all answered every unreact, resolve and own-comment delete with the + * unmatched `404 ENDPOINT_NOT_FOUND`. The runtime dispatcher reaches that + * kernel instead, through its `/comments` domain, which forwards the request + * to this member on the kernel's `comments` slot (ruling A on #22438, applied + * to this member of the class). + * + * ## One body, two faces + * + * The member runs the SAME registrars the self-hosted mount runs + * (`registerCommentReactionRoutes`, `registerCommentDoorsRoutes`) over the SAME + * deps, on a private route table of its own: a `HonoHttpServer` that never + * listens. So the caller resolution, every refusal, the request-body reading + * (and its refusal) and every answer are byte-for-byte the mount's: there is + * no second copy of a door to drift from the first. The table is built on the + * first request, and every service the doors read is still read per request. + * + * ⛔ The table never listens and is never the kernel's `http.server`: a + * self-hosted kernel keeps its own mount unchanged, and no path is mounted + * twice on a socket. + * + * ## What it answers outside the three routes + * + * A method and path that match none of the three routes answers + * `404 ENDPOINT_NOT_FOUND`, the transport's own unmatched answer, without + * reaching any door. The dispatcher claims exactly the three shapes and never + * forwards one. + */ + +import type { IHttpServer } from '@objectstack/spec/contracts'; +import { HonoHttpServer } from '@objectstack/plugin-hono-server'; + +import { COMMENT_REACTION_REMOVE_ROUTE } from './comment-reaction-routes.js'; +import { COMMENT_REMOVE_ROUTE, COMMENT_RESOLUTION_ROUTE } from './comment-routes.js'; + +/** One comment door's method and route pattern. */ +export interface CommentDoorRoute { + method: 'DELETE' | 'PUT'; + route: string; +} + +/** + * The three comment doors, in the self-hosted mount's registration order (the + * order a request is matched in): the unreact door, then the resolution door, + * then the own-comment delete door. + */ +export const COMMENT_DOOR_ROUTES: readonly CommentDoorRoute[] = [ + { method: 'DELETE', route: COMMENT_REACTION_REMOVE_ROUTE }, + { method: 'PUT', route: COMMENT_RESOLUTION_ROUTE }, + { method: 'DELETE', route: COMMENT_REMOVE_ROUTE }, +]; + +/** Does `pathname` match `pattern`, whose `:name` segments match one non-empty segment each? */ +function matchesRoute(pattern: string, pathname: string): boolean { + const want = pattern.split('/'); + const got = pathname.split('/'); + if (want.length !== got.length) return false; + return want.every((segment, i) => (segment.startsWith(':') ? got[i].length > 0 : segment === got[i])); +} + +/** + * The comment door `method` and `pathname` name, or `undefined`. Exported so + * the runtime's claim and this member can be pinned to the same three shapes. + */ +export function matchCommentDoor(method: string, pathname: string): CommentDoorRoute | undefined { + const verb = method.toUpperCase(); + return COMMENT_DOOR_ROUTES.find((door) => door.method === verb && matchesRoute(door.route, pathname)); +} + +/** The transport's unmatched answer, as `plugin-hono-server`'s `unmatchedResponse` writes it. */ +function unmatched(): Response { + return new Response(JSON.stringify({ success: false, error: { code: 'ENDPOINT_NOT_FOUND', message: 'Not found' } }), { + status: 404, + headers: { 'content-type': 'application/json' }, + }); +} + +/** + * Build `handleCommentDoor` over `mount`, the function that registers the + * three doors on an `IHttpServer` (the one the self-hosted mount calls too). + */ +export function createCommentDoorMember(mount: (http: IHttpServer) => void): (request: Request) => Promise { + let table: HonoHttpServer | undefined; + return async (request: Request): Promise => { + if (!matchCommentDoor(request.method, new URL(request.url).pathname)) return unmatched(); + if (!table) { + const built = new HonoHttpServer(0); + mount(built); + table = built; + } + return table.getRawApp().fetch(request); + }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c6d8c5e6cbd..00a2cc23326 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1899,6 +1899,9 @@ importers: '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects + '@objectstack/plugin-hono-server': + specifier: workspace:* + version: link:../plugin-hono-server '@objectstack/spec': specifier: workspace:* version: link:../../spec From 35ad4ead4931bf4ec2febb2961c83ba3927fcfce Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:41:31 +0000 Subject: [PATCH 03/12] feat(runtime): a /comments dispatcher domain forwards the three comment doors to the comments slot Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/runtime/src/domains/comments.test.ts | 273 ++++++++++++++++++ packages/runtime/src/domains/comments.ts | 202 +++++++++++++ packages/runtime/src/http-dispatcher.ts | 6 + packages/runtime/src/route-ledger.ts | 8 + 4 files changed, 489 insertions(+) create mode 100644 packages/runtime/src/domains/comments.test.ts create mode 100644 packages/runtime/src/domains/comments.ts diff --git a/packages/runtime/src/domains/comments.test.ts b/packages/runtime/src/domains/comments.test.ts new file mode 100644 index 00000000000..c84ad6ef66c --- /dev/null +++ b/packages/runtime/src/domains/comments.test.ts @@ -0,0 +1,273 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36469] The `/comments` dispatcher domain — the three comment doors for a + * kernel with no `http.server` (ruling A on #22438, applied to this member of + * the class). + * + * Driven through the REAL `HttpDispatcher.dispatch()` on a kernel that + * registers no `http.server` (the hosted shape), with a stub `comments` + * member that reads the request it is handed (method, path, JSON body). + * + * What this pins: + * 1. each of the three shapes reaches the member with the transport's own + * request, body unread, and the member's `Response` comes back as it is; + * 2. the claim is the three method and path shapes alone: every other method + * and every other path under `/comments` keeps the dispatcher's ordinary + * miss, and the member never runs for one; + * 3. an absent `comments` slot, or a slot with no `handleCommentDoor`, + * answers `501 NOT_IMPLEMENTED` — ⛔ never a route miss — and the slot is + * read per request; + * 4. a member that throws, or a body the transport already consumed, answers + * a sanitised `500` and is logged; + * 5. the environment-scoped spelling reaches the member at the door's wire + * path, its body unread; + * 6. no preamble-gate exemption: a signed-in non-member of the environment + * and a session owing an authentication step are stopped before the + * member runs, a member of the environment reaches it. + * + * The wire half — `createHonoApp` over a kernel with the REAL AuditPlugin and + * no `http.server` — is + * `packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { HttpDispatcher } from '../http-dispatcher.js'; +import type { HttpProtocolContext, KernelResolver } from '../http-dispatcher.js'; + +const ORIGIN = 'http://tenant.example'; +const JSON_HEADERS = { 'Content-Type': 'application/json' }; + +/** A member shaped like `ICommentDoorsService.handleCommentDoor`: it records and echoes what it was handed. */ +function stubMember() { + const seen: Array<{ request: Request; method: string; path: string; body: string }> = []; + const handleCommentDoor = vi.fn(async (request: Request): Promise => { + const body = await request.text(); + const path = new URL(request.url).pathname; + seen.push({ request, method: request.method, path, body }); + return new Response(JSON.stringify({ success: true, data: { method: request.method, path, body } }), { + status: 200, + headers: JSON_HEADERS, + }); + }); + return { handleCommentDoor, seen }; +} + +/** A kernel with no `http.server` — only the services named. */ +function kernelWith(services: Record): any { + return { + getState: () => 'running', + getService: (n: string) => services[n] ?? null, + getServiceAsync: async (n: string) => services[n] ?? null, + context: { getService: (n: string) => services[n] ?? null }, + }; +} + +function makeDispatcher(services: Record) { + const logger = { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }; + const dispatcher = new HttpDispatcher(kernelWith(services), undefined, { enforceProjectMembership: false }); + (dispatcher as any).domainDeps.logger = logger; + return { dispatcher, logger }; +} + +const ctx = (request: Request): HttpProtocolContext => ({ request }); +const wire = (method: string, path: string, body?: unknown, prefix = '/api/v1') => new Request(`${ORIGIN}${prefix}${path}`, { + method, + headers: JSON_HEADERS, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), +}); + +/** `{ status, code }` of a dispatcher envelope answer. */ +const envelope = (r: any) => ({ status: r.response?.status, code: r.response?.body?.error?.code }); + +const DOORS: Array<[method: string, path: string, body?: unknown]> = [ + ['DELETE', '/comments/reactions/rx_1'], + ['PUT', '/comments/c_1/resolution', { resolved: true }], + ['DELETE', '/comments/c_1'], +]; + +describe('[#36469] /comments forwards the three comment doors to the comments member on a kernel with no http.server', () => { + it.each(DOORS)('%s %s reaches the member with the transport\'s own request, body unread, and its Response comes back as it is', async (method, path, body) => { + const member = stubMember(); + const { dispatcher } = makeDispatcher({ comments: { handleCommentDoor: member.handleCommentDoor } }); + const request = wire(method, path, body); + + const result = await dispatcher.dispatch(method, path, { resolved: 'not-this-one' }, {}, ctx(request)); + + expect(result.handled).toBe(true); + expect(result.response).toBeUndefined(); + expect(member.handleCommentDoor).toHaveBeenCalledTimes(1); + expect(member.seen[0]!.request).toBe(request); + const res = result.result as Response; + expect(res).toBeInstanceOf(Response); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + success: true, + data: { method, path: `/api/v1${path}`, body: body === undefined ? '' : JSON.stringify(body) }, + }); + }); + + it('claims exactly the three shapes: every other method and path keeps the ordinary miss, and the member never runs', async () => { + const member = stubMember(); + const { dispatcher } = makeDispatcher({ comments: { handleCommentDoor: member.handleCommentDoor } }); + const misses: Array<[string, string]> = [ + ['GET', '/comments/c_1'], + ['POST', '/comments/c_1'], + ['PATCH', '/comments/c_1'], + ['PUT', '/comments/c_1'], + ['DELETE', '/comments/c_1/resolution'], + ['GET', '/comments/c_1/resolution'], + ['PUT', '/comments/reactions/rx_1'], + ['DELETE', '/comments'], + ['DELETE', '/comments/'], + ['DELETE', '/comments/reactions/rx_1/x'], + ['DELETE', '/comments/c_1/resolution/x'], + ]; + for (const [method, path] of misses) { + const result = await dispatcher.dispatch(method, path, undefined, {}, ctx(wire(method, path))); + expect(envelope(result), `${method} ${path}`).toEqual({ status: 404, code: 'ROUTE_NOT_FOUND' }); + } + // A lexical sibling is not under the segment claim at all. + expect((dispatcher as any).domainRegistry.resolve('/commentsx/c_1', 'DELETE')).toBeUndefined(); + expect(member.handleCommentDoor).not.toHaveBeenCalled(); + }); + + it('the environment-scoped spelling reaches the member at the door\'s wire path, body unread', async () => { + const member = stubMember(); + const { dispatcher } = makeDispatcher({ comments: { handleCommentDoor: member.handleCommentDoor } }); + const path = '/environments/env_1/comments/c_9/resolution'; + const request = wire('PUT', path, { resolved: false }); + + const result = await dispatcher.dispatch('PUT', path, {}, {}, ctx(request)); + + expect(result.response, JSON.stringify(result.response?.body)).toBeUndefined(); + expect(member.seen).toHaveLength(1); + expect(member.seen[0]!.path).toBe('/api/v1/comments/c_9/resolution'); + expect(member.seen[0]!.body).toBe('{"resolved":false}'); + }); +}); + +describe('[#36469] absence is a typed 501, never a route miss', () => { + it('no comments slot on the kernel: 501 NOT_IMPLEMENTED, naming the plugin that registers it', async () => { + const { dispatcher } = makeDispatcher({}); + for (const [method, path, body] of DOORS) { + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path, body))); + expect(envelope(result), `${method} ${path}`).toEqual({ status: 501, code: 'NOT_IMPLEMENTED' }); + expect(result.response?.body?.error?.message).toContain('@objectstack/plugin-audit'); + } + }); + + it('a comments service with no handleCommentDoor member: 501 NOT_IMPLEMENTED, naming the member', async () => { + const { dispatcher } = makeDispatcher({ comments: { somethingElse: vi.fn() } }); + const result = await dispatcher.dispatch('DELETE', '/comments/c_1', {}, {}, ctx(wire('DELETE', '/comments/c_1'))); + expect(envelope(result)).toEqual({ status: 501, code: 'NOT_IMPLEMENTED' }); + expect(result.response?.body?.error?.message).toContain('does not implement handleCommentDoor'); + }); + + it('the slot is read per request: one registered after a 501 is reached by the next request', async () => { + const services: Record = {}; + const dispatcher = new HttpDispatcher(kernelWith(services), undefined, { enforceProjectMembership: false }); + + const before = await dispatcher.dispatch('DELETE', '/comments/c_1', {}, {}, ctx(wire('DELETE', '/comments/c_1'))); + expect(envelope(before)).toEqual({ status: 501, code: 'NOT_IMPLEMENTED' }); + + const member = stubMember(); + services.comments = { handleCommentDoor: member.handleCommentDoor }; + const after = await dispatcher.dispatch('DELETE', '/comments/c_1', {}, {}, ctx(wire('DELETE', '/comments/c_1'))); + expect(after.response, JSON.stringify(after.response?.body)).toBeUndefined(); + expect((after.result as Response).status).toBe(200); + }); +}); + +describe('[#36469] faults are the server\'s, answered as such', () => { + it('a member that throws: a sanitised 500, its message withheld from the client and logged', async () => { + const boom = new Error('SQLITE_ERROR: no such table: sys_comment'); + const { dispatcher, logger } = makeDispatcher({ comments: { handleCommentDoor: vi.fn().mockRejectedValue(boom) } }); + + const result = await dispatcher.dispatch('DELETE', '/comments/c_1', {}, {}, ctx(wire('DELETE', '/comments/c_1'))); + + expect(envelope(result)).toEqual({ status: 500, code: 'INTERNAL_ERROR' }); + expect(JSON.stringify(result.response?.body)).not.toContain('sys_comment'); + expect(logger.error).toHaveBeenCalledTimes(1); + expect(logger.error.mock.calls[0]![1]).toBe(boom); + }); + + it('a PUT whose body the transport already consumed: 500 and logged, and the member is never asked', async () => { + const member = stubMember(); + const { dispatcher, logger } = makeDispatcher({ comments: { handleCommentDoor: member.handleCommentDoor } }); + const request = wire('PUT', '/comments/c_1/resolution', { resolved: true }); + await request.text(); + + const result = await dispatcher.dispatch('PUT', '/comments/c_1/resolution', {}, {}, ctx(request)); + + expect(envelope(result)).toEqual({ status: 500, code: 'INTERNAL_ERROR' }); + expect(member.handleCommentDoor).not.toHaveBeenCalled(); + expect(String(logger.error.mock.calls[0]![0])).toContain('request body was consumed'); + }); +}); + +describe('[#36469] no preamble-gate exemption — the credential is the session, so both gates apply', () => { + const ENV = 'env-tenant-1'; + const USER = 'u-member'; + + function makeTenantHost(opts: { member?: boolean; authGate?: { code: string; message: string } } = {}) { + const comments = stubMember(); + const find = vi.fn(async (object: string) => (object === 'sys_environment_member' && opts.member + ? [{ environment_id: ENV, user_id: USER }] + : [])); + const objectql = { + find, + getObjects: vi.fn().mockReturnValue({}), + registry: { + getObject: vi.fn((name: string) => (name === 'sys_environment_member' ? { name } : null)), + getRegisteredTypes: vi.fn().mockReturnValue([]), + }, + }; + const auth = { + isAuthGateActive: () => opts.authGate !== undefined, + getApi: async () => ({ + getSession: async () => ({ + user: { id: USER, ...(opts.authGate ? { authGate: opts.authGate } : {}) }, + session: { userId: USER, activeOrganizationId: 'org-tenant' }, + }), + }), + }; + const tenant = kernelWith({ objectql, auth, comments: { handleCommentDoor: comments.handleCommentDoor } }); + const resolver: KernelResolver = { + resolveKernel: async (c: HttpProtocolContext) => { + c.environmentId = ENV; + return tenant; + }, + }; + const dispatcher = new HttpDispatcher(kernelWith({}), undefined, { + kernelResolver: resolver, + enforceProjectMembership: true, + }); + return { dispatcher, comments }; + } + + it('a signed-in caller who is not a member of the environment is refused 403 before the member runs', async () => { + const { dispatcher, comments } = makeTenantHost(); + const result = await dispatcher.dispatch('DELETE', '/comments/c_1', {}, {}, ctx(wire('DELETE', '/comments/c_1'))); + expect(envelope(result)).toEqual({ status: 403, code: 'PROJECT_MEMBERSHIP_REQUIRED' }); + expect(comments.handleCommentDoor).not.toHaveBeenCalled(); + }); + + it('⭐ control: a member of the environment reaches the member', async () => { + const { dispatcher, comments } = makeTenantHost({ member: true }); + const result = await dispatcher.dispatch('DELETE', '/comments/c_1', {}, {}, ctx(wire('DELETE', '/comments/c_1'))); + expect(result.response, JSON.stringify(result.response?.body)).toBeUndefined(); + expect(comments.handleCommentDoor).toHaveBeenCalledTimes(1); + }); + + it('a session that still owes an authentication step is stopped by the ADR-0069 gate: the paths are not allow-listed', async () => { + const { dispatcher, comments } = makeTenantHost({ + member: true, + authGate: { code: 'PASSWORD_EXPIRED', message: 'Your password has expired.' }, + }); + const result = await dispatcher.dispatch('PUT', '/comments/c_1/resolution', {}, {}, ctx(wire('PUT', '/comments/c_1/resolution', { resolved: true }))); + expect(result.response?.status).toBe(403); + expect(result.response?.body?.error?.details?.code ?? result.response?.body?.error?.code).toBe('PASSWORD_EXPIRED'); + expect(comments.handleCommentDoor).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/runtime/src/domains/comments.ts b/packages/runtime/src/domains/comments.ts new file mode 100644 index 00000000000..487567937b0 --- /dev/null +++ b/packages/runtime/src/domains/comments.ts @@ -0,0 +1,202 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `/comments` domain — the three comment doors, reached through the dispatcher + * (ADR-0076 D11 step ③'s shape: the dispatcher owns registration, and one + * route bridges to one service slot; `/webhooks/redeliver` is the precedent + * this mirrors). + * + * ## What it serves, and for whom + * + * The three server doors a member reaches without an object-level grant for + * the write they make: `DELETE /comments/reactions/:id` (remove your own + * reaction), `PUT /comments/:id/resolution` (resolve or reopen a thread you + * can read) and `DELETE /comments/:id` (remove a comment you wrote). A + * self-hosted kernel serves them already: plugin-audit mounts them on the + * kernel's `http.server` (`mountCommentDoors`). A hosted tenant kernel owns no + * socket and therefore no `http.server`, so on that shape every unreact, + * resolve and own-comment delete answered the host's unmatched + * `404 ENDPOINT_NOT_FOUND` (#36469). This domain is the hosted door (ruling A + * on #22438, applied to this member of the class): it forwards the request to + * the request kernel's `comments` slot — the transport-neutral + * `ICommentDoorsService.handleCommentDoor(request)` member — and returns that + * member's `Response` as it is. The self-hosted mount is untouched and is not + * a caller. + * + * ## Exactly three shapes are claimed + * + * The registry claims `/comments` and everything under it for `PUT` and + * `DELETE`; the handler then claims only the three method and path shapes + * ({@link matchCommentDoorPath}) and answers every other one with the + * dispatcher's ordinary miss (`404 ROUTE_NOT_FOUND`), exactly what it answered + * before this domain existed; the member never runs for one. `GET`, `POST` + * and `PATCH` are never claimed. + * + * ## The request is forwarded, never read + * + * The resolution door reads `{ "resolved": boolean }` from the JSON body. This + * domain reads neither the body nor the parsed `body` the transport hands + * `dispatch()`: the member owns the read, and the request it receives is the + * transport's own (`context.request`). A body the transport had already + * consumed would reach the member empty, so that is answered loudly here as a + * server fault instead. + * + * The member matches the door's own wire path (`/api/v1/comments/…`). A + * request that arrived under another spelling of the same path — the + * environment-scoped `/api/v1/environments/:id/comments/…` — is handed on with + * its URL rewritten to the wire path and its body still unread. + * + * ## The member is the only judge of the caller + * + * No anonymous-deny, no session read, no `ExecutionContext` handed on: the + * member resolves the caller from the request's own credentials, the rule the + * self-hosted mount applies. ⛔ These paths have NO entry on either dispatcher + * preamble gate: they are not on the ADR-0069 auth-gate allow-list, and + * `HttpDispatcher.enforceProjectMembership` does not skip them. The credential + * is the session, so a session that still owes an authentication step, or a + * signed-in caller who is not a member of the request's environment, is + * stopped before the member runs: stricter than the self-hosted mount, never + * looser. + * + * ## The slot is resolved per request, and absence is a typed answer + * + * Read on every request, never recorded (AGENTS.md, "Startup registry + * reads"). An empty `comments` slot (a stack without plugin-audit) or a slot + * whose service has no `handleCommentDoor` answers `501 NOT_IMPLEMENTED`, + * ⛔ never `ENDPOINT_NOT_FOUND`: the route IS mounted, and what is missing is + * the implementation behind it. + */ + +import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types'; +import type { ICommentDoorsService } from '@objectstack/spec/contracts'; +import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js'; +import type { DomainHandlerDeps, DomainRequest, DomainRoute } from '../domain-handler-registry.js'; + +/** The prefix the domain claims (a segment claim, narrowed by the handler). */ +export const COMMENTS_DOMAIN_PREFIX = '/comments'; + +/** The methods the registry claims for the prefix; the handler narrows further. */ +export const COMMENTS_DOMAIN_METHODS = ['PUT', 'DELETE'] as const; + +/** The three door shapes, as dispatcher paths (API prefix stripped), in the mount's order. */ +export const COMMENT_DOOR_PATHS = [ + { method: 'DELETE', path: '/comments/reactions/:id' }, + { method: 'PUT', path: '/comments/:id/resolution' }, + { method: 'DELETE', path: '/comments/:id' }, +] as const; + +/** The wire prefix the doors are mounted under by plugin-audit (its routes are fixed at `/api/v1`). */ +const DOOR_WIRE_PREFIX = '/api/v1'; + +/** The slot the member lives on (`AuditPlugin` registers it). */ +const COMMENTS_SLOT = 'comments'; + +/** + * Is `method path` one of the three comment doors? `path` is the dispatcher's + * clean path; each `:id` matches one non-empty segment. + */ +export function matchCommentDoorPath(method: string, path: string): boolean { + const verb = method.toUpperCase(); + const got = path.split('/'); + return COMMENT_DOOR_PATHS.some((door) => { + if (door.method !== verb) return false; + const want = door.path.split('/'); + return want.length === got.length + && want.every((segment, i) => (segment.startsWith(':') ? got[i].length > 0 : segment === got[i])); + }); +} + +export function createCommentsDomain(deps: DomainHandlerDeps): DomainRoute { + return { + prefix: COMMENTS_DOMAIN_PREFIX, + match: 'segment', + methods: [...COMMENTS_DOMAIN_METHODS], + handler: (req, context) => handleCommentsRequest(deps, req, context), + }; +} + +/** + * The transport's request, addressed at the door's wire path. Handed on as it + * is when it already is; otherwise a copy at the wire path whose body is the + * original's unread stream. + */ +function atWirePath(request: Request, cleanPath: string): Request { + const url = new URL(request.url); + const wirePath = DOOR_WIRE_PREFIX + cleanPath; + if (url.pathname === wirePath) return request; + url.pathname = wirePath; + const init: RequestInit & { duplex?: 'half' } = { + method: request.method, + headers: request.headers, + signal: request.signal, + }; + if (request.body) { + init.body = request.body; + init.duplex = 'half'; + } + return new Request(url, init); +} + +/** + * Forward a comment door request to the request kernel's + * `comments.handleCommentDoor` and return its `Response` untouched. + */ +export async function handleCommentsRequest( + deps: DomainHandlerDeps, + req: DomainRequest, + context: HttpProtocolContext, +): Promise { + // Not one of the three doors: the dispatcher's ordinary miss, the answer + // the path got before this domain existed. + if (!matchCommentDoorPath(req.method, req.path)) return { handled: true, response: deps.routeNotFound(req.path) }; + + const service = await deps.resolveService(context, COMMENTS_SLOT, context.environmentId) as + Pick | undefined; + if (!service) { + return { + handled: true, + response: deps.error( + 'The comment doors are not available: no comments service is registered. ' + + '@objectstack/plugin-audit registers it; compose AuditPlugin on this kernel.', + 501, + ), + }; + } + if (typeof service.handleCommentDoor !== 'function') { + return { + handled: true, + response: deps.error( + 'The comment doors are not available: the registered comments service ' + + 'does not implement handleCommentDoor.', + 501, + ), + }; + } + + const request = context.request as Request; + const logger = deps.logger ?? console; + + if (request?.bodyUsed === true) { + logger?.error?.( + '[comments] the request body was consumed before the /comments domain could forward it: ' + + 'the HTTP transport must hand the dispatcher the request with its body unread; the client was ' + + 'answered 500 rather than the refusal the door would have given', + ); + return { handled: true, response: deps.error(INTERNAL_ERROR_MESSAGE, 500) }; + } + + try { + return { handled: true, result: await service.handleCommentDoor(atWirePath(request, req.path)) }; + } catch (err) { + // As `/webhooks/redeliver`: the member owns every answer it means to + // give, so a throw out of it is unattributable here and its message + // never reaches the client. The original error goes to the server log. + logger?.error?.( + '[comments] the comments service threw while serving a comment door request; the client was answered ' + + 'with a sanitised 500: the message is withheld unconditionally, and this line is where the ' + + 'original error is read', + err instanceof Error ? err : new Error(String(err)), + ); + return { handled: true, response: deps.error(INTERNAL_ERROR_MESSAGE, 500) }; + } +} diff --git a/packages/runtime/src/http-dispatcher.ts b/packages/runtime/src/http-dispatcher.ts index c997ccceda5..7cb31b65008 100644 --- a/packages/runtime/src/http-dispatcher.ts +++ b/packages/runtime/src/http-dispatcher.ts @@ -57,6 +57,7 @@ import { createAutomationDomain, handleAutomationRequest } from './domains/autom import { createAuthDomain, handleAuthRequest } from './domains/auth.js'; import { createApprovalsActDomain, APPROVALS_ACT_ROUTE } from './domains/approvals.js'; import { createWebhooksRedeliverDomain } from './domains/webhooks.js'; +import { createCommentsDomain } from './domains/comments.js'; import { createAiDomain, handleAIRequest } from './domains/ai.js'; import { createActionsDomain, handleActionsRequest } from './domains/actions.js'; import { dispatchActionRequest, type ActionDispatchAnswer, type ActionDispatchRequest, type ActionResumeRequest } from './action-dispatch.js'; @@ -1013,6 +1014,11 @@ export class HttpDispatcher { // `POST /webhooks/redeliver`, forwarded to the `webhooks` slot's // `handleRedeliver`, resolved per request. See `./domains/webhooks.ts`. this.domainRegistry.register(createWebhooksRedeliverDomain(this.domainDeps)); + // The three comment doors for a kernel with no `http.server` (#36469; + // ruling A on #22438): exactly their three method and path shapes, + // forwarded to the `comments` slot's `handleCommentDoor`, resolved per + // request. See `./domains/comments.ts`. + this.domainRegistry.register(createCommentsDomain(this.domainDeps)); this.domainRegistry.register(createAiDomain(this.domainDeps)); this.domainRegistry.register(createActionsDomain(this.domainDeps)); for (const route of createMcpDomains(this.domainDeps)) this.domainRegistry.register(route); diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 995026f9ee5..55c5b257f3c 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -728,6 +728,14 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { route: 'POST /webhooks/redeliver', domain: '/webhooks/redeliver', disposition: 'server-only', note: 'the operator button that sends a finished webhook delivery again. Forwarded with its JSON body UNREAD to the webhooks slot\'s IWebhookService.handleRedeliver, resolved per request (plugin-webhooks registers the slot at kernel:ready, only once its redelivery veto is installed), and the member\'s Response returned as it is: the member judges the caller from the request\'s own credentials through the auth service (401 UNAUTHENTICATED with no signed-in user, exactly as the self-hosted mount answers it), scopes the row to the caller\'s active organization and answers every refusal itself. No preamble-gate exemption: unlike /approvals/act the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never ROUTE_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. POST only: the member does not match the method, so no other method is claimed and the member never runs for one. This is the door for a kernel with no raw app; a self-hosted kernel serves the same path from plugin-webhooks\' raw-app mount, which never passes through the dispatcher. NOT JS-SDK surface: the self-hosted route it bridges has never been, and this door declares no client method. Pinned in `domains/webhooks-redeliver.test.ts`' }, + // ── comment doors (the hosted door) ─────────────────────────────────────── + { route: 'DELETE /comments/reactions/:id', domain: '/comments', disposition: 'server-only', + note: 'the unreact door: a member removes their own comment reaction, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the comments slot\'s ICommentDoorsService.handleCommentDoor, resolved per request (plugin-audit registers the slot in init), and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller (resolved from the request\'s own credentials, 401 with none), every refusal and every answer are the mount\'s. No preamble-gate exemption: the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never ENDPOINT_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. This is the door for a kernel with no http.server (#36469); a self-hosted kernel serves the same path from plugin-audit\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the console\'s comment panel is the consumer, and the SDK gap is acknowledged once, on the mount\'s own ledger rows (plugin-audit comment-reaction-route-ledger.ts / comment-route-ledger.ts). Pinned in `domains/comments.test.ts`' }, + { route: 'PUT /comments/:id/resolution', domain: '/comments', disposition: 'server-only', + note: 'the resolution door: whoever can read a thread (and may post on it) resolves or reopens it, body exactly { resolved: boolean }. Same forwarding, credential, absence and door notes as the unreact row' }, + { route: 'DELETE /comments/:id', domain: '/comments', disposition: 'server-only', + note: 'the own-comment delete door: a member removes a comment they wrote, with no object delete grant. Same forwarding, credential, absence and door notes as the unreact row' }, + // ── ai (dynamic route table, owned by another repo) ─────────────────────── { route: '* /ai/**', domain: '/ai', disposition: 'dynamic', note: 'routes come from service-ai buildAIRoutes() at plugin start — service-ai is a Cloud/EE package in the `cloud` repo, so this repo cannot enumerate them and the dispatcher only proxies. With the service absent the mount stays, so the answer is 501 carrying the shared serviceUnavailableMessage (the sentence discovery reports for the slot), NOT 404 — with two narrower arms: an anonymous caller is refused 401 first, and GET /ai/agents answers 200 with an empty list as a console courtesy. Enumerated on the other side of that boundary: cloud packages/service-ai/src/ai-route-ledger.ts, whose conformance test drives client.ai.* against the table buildAIRoutes() really returns. The client now expresses that table — ai.chat / ai.chatStream / ai.complete / ai.models / ai.conversations.* — but do NOT read a `sdk` disposition into this row: it stays `dynamic` because THIS repo still cannot see the routes. An earlier note here claimed the client "expresses nlq/suggest/insights against the REST AI routes"; that was never verified and was FALSE — nothing has ever mounted those three paths, and both they and the methods calling them are gone' }, From 3dcfddc86e2b41183ee58187ccaff423a9d75dda Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:44:25 +0000 Subject: [PATCH 04/12] test(http-conformance): depend on plugin-audit; route-envelope guard declares the /comments domain Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/qa/http-conformance/package.json | 1 + pnpm-lock.yaml | 3 +++ scripts/check-route-envelope.mjs | 6 ++++++ 3 files changed, 10 insertions(+) diff --git a/packages/qa/http-conformance/package.json b/packages/qa/http-conformance/package.json index 299bcb7abf9..a63da903eef 100644 --- a/packages/qa/http-conformance/package.json +++ b/packages/qa/http-conformance/package.json @@ -20,6 +20,7 @@ "@objectstack/mcp": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/plugin-approvals": "workspace:*", + "@objectstack/plugin-audit": "workspace:*", "@objectstack/plugin-auth": "workspace:*", "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/plugin-webhooks": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 00a2cc23326..b6a7e5340e2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2520,6 +2520,9 @@ importers: '@objectstack/plugin-approvals': specifier: workspace:* version: link:../../plugins/plugin-approvals + '@objectstack/plugin-audit': + specifier: workspace:* + version: link:../../plugins/plugin-audit '@objectstack/plugin-auth': specifier: workspace:* version: link:../../plugins/plugin-auth diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 5b6a842a940..4dbb959988a 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -1120,6 +1120,12 @@ const DISPATCHER_DOMAINS = { // ADR-0131 D6), split out of `security.ts` beside the gate it calls. Every // answer it gives goes through `deps.success` / `deps.error`. 'catalog-activation.ts': { handBuilt: 0 }, + // [#36469] The `/comments` bridge: the comments member's own JSON `Response` + // is handed back as `result` (the `/webhooks/redeliver` shape), and every + // answer the domain makes itself — the ordinary miss for a shape it does not + // serve, the two 501s, the sanitised 500s — goes through `deps.routeNotFound` + // / `deps.error`. + 'comments.ts': { handBuilt: 0 }, 'data.ts': { handBuilt: 0 }, // [#25785] Was 0. Kind 1: the translation bundle is the one `/i18n` face a // browser revalidates. Its `200` must carry `ETag` and `Cache-Control` and From 9b682926adc018f8f1a7871c53dfcf4b74157e38 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:48:37 +0000 Subject: [PATCH 05/12] test: a dispatcher-only kernel serves the comment doors; dogfood ledgers classify the /comments domain The http-conformance boot composes AuditPlugin with and without an http.server and pins byte parity between the two doors, and a typed 501 when the comments service is absent. The authz matrix classifies the new /comments ledger rows; the live-mount parity boot pins them as unexercised because it composes no AuditPlugin. Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- .../dogfood/test/authz-conformance.matrix.ts | 24 +- .../qa/dogfood/test/authz-conformance.test.ts | 2 + .../test/authz-ledger-population.baseline.ts | 4 +- ...e-ledger-live-mount-parity.dogfood.test.ts | 10 + .../hono-comment-doors.conformance.test.ts | 250 ++++++++++++++++++ packages/qa/http-conformance/vitest.config.ts | 8 + packages/runtime/src/route-ledger.ts | 2 +- 7 files changed, 293 insertions(+), 7 deletions(-) create mode 100644 packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts diff --git a/packages/qa/dogfood/test/authz-conformance.matrix.ts b/packages/qa/dogfood/test/authz-conformance.matrix.ts index 4d85b2e7a57..b097113f9b7 100644 --- a/packages/qa/dogfood/test/authz-conformance.matrix.ts +++ b/packages/qa/dogfood/test/authz-conformance.matrix.ts @@ -25,7 +25,7 @@ // dispatcher domain files. // // The population comes from `packages/rest/src/rest-route-ledger.ts` (20 -// families) and `packages/runtime/src/route-ledger.ts` (23 +// families) and `packages/runtime/src/route-ledger.ts` (24 // domains) because those two are enumerated from a RUNNING server and guarded // in both directions by their own conformance tests — so a new family or // domain cannot be silently absent from them, and therefore cannot be silently @@ -76,11 +76,11 @@ // The ledgers supply the POPULATION; the classification stays a reviewed row // here. // -// Of the 41 ledger keys, 17 are classified by rows below (re-derived when the +// Of the 42 ledger keys, 18 are classified by rows below (re-derived when the // `/ui` and `/data` domains arrived classified under ADR-0138 D2's second // slice, after the `forms` family and the `/notifications`, `/keys` and -// `/share-links` domains did under its first, the `/webhooks/redeliver` domain -// did, #22755, `/approvals/act` did, #22576, and `/i18n` left the baseline, +// `/share-links` domains did under its first, the `/comments` domain did, +// #36469, the `/webhooks/redeliver` domain did, #22755, `/approvals/act` did, #22576, and `/i18n` left the baseline, // #22432); the other 24 are enumerated one by one, // dated, and pinned SHRINK-ONLY in `authz-ledger-population.baseline.ts`, // whose MAX note dates every step down from the 34 of 40 it held on the @@ -423,6 +423,22 @@ export const AUTHZ_CONFORMANCE: AuthzPrimitive[] = [ covers: ['dispatcher-domain:route-ledger.ts:/webhooks/redeliver'], note: 'The DISPATCHER domain only: on a self-hosted kernel the same path is served from the raw Hono app and never reaches the dispatcher, which is why the route-ledger row is pinned unobservable on the showcase boot. Unit- and wire-proven, not dogfood-proven: plugin-webhooks webhook-redeliver-member.test.ts drives the member on a real kernel, messaging service and outbox (every refusal the contract declares, the tenant scope, the veto, byte parity with the mount); runtime domains/webhooks-redeliver.test.ts pins the domain on the real HttpDispatcher (the request forwarded unread, POST alone claimed, 501 for an absent slot or member, the slot read per request, a signed-in non-member and a gated session stopped before the member while a member of the environment and an anonymous caller reach it); http-conformance hono-webhooks-redeliver.conformance.test.ts drives the real plugin through createHonoApp and the self-hosted mount, where a replay lands in the outbox and every refusal, anonymous first, answers the same bytes at both doors.' }, + // #36469 — the `/comments` dispatcher domain (ruling A on #22438, applied to + // the comment doors). As `webhook-redeliver-session`, the credential IS the + // session: the member resolves the caller from the request's own + // credentials, and the dispatcher's two preamble gates apply unexempted. + // ⛔ Ids stay in this comment, out of the row's strings. + // + // Not HIGH_RISK: each door writes one row the caller owns or may resolve, + // after reading it AS THE CALLER (object grant, organization wall, the + // comment read gate), so it is no sibling read path around a data gate. Its + // proofs are the plugin-audit and plugin-security door suites and the + // two-door wire suite, none of which lives in this directory. + { id: 'comment-doors-session', summary: 'Comment doors (`DELETE /comments/reactions/:id`, `PUT /comments/:id/resolution`, `DELETE /comments/:id`) — a signed-in member removes their own reaction, resolves or reopens a thread they can read and may post on, and removes a comment they wrote with no reply under it; a row the caller cannot read answers as unknown, another member\'s row is refused 403, and an anonymous caller is refused 401 by the door itself, exactly as the self-hosted mount refuses it', state: 'enforced', + enforcement: 'core/security/own-row-delete-routes.ts (the unreact and own-comment delete doors) and plugin-audit/comment-routes.ts (the resolution door) — the caller resolved from the request\'s own credentials (ownRowDeleteCallerResolver: no signed-in user 401, a held sign-in 403), the row read AS THE CALLER (object grant, organization wall, comment read gate; unreadable = unknown 404), the owner column checked (403 PERMISSION_DENIED) or the posting gate asked (canWriteObject insert on sys_comment), then a system write attributed to the caller; reached through ICommentDoorsService.handleCommentDoor by runtime/domains/comments.ts, which claims exactly the three method and path shapes, forwards the transport\'s request UNREAD, resolves the slot per request and adds no credential of its own (an absent slot or member is a typed 501, never a route miss). The two dispatcher preamble gates apply with NO exemption: core/security/auth-gate.ts ALLOW_ROUTES does not list the paths and runtime/http-dispatcher.ts enforceProjectMembership does not skip them. The member runs the very registration the self-hosted mount runs (plugin-audit comment-doors-member.ts over registerCommentDoors in audit-plugin.ts)', + covers: ['dispatcher-domain:route-ledger.ts:/comments'], + note: 'The DISPATCHER domain only: on a self-hosted kernel the same paths are served from plugin-audit\'s mount on the kernel\'s http.server and never reach the dispatcher. Unit- and wire-proven, not dogfood-proven: runtime domains/comments.test.ts pins the domain on the real HttpDispatcher (the three shapes forwarded unread, every other method and path the ordinary miss, 501 for an absent slot or member, the slot read per request, the environment-scoped spelling forwarded at the wire path, a signed-in non-member and a gated session stopped before the member); http-conformance hono-comment-doors.conformance.test.ts drives the real AuditPlugin through createHonoApp on a kernel with no http.server (unreact, resolve and reopen, own-comment delete land in the store) and answers the anonymous refusal and refused bodies with the same bytes as the self-hosted mount; plugin-security comment-doors.integration.test.ts and comment-reaction-unreact-door.integration.test.ts hold the doors\' grants on the real stack.' }, + // ── ADR-0138 D2 — THE CLOSED LIST OF DOORS (card E2) ───────────────────── // // "An unauthenticated request is served by exactly these six door classes"; diff --git a/packages/qa/dogfood/test/authz-conformance.test.ts b/packages/qa/dogfood/test/authz-conformance.test.ts index fe20e614c4f..8a0f9e0445a 100644 --- a/packages/qa/dogfood/test/authz-conformance.test.ts +++ b/packages/qa/dogfood/test/authz-conformance.test.ts @@ -1084,6 +1084,8 @@ describe('the ledger-sourced population and its baseline bite', () => { // [#22576] classified by `approval-action-token`. 'dispatcher-domain:route-ledger.ts:/approvals/act', 'dispatcher-domain:route-ledger.ts:/automation', + // [#36469] classified by `comment-doors-session`. + 'dispatcher-domain:route-ledger.ts:/comments', // [ADR-0138 D2, second slice] classified by `anonymous-deny-data`. 'dispatcher-domain:route-ledger.ts:/data', // [#22432] classified by `anonymous-deny-i18n`. diff --git a/packages/qa/dogfood/test/authz-ledger-population.baseline.ts b/packages/qa/dogfood/test/authz-ledger-population.baseline.ts index 99dc1d3af3d..9deac778c69 100644 --- a/packages/qa/dogfood/test/authz-ledger-population.baseline.ts +++ b/packages/qa/dogfood/test/authz-ledger-population.baseline.ts @@ -100,8 +100,8 @@ export const LEDGER_POPULATION_BASELINE: readonly string[] = [ // `/keys` and `/share-links` (ADR-0138 D2: each domain's anonymous decision // moved to its first statement), and `/ui` and `/data` (ADR-0138 D2's second // slice: each domain's anonymous decision became its first statement). - // `/approvals/act` and `/webhooks/redeliver` were never enumerated here: they - // arrived classified. The other 9 domains are here. + // `/approvals/act`, `/webhooks/redeliver` and `/comments` (#36469) were + // never enumerated here: they arrived classified. The other 9 domains are here. 'dispatcher-domain:route-ledger.ts:/.well-known/objectstack', 'dispatcher-domain:route-ledger.ts:/ai', 'dispatcher-domain:route-ledger.ts:/apps', diff --git a/packages/qa/dogfood/test/route-ledger-live-mount-parity.dogfood.test.ts b/packages/qa/dogfood/test/route-ledger-live-mount-parity.dogfood.test.ts index f76750d2631..3a3ca60ba47 100644 --- a/packages/qa/dogfood/test/route-ledger-live-mount-parity.dogfood.test.ts +++ b/packages/qa/dogfood/test/route-ledger-live-mount-parity.dogfood.test.ts @@ -177,6 +177,16 @@ const UNEXERCISED_BY_THIS_BOOT: Record = { // `rawApp.post()` on the Hono app — never through the port. 'POST /api/v1/webhooks/redeliver': 'self-hosted, plugin-webhooks mounts the redeliver door with rawApp.post() directly on Hono, so it never passes through the IHttpServer port; the dispatcher domain this row ledgers serves only a kernel with no raw app. Both doors are driven, on the real plugin, by packages/qa/http-conformance/src/hono-webhooks-redeliver.conformance.test.ts', + // [#36469] Two doors, one path, for the three comment doors. These rows + // ledger the DISPATCHER's `/comments` domain, the door for a kernel with NO + // `http.server`. Self-hosted, plugin-audit mounts the same paths on the + // port — but this boot composes no AuditPlugin, so nothing answers them here. + 'DELETE /api/v1/comments/reactions/:id': + 'self-hosted, plugin-audit mounts the comment doors on the kernel\'s http.server, and this boot composes no AuditPlugin, so nothing mounts the path; the dispatcher domain this row ledgers serves only a kernel with no http.server and mounts no route here. Both doors are driven, on the real plugin, by packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts', + 'PUT /api/v1/comments/:id/resolution': + 'self-hosted, plugin-audit mounts the comment doors on the kernel\'s http.server, and this boot composes no AuditPlugin, so nothing mounts the path; the dispatcher domain this row ledgers serves only a kernel with no http.server and mounts no route here. Both doors are driven, on the real plugin, by packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts', + 'DELETE /api/v1/comments/:id': + 'self-hosted, plugin-audit mounts the comment doors on the kernel\'s http.server, and this boot composes no AuditPlugin, so nothing mounts the path; the dispatcher domain this row ledgers serves only a kernel with no http.server and mounts no route here. Both doors are driven, on the real plugin, by packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts', // [#22773] Two doors, one path, a third time. This row ledgers the inbound // hook as the DISPATCHER's `/automation` domain serves it, the door for a // kernel with NO raw app. Self-hosted, `@objectstack/trigger-api`'s 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 new file mode 100644 index 00000000000..e4a44c6faee --- /dev/null +++ b/packages/qa/http-conformance/src/hono-comment-doors.conformance.test.ts @@ -0,0 +1,250 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36469] The three comment doors on the hosted shape: `createHonoApp` over a + * kernel with NO `http.server` (a hosted tenant kernel owns no socket), the + * REAL `AuditPlugin` over a real store. + * + * Before the `/comments` dispatcher domain and the `comments` slot existed, + * every request below answered the transport's unmatched + * `404 ENDPOINT_NOT_FOUND` on this shape: the doors were mounted only on the + * kernel's own `http.server`, which this kernel does not have. That is the + * card's measured body, and the first pin here asserts it is gone, door by + * door. + * + * What this pins: + * 1. on the hosted shape, a member removes their own reaction, resolves and + * reopens a thread, and removes their own comment, each answered by the + * door and each landing in the store; + * 2. the two doors answer the same request with the same bytes — the + * 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. + * + * 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 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 type { IHttpServer } from '@objectstack/spec/contracts'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const PREFIX = '/api/v1'; +const COMMENT = 'sys_comment'; +const REACTION = 'sys_comment_reaction'; +const BOARD = 'cdh_board'; +/** The header the test auth service reads the signed-in user from. */ +const SIGNED_IN_AS = 'x-test-signed-in-as'; +const ALICE = 'usr_alice'; +const SYSTEM = { isSystem: true } as const; + +const board = { name: BOARD, label: 'Board', fields: { name: { name: 'name', label: 'Name', type: 'text' as const } } }; + +/** An auth service whose in-process session read names the user the request names. */ +class TestAuth implements Plugin { + name = 'test.comment-doors-auth'; + version = '1.0.0'; + type = 'standard' as const; + async init(ctx: PluginContext): Promise { + ctx.registerService('auth', { + api: { + async getSession(input: { headers: Headers }) { + const userId = input.headers.get(SIGNED_IN_AS); + if (!userId) return null; + return { user: { id: userId, email: `${userId}@acme.test` }, session: { id: `ses_${userId}`, userId } }; + }, + }, + }); + } +} + +const liveKernels: ObjectKernel[] = []; +const liveDrivers: SqliteWasmDriver[] = []; +afterEach(async () => { + while (liveKernels.length) { + const kernel = liveKernels.pop(); + await Promise.race([kernel?.shutdown(), new Promise((resolve) => setTimeout(resolve, 10_000))]); + } + while (liveDrivers.length) { + try { await liveDrivers.pop()?.disconnect(); } catch { /* already closed */ } + } +}); + +/** + * One kernel. `selfHosted` gives it the real Hono server, so plugin-audit + * mounts the doors on it; without it the kernel has no `http.server`, the + * hosted shape. `audit: false` leaves the `comments` slot empty. + */ +async function bootKernel(opts: { selfHosted: boolean; audit?: boolean }) { + const kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + liveKernels.push(kernel); + await kernel.use(new ObjectQLPlugin()); + if (opts.selfHosted) await kernel.use(new HonoServerPlugin({ port: 0, cors: false })); + await kernel.use(new TestAuth()); + if (opts.audit !== false) await kernel.use(new AuditPlugin()); + await kernel.bootstrap(); + + const objectql = kernel.getService('objectql'); + const driver = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + liveDrivers.push(driver); + (objectql as any).registerDriver(driver, true); + objectql.registry.registerObject(board as any, 'comment-doors-test', 'comment-doors-test'); + await (objectql as any).syncSchemas(); + await installDefaultOrganization(objectql as any); + + /** A thread on a board, with one top-level comment Alice wrote and one reaction of hers on it. */ + const seed = async () => { + const row: any = await objectql.insert(BOARD, { name: 'board' }, { context: SYSTEM } as any); + const comment: any = await objectql.insert( + COMMENT, + { thread_id: `${BOARD}:${row.id}`, author_id: ALICE, body: 'hello' }, + { context: { ...SYSTEM, userId: ALICE } } as any, + ); + const reaction: any = await objectql.insert( + REACTION, + { comment_id: String(comment.id), emoji: '👍', user_id: ALICE }, + { context: { ...SYSTEM, userId: ALICE } } as any, + ); + return { commentId: String(comment.id), reactionId: String(reaction.id) }; + }; + const stored = (object: string, id: string) => objectql.findOne(object, { where: { id }, context: SYSTEM } as any); + return { kernel, seed, stored }; +} + +/** The hosted door: `createHonoApp` over a kernel with no `http.server`. */ +async function hostedDoor(opts: { audit?: boolean } = {}) { + const booted = await bootKernel({ selfHosted: false, audit: opts.audit }); + let server: unknown; + try { server = booted.kernel.getService('http.server'); } catch { server = undefined; } + expect(server, 'the hosted shape owns no socket').toBeUndefined(); + const app = createHonoApp({ kernel: booted.kernel as any, prefix: PREFIX, cors: false }); + return { ...booted, send: (path: string, init?: RequestInit) => app.request(`http://tenant.example${path}`, init) }; +} + +/** The self-hosted door: plugin-audit's own mount on the kernel's `http.server`, over a real socket. */ +async function selfHostedDoor() { + const booted = await bootKernel({ selfHosted: true }); + const server = booted.kernel.getService('http.server'); + const base = `http://127.0.0.1:${server.getPort!()}`; + return { ...booted, send: (path: string, init?: RequestInit) => fetch(`${base}${path}`, init) }; +} + +const as = (userId: string | undefined, init: RequestInit = {}): RequestInit => ({ + ...init, + headers: { 'content-type': 'application/json', ...(userId ? { [SIGNED_IN_AS]: userId } : {}) }, +}); + +/** Headers a transport adds or drops on its own, independent of the route. */ +const TRANSPORT_HEADERS = new Set(['date', 'connection', 'keep-alive', 'content-length', 'transfer-encoding', 'content-encoding', 'vary']); +async function snapshot(res: Response) { + return { + status: res.status, + headers: [...res.headers.entries()].filter(([k]) => !TRANSPORT_HEADERS.has(k)), + body: await res.text(), + }; +} + +describe('[#36469] the comment doors answer on the hosted shape (createHonoApp, no http.server, real AuditPlugin)', () => { + it('no door answers the unmatched ENDPOINT_NOT_FOUND any more', async () => { + const door = await hostedDoor(); + const { commentId, reactionId } = await door.seed(); + const requests: Array<[string, RequestInit]> = [ + [`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' })], + [`${PREFIX}/comments/${commentId}/resolution`, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: true }) })], + [`${PREFIX}/comments/${commentId}`, as(undefined, { method: 'DELETE' })], + ]; + for (const [path, init] of requests) { + const res = await door.send(path, init); + const body = await res.text(); + expect(body, `${init.method} ${path}`).not.toContain('ENDPOINT_NOT_FOUND'); + expect(res.status, `${init.method} ${path}: ${body}`).not.toBe(404); + } + }); + + it('a member removes their own reaction: 200, and the row is gone', async () => { + const door = await hostedDoor(); + const { reactionId } = await door.seed(); + + const res = await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' })); + + 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: 200 each, and the stored flag follows', async () => { + const door = await hostedDoor(); + const { commentId } = await door.seed(); + const path = `${PREFIX}/comments/${commentId}/resolution`; + + const resolved = await door.send(path, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: true }) })); + expect(resolved.status, await resolved.clone().text()).toBe(200); + expect((await resolved.json()).data).toMatchObject({ id: commentId, is_resolved: true, resolved_by: ALICE }); + expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeTruthy(); + + const reopened = await door.send(path, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: false }) })); + expect(reopened.status, await reopened.clone().text()).toBe(200); + expect((await reopened.json()).data).toMatchObject({ id: commentId, is_resolved: false }); + expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeFalsy(); + }); + + it('a member removes their own comment: 200, and the row is gone', async () => { + const door = await hostedDoor(); + const { commentId, reactionId } = await door.seed(); + // The comment's own reaction first, so nothing hangs under it but what the door reads. + await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' })); + + const res = await door.send(`${PREFIX}/comments/${commentId}`, as(ALICE, { method: 'DELETE' })); + + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toEqual({ success: true, data: { id: commentId, deleted: true } }); + expect(await door.stored(COMMENT, commentId)).toBeNull(); + }); +}); + +describe('[#36469] both doors answer the same request with the same bytes', () => { + it('the anonymous refusal and the refused body are byte-identical at the mount and at the hosted door', async () => { + const hosted = await hostedDoor(); + const selfHosted = await selfHostedDoor(); + const cases: Array<[label: string, path: string, init: RequestInit]> = [ + ['anonymous unreact', `${PREFIX}/comments/reactions/rx_missing`, as(undefined, { method: 'DELETE' })], + ['anonymous resolve', `${PREFIX}/comments/c_missing/resolution`, as(undefined, { method: 'PUT', body: '{"resolved":true}' })], + ['anonymous own delete', `${PREFIX}/comments/c_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 viaHosted = await snapshot(await hosted.send(path, init)); + const viaMount = await snapshot(await selfHosted.send(path, init)); + expect(viaHosted.status, label).not.toBe(404); + expect(viaHosted, label).toEqual(viaMount); + } + }); +}); + +describe('[#36469] a hosted kernel without plugin-audit answers a typed 501, never a route miss', () => { + it('each door: 501 NOT_IMPLEMENTED naming the plugin', async () => { + const door = await hostedDoor({ audit: false }); + const requests: Array<[string, RequestInit]> = [ + [`${PREFIX}/comments/reactions/rx_1`, as(ALICE, { method: 'DELETE' })], + [`${PREFIX}/comments/c_1/resolution`, as(ALICE, { method: 'PUT', body: '{"resolved":true}' })], + [`${PREFIX}/comments/c_1`, as(ALICE, { method: 'DELETE' })], + ]; + for (const [path, init] of requests) { + const res = await door.send(path, init); + const body = await res.json() as any; + expect(res.status, `${init.method} ${path}`).toBe(501); + expect(body.error.code).toBe('NOT_IMPLEMENTED'); + expect(body.error.message).toContain('@objectstack/plugin-audit'); + } + }); +}); diff --git a/packages/qa/http-conformance/vitest.config.ts b/packages/qa/http-conformance/vitest.config.ts index 3846c8b1a29..badfc4f497d 100644 --- a/packages/qa/http-conformance/vitest.config.ts +++ b/packages/qa/http-conformance/vitest.config.ts @@ -47,6 +47,14 @@ export default defineConfig({ find: /^@objectstack\/service-messaging$/, replacement: path.resolve(__dirname, '../../services/service-messaging/src/index.ts'), }, + // `hono-comment-doors.conformance.test.ts` boots the REAL AuditPlugin on + // both of its doors — the self-hosted mount on `http.server` and the + // `handleCommentDoor` member behind the dispatcher's `/comments` domain — + // so its verdict about either is about this checkout's plugin source. + { + find: /^@objectstack\/plugin-audit$/, + replacement: path.resolve(__dirname, '../../plugins/plugin-audit/src/index.ts'), + }, // `cors-doors.conformance.test.ts` reads `AuthManager`'s trusted-origin // merge off a REAL better-auth instance — one of the CORS doors it holds // to one answer — so that verdict is about this checkout's auth source. diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 55c5b257f3c..3c207e03e44 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -730,7 +730,7 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ // ── comment doors (the hosted door) ─────────────────────────────────────── { route: 'DELETE /comments/reactions/:id', domain: '/comments', disposition: 'server-only', - note: 'the unreact door: a member removes their own comment reaction, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the comments slot\'s ICommentDoorsService.handleCommentDoor, resolved per request (plugin-audit registers the slot in init), and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller (resolved from the request\'s own credentials, 401 with none), every refusal and every answer are the mount\'s. No preamble-gate exemption: the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never ENDPOINT_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. This is the door for a kernel with no http.server (#36469); a self-hosted kernel serves the same path from plugin-audit\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the console\'s comment panel is the consumer, and the SDK gap is acknowledged once, on the mount\'s own ledger rows (plugin-audit comment-reaction-route-ledger.ts / comment-route-ledger.ts). Pinned in `domains/comments.test.ts`' }, + note: 'the unreact door: a member removes their own comment reaction, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the comments slot\'s ICommentDoorsService.handleCommentDoor, resolved per request (plugin-audit registers the slot in init), and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller (resolved from the request\'s own credentials, 401 with none), every refusal and every answer are the mount\'s. No preamble-gate exemption: the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never ENDPOINT_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from plugin-audit\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the console\'s comment panel is the consumer, and the SDK gap is acknowledged once, on the mount\'s own ledger rows (plugin-audit comment-reaction-route-ledger.ts / comment-route-ledger.ts). Pinned in `domains/comments.test.ts`' }, { route: 'PUT /comments/:id/resolution', domain: '/comments', disposition: 'server-only', note: 'the resolution door: whoever can read a thread (and may post on it) resolves or reopens it, body exactly { resolved: boolean }. Same forwarding, credential, absence and door notes as the unreact row' }, { route: 'DELETE /comments/:id', domain: '/comments', disposition: 'server-only', From 5d87ca07b52ceca6b88fe2c25470f2ffba424f11 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:48:54 +0000 Subject: [PATCH 06/12] chore(changeset): the comment doors on a kernel with no http.server Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- .changeset/36469-comment-doors-hosted.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/36469-comment-doors-hosted.md diff --git a/.changeset/36469-comment-doors-hosted.md b/.changeset/36469-comment-doors-hosted.md new file mode 100644 index 00000000000..5455ec49694 --- /dev/null +++ b/.changeset/36469-comment-doors-hosted.md @@ -0,0 +1,16 @@ +--- +'@objectstack/spec': patch +'@objectstack/runtime': patch +'@objectstack/plugin-audit': patch +--- + +fix(comments): unreact, resolve and own-comment delete work on a kernel with no `http.server` (a hosted tenant kernel) instead of answering `404 ENDPOINT_NOT_FOUND` + +Clause-②: yes (widening) +Metadata-protocol: none + +The three comment doors, `DELETE /api/v1/comments/reactions/:id`, `PUT /api/v1/comments/:id/resolution` and `DELETE /api/v1/comments/:id`, were mounted by `AuditPlugin` only on the kernel's `http.server`. A hosted tenant kernel owns no socket and registers no `http.server`, so the host answered each of them with its unmatched `404 ENDPOINT_NOT_FOUND`, and removing a reaction, resolving or reopening a thread and deleting your own comment failed there. + +- `@objectstack/spec/contracts` declares `ICommentDoorsService` with one optional, transport-neutral member, `handleCommentDoor(request: Request): Promise`, and types the `comments` service slot with it (`ServiceSlotContracts.comments`). A service without the member still satisfies the contract. +- `AuditPlugin` registers the `comments` service with that member. It runs the same registrars over the same dependencies the `http.server` mount runs, on a private route table that never listens, so every answer is the mount's own. The `http.server` mount is unchanged, and no path is mounted twice. +- The runtime dispatcher gains a `/comments` domain that claims exactly the three method and path shapes and forwards the request, body unread, to the request kernel's `comments` service. Every other `/comments` shape keeps the dispatcher's `404 ROUTE_NOT_FOUND`. With no `comments` service, or one without `handleCommentDoor`, the doors answer `501 NOT_IMPLEMENTED` naming `@objectstack/plugin-audit`. The doors stay behind the dispatcher's authentication and project-membership gates. From d994a87cca1c9dcc232d6166cb7bcbd0067032d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:12:56 +0000 Subject: [PATCH 07/12] fix(runtime): the /comments door table keys its shapes as pattern, so the affected-docs walk does not read it as a spec API declaration Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/runtime/src/domains/comments.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/runtime/src/domains/comments.ts b/packages/runtime/src/domains/comments.ts index 487567937b0..a43e4c8c464 100644 --- a/packages/runtime/src/domains/comments.ts +++ b/packages/runtime/src/domains/comments.ts @@ -80,9 +80,9 @@ export const COMMENTS_DOMAIN_METHODS = ['PUT', 'DELETE'] as const; /** The three door shapes, as dispatcher paths (API prefix stripped), in the mount's order. */ export const COMMENT_DOOR_PATHS = [ - { method: 'DELETE', path: '/comments/reactions/:id' }, - { method: 'PUT', path: '/comments/:id/resolution' }, - { method: 'DELETE', path: '/comments/:id' }, + { method: 'DELETE', pattern: '/comments/reactions/:id' }, + { method: 'PUT', pattern: '/comments/:id/resolution' }, + { method: 'DELETE', pattern: '/comments/:id' }, ] as const; /** The wire prefix the doors are mounted under by plugin-audit (its routes are fixed at `/api/v1`). */ @@ -100,7 +100,7 @@ export function matchCommentDoorPath(method: string, path: string): boolean { const got = path.split('/'); return COMMENT_DOOR_PATHS.some((door) => { if (door.method !== verb) return false; - const want = door.path.split('/'); + const want = door.pattern.split('/'); return want.length === got.length && want.every((segment, i) => (segment.startsWith(':') ? got[i].length > 0 : segment === got[i])); }); From 5e2970dc425df81215c02be4b15528e97e9d27b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 16:50:32 +0000 Subject: [PATCH 08/12] test: route-ledger census 153, plugin-audit aliases plugin-hono-server to source, comments domain test pays the metadata load at collection, conformance findOne options typed Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/plugins/plugin-audit/vitest.config.ts | 7 +++++++ .../src/hono-comment-doors.conformance.test.ts | 2 +- packages/runtime/src/domains/comments.test.ts | 4 ++++ packages/runtime/src/route-ledger.ts | 2 +- 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-audit/vitest.config.ts b/packages/plugins/plugin-audit/vitest.config.ts index c19351f7383..b7401b5bd93 100644 --- a/packages/plugins/plugin-audit/vitest.config.ts +++ b/packages/plugins/plugin-audit/vitest.config.ts @@ -40,6 +40,13 @@ export default defineConfig({ // One rule for all namespaces cannot go stale that way. alias: [ { find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') }, + // The never-listening route table `comment-doors-member.ts` serves the + // comment doors on for a kernel with no `http.server`: to source, so the + // suite's verdict is about the checkout (`pnpm check:test-source-alias`). + { + find: /^@objectstack\/plugin-hono-server$/, + replacement: path.resolve(__dirname, '../plugin-hono-server/src/index.ts'), + }, // [#16829] The real driver `read-audit-view-instant-preservation.integration.test.ts` // boots. That file exists to judge the ledger row AFTER the real // `sys_stamp_audit_insert` hook and a real driver have both run, so 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 e4a44c6faee..db917986c32 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 @@ -116,7 +116,7 @@ async function bootKernel(opts: { selfHosted: boolean; audit?: boolean }) { ); return { commentId: String(comment.id), reactionId: String(reaction.id) }; }; - const stored = (object: string, id: string) => objectql.findOne(object, { where: { id }, context: SYSTEM } as any); + const stored = (object: string, id: string) => objectql.findOne(object, { where: { id }, context: { ...SYSTEM } }); return { kernel, seed, stored }; } diff --git a/packages/runtime/src/domains/comments.test.ts b/packages/runtime/src/domains/comments.test.ts index c84ad6ef66c..b0ce5012a0a 100644 --- a/packages/runtime/src/domains/comments.test.ts +++ b/packages/runtime/src/domains/comments.test.ts @@ -32,6 +32,10 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid during collection, not inside a case's clock: the dispatcher reaches +// `standalone-stack.ts`, whose dynamic `@objectstack/metadata` import would +// otherwise load inside the first case that gets that far (check:test-source-alias). +import '@objectstack/metadata'; import { HttpDispatcher } from '../http-dispatcher.js'; import type { HttpProtocolContext, KernelResolver } from '../http-dispatcher.js'; diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 3c207e03e44..b07ccc9aef7 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -301,7 +301,7 @@ export const NON_DISPATCH_MOUNT_PREFIXES = [ /** * The ledger. * - * CENSUS (generated): this list holds 150 rows. + * CENSUS (generated): this list holds 153 rows. * * ⛔ THAT NUMBER IS WRITTEN BY A TOOL — never by hand. * `pnpm check:route-ledger-census` counts the rows below and fails when the two From 2f6e249adf3f433e998076dbbdbbabfdbcf5aeb3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:19:32 +0000 Subject: [PATCH 09/12] test(http-conformance): the comment doors boot seeds the identity rows the door's caller resolution reads Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- .../hono-comment-doors.conformance.test.ts | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) 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 db917986c32..2b04265aac8 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 @@ -35,7 +35,7 @@ import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import { AuditPlugin } from '@objectstack/plugin-audit'; import { createHonoApp } from '@objectstack/hono'; import type { IHttpServer } from '@objectstack/spec/contracts'; -import { installDefaultOrganization } from './default-organization.testkit.js'; +import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-organization.testkit.js'; const PREFIX = '/api/v1'; const COMMENT = 'sys_comment'; @@ -46,6 +46,35 @@ const SIGNED_IN_AS = 'x-test-signed-in-as'; const ALICE = 'usr_alice'; const SYSTEM = { isSystem: true } as const; +/** + * The identity rows the door's caller resolution reads on every signed-in + * request (`resolve-authz-context.ts`: membership, positions, permission + * sets). A deployment's auth and security plugins register them; this kernel + * stubs `auth`, so they are spelled here with only the columns that resolver + * reads, the precedent `conformance.integration.test.ts` set. Registered + * before the schema sync, so their tables exist and Alice's membership reads. + */ +const text = (name: string) => ({ name, type: 'text' as const }); +const identityObjects = [ + { owner: '@objectstack/plugin-auth', def: { name: 'sys_user', label: 'User', fields: { id: { ...text('id'), primaryKey: true }, email: text('email') } } }, + { + owner: '@objectstack/plugin-auth', + def: { name: 'sys_member', label: 'Member', fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') } }, + }, + { + owner: '@objectstack/plugin-security', + def: { name: 'sys_user_position', label: 'User Position', fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), position: text('position'), organization_id: text('organization_id') } }, + }, + { + owner: '@objectstack/plugin-security', + def: { name: 'sys_user_permission_set', label: 'User Permission Set', fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), permission_set_id: text('permission_set_id'), organization_id: text('organization_id') } }, + }, + { + owner: '@objectstack/plugin-security', + def: { name: 'sys_position', label: 'Position', fields: { id: { ...text('id'), primaryKey: true }, name: text('name'), active: { name: 'active', type: 'boolean' as const }, organization_id: text('organization_id') } }, + }, +] as const; + const board = { name: BOARD, label: 'Board', fields: { name: { name: 'name', label: 'Name', type: 'text' as const } } }; /** An auth service whose in-process session read names the user the request names. */ @@ -59,7 +88,7 @@ class TestAuth implements Plugin { async getSession(input: { headers: Headers }) { const userId = input.headers.get(SIGNED_IN_AS); if (!userId) return null; - return { user: { id: userId, email: `${userId}@acme.test` }, session: { id: `ses_${userId}`, userId } }; + return { user: { id: userId, email: `${userId}@acme.test` }, session: { id: `ses_${userId}`, userId, activeOrganizationId: DEFAULT_ORGANIZATION_ID } }; }, }, }); @@ -98,8 +127,12 @@ async function bootKernel(opts: { selfHosted: boolean; audit?: boolean }) { liveDrivers.push(driver); (objectql as any).registerDriver(driver, true); objectql.registry.registerObject(board as any, 'comment-doors-test', 'comment-doors-test'); + for (const o of identityObjects) objectql.registry.registerObject(o.def as never, o.owner); await (objectql as any).syncSchemas(); await installDefaultOrganization(objectql as any); + // Alice is a current member of the organization her session names. + await objectql.insert('sys_user', { id: ALICE, email: `${ALICE}@acme.test` }, { context: SYSTEM } as any); + await objectql.insert('sys_member', { user_id: ALICE, organization_id: DEFAULT_ORGANIZATION_ID, role: 'member' }, { context: SYSTEM } as any); /** A thread on a board, with one top-level comment Alice wrote and one reaction of hers on it. */ const seed = async () => { From 6b916dcfcb9f31150b539ef9cc22497516689f28 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:35:34 +0000 Subject: [PATCH 10/12] test(http-conformance): type the resolution door's answer reads Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- .../src/hono-comment-doors.conformance.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 2b04265aac8..fea910ee48c 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 @@ -221,12 +221,12 @@ describe('[#36469] the comment doors answer on the hosted shape (createHonoApp, const resolved = await door.send(path, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: true }) })); expect(resolved.status, await resolved.clone().text()).toBe(200); - expect((await resolved.json()).data).toMatchObject({ id: commentId, is_resolved: true, resolved_by: ALICE }); + expect(((await resolved.json()) as { data: unknown }).data).toMatchObject({ id: commentId, is_resolved: true, resolved_by: ALICE }); expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeTruthy(); const reopened = await door.send(path, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: false }) })); expect(reopened.status, await reopened.clone().text()).toBe(200); - expect((await reopened.json()).data).toMatchObject({ id: commentId, is_resolved: false }); + expect(((await reopened.json()) as { data: unknown }).data).toMatchObject({ id: commentId, is_resolved: false }); expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeFalsy(); }); From 604b45ec31de0fde33a7dff4d916eb0762dbdfa7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 21:02:54 +0000 Subject: [PATCH 11/12] docs(comments): the hosted miss before the /comments domain was the dispatcher's ROUTE_NOT_FOUND; the card's ENDPOINT_NOT_FOUND reading is unexplained Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- .changeset/36469-comment-doors-hosted.md | 6 +++--- .../plugin-audit/src/comment-doors-member.ts | 9 ++++++--- .../src/hono-comment-doors.conformance.test.ts | 15 +++++++++------ packages/runtime/src/domains/comments.ts | 14 ++++++++++---- packages/runtime/src/route-ledger.ts | 2 +- .../spec/src/contracts/comment-doors-service.ts | 3 ++- 6 files changed, 31 insertions(+), 18 deletions(-) diff --git a/.changeset/36469-comment-doors-hosted.md b/.changeset/36469-comment-doors-hosted.md index 5455ec49694..b059a407c14 100644 --- a/.changeset/36469-comment-doors-hosted.md +++ b/.changeset/36469-comment-doors-hosted.md @@ -4,13 +4,13 @@ '@objectstack/plugin-audit': patch --- -fix(comments): unreact, resolve and own-comment delete work on a kernel with no `http.server` (a hosted tenant kernel) instead of answering `404 ENDPOINT_NOT_FOUND` +fix(comments): unreact, resolve and own-comment delete work on a kernel with no `http.server` (a hosted tenant kernel) instead of answering 404 Clause-②: yes (widening) Metadata-protocol: none -The three comment doors, `DELETE /api/v1/comments/reactions/:id`, `PUT /api/v1/comments/:id/resolution` and `DELETE /api/v1/comments/:id`, were mounted by `AuditPlugin` only on the kernel's `http.server`. A hosted tenant kernel owns no socket and registers no `http.server`, so the host answered each of them with its unmatched `404 ENDPOINT_NOT_FOUND`, and removing a reaction, resolving or reopening a thread and deleting your own comment failed there. +The three comment doors, `DELETE /api/v1/comments/reactions/:id`, `PUT /api/v1/comments/:id/resolution` and `DELETE /api/v1/comments/:id`, were mounted by `AuditPlugin` only on the kernel's `http.server`. A hosted tenant kernel owns no socket and registers no `http.server`, so the host's `createHonoApp` catch-all handed each of them to the runtime dispatcher, which had no domain for them and answered `404 ROUTE_NOT_FOUND`, and removing a reaction, resolving or reopening a thread and deleting your own comment failed there. - `@objectstack/spec/contracts` declares `ICommentDoorsService` with one optional, transport-neutral member, `handleCommentDoor(request: Request): Promise`, and types the `comments` service slot with it (`ServiceSlotContracts.comments`). A service without the member still satisfies the contract. -- `AuditPlugin` registers the `comments` service with that member. It runs the same registrars over the same dependencies the `http.server` mount runs, on a private route table that never listens, so every answer is the mount's own. The `http.server` mount is unchanged, and no path is mounted twice. +- `AuditPlugin` registers the `comments` service with that member. It runs the same registrars over the same dependencies the `http.server` mount runs, on a private route table that never listens, so every answer is the mount's own. The `http.server` mount is unchanged, and no path is mounted twice. `@objectstack/plugin-audit` now depends on `@objectstack/plugin-hono-server` at runtime (the private table is a `HonoHttpServer`), and the `comments` service name is now taken: a composition that registers its own `comments` service alongside `AuditPlugin` fails to boot with a duplicate-service error. - The runtime dispatcher gains a `/comments` domain that claims exactly the three method and path shapes and forwards the request, body unread, to the request kernel's `comments` service. Every other `/comments` shape keeps the dispatcher's `404 ROUTE_NOT_FOUND`. With no `comments` service, or one without `handleCommentDoor`, the doors answer `501 NOT_IMPLEMENTED` naming `@objectstack/plugin-audit`. The doors stay behind the dispatcher's authentication and project-membership gates. diff --git a/packages/plugins/plugin-audit/src/comment-doors-member.ts b/packages/plugins/plugin-audit/src/comment-doors-member.ts index 822bb68744b..c27e1a921bf 100644 --- a/packages/plugins/plugin-audit/src/comment-doors-member.ts +++ b/packages/plugins/plugin-audit/src/comment-doors-member.ts @@ -8,9 +8,12 @@ * * `AuditPlugin` mounts the three comment doors on the kernel's `http.server` * (`mountCommentDoors`). A hosted tenant kernel owns no socket and registers no - * `http.server`, so on that shape the doors were never mounted, and the host's - * catch-all answered every unreact, resolve and own-comment delete with the - * unmatched `404 ENDPOINT_NOT_FOUND`. The runtime dispatcher reaches that + * `http.server`, so on that shape the doors were never mounted. Its host's + * `createHonoApp` catch-all handed each unreact, resolve and own-comment + * delete to the runtime dispatcher, where no domain claimed it, and the + * answer was the dispatcher's `404 ROUTE_NOT_FOUND`. (The card's hosted + * reading of `404 ENDPOINT_NOT_FOUND` is not explained by this tree.) The + * runtime dispatcher reaches that * kernel instead, through its `/comments` domain, which forwards the request * to this member on the kernel's `comments` slot (ruling A on #22438, applied * to this member of the class). 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 fea910ee48c..40f22911647 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 @@ -6,11 +6,13 @@ * REAL `AuditPlugin` over a real store. * * Before the `/comments` dispatcher domain and the `comments` slot existed, - * every request below answered the transport's unmatched - * `404 ENDPOINT_NOT_FOUND` on this shape: the doors were mounted only on the - * kernel's own `http.server`, which this kernel does not have. That is the - * card's measured body, and the first pin here asserts it is gone, door by - * door. + * every request below answered the dispatcher's `404 ROUTE_NOT_FOUND` on + * this shape: the doors were mounted only on the kernel's own `http.server`, + * 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.) * * What this pins: * 1. on the hosted shape, a member removes their own reaction, resolves and @@ -187,7 +189,7 @@ async function snapshot(res: Response) { } describe('[#36469] the comment doors answer on the hosted shape (createHonoApp, no http.server, real AuditPlugin)', () => { - it('no door answers the unmatched ENDPOINT_NOT_FOUND any more', async () => { + it('no door answers a route miss (ROUTE_NOT_FOUND or ENDPOINT_NOT_FOUND) any more', async () => { const door = await hostedDoor(); const { commentId, reactionId } = await door.seed(); const requests: Array<[string, RequestInit]> = [ @@ -198,6 +200,7 @@ describe('[#36469] the comment doors answer on the hosted shape (createHonoApp, for (const [path, init] of requests) { const res = await door.send(path, init); const body = await res.text(); + expect(body, `${init.method} ${path}`).not.toContain('ROUTE_NOT_FOUND'); expect(body, `${init.method} ${path}`).not.toContain('ENDPOINT_NOT_FOUND'); expect(res.status, `${init.method} ${path}: ${body}`).not.toBe(404); } diff --git a/packages/runtime/src/domains/comments.ts b/packages/runtime/src/domains/comments.ts index a43e4c8c464..ac54dfd29a8 100644 --- a/packages/runtime/src/domains/comments.ts +++ b/packages/runtime/src/domains/comments.ts @@ -14,9 +14,14 @@ * can read) and `DELETE /comments/:id` (remove a comment you wrote). A * self-hosted kernel serves them already: plugin-audit mounts them on the * kernel's `http.server` (`mountCommentDoors`). A hosted tenant kernel owns no - * socket and therefore no `http.server`, so on that shape every unreact, - * resolve and own-comment delete answered the host's unmatched - * `404 ENDPOINT_NOT_FOUND` (#36469). This domain is the hosted door (ruling A + * socket and therefore no `http.server`. Its host mounts `createHonoApp`'s + * `/api/v1/*` catch-all, which hands every request no other route claims to + * `dispatch()`, and no domain claimed these paths, so on that shape every + * unreact, resolve and own-comment delete answered the dispatcher's + * `404 ROUTE_NOT_FOUND` (#36469; the card's reading of the transport's + * `404 ENDPOINT_NOT_FOUND` on the hosted rig is not explained by this tree: + * it predates this domain, or a layer upstream of the catch-all answered it). + * This domain is the hosted door (ruling A * on #22438, applied to this member of the class): it forwards the request to * the request kernel's `comments` slot — the transport-neutral * `ICommentDoorsService.handleCommentDoor(request)` member — and returns that @@ -63,7 +68,8 @@ * Read on every request, never recorded (AGENTS.md, "Startup registry * reads"). An empty `comments` slot (a stack without plugin-audit) or a slot * whose service has no `handleCommentDoor` answers `501 NOT_IMPLEMENTED`, - * ⛔ never `ENDPOINT_NOT_FOUND`: the route IS mounted, and what is missing is + * ⛔ never the dispatcher's `404 ROUTE_NOT_FOUND` (nor a transport's + * `404 ENDPOINT_NOT_FOUND`): the route IS mounted, and what is missing is * the implementation behind it. */ diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index b07ccc9aef7..ab6717d0f5e 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -730,7 +730,7 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ // ── comment doors (the hosted door) ─────────────────────────────────────── { route: 'DELETE /comments/reactions/:id', domain: '/comments', disposition: 'server-only', - note: 'the unreact door: a member removes their own comment reaction, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the comments slot\'s ICommentDoorsService.handleCommentDoor, resolved per request (plugin-audit registers the slot in init), and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller (resolved from the request\'s own credentials, 401 with none), every refusal and every answer are the mount\'s. No preamble-gate exemption: the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never ENDPOINT_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from plugin-audit\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the console\'s comment panel is the consumer, and the SDK gap is acknowledged once, on the mount\'s own ledger rows (plugin-audit comment-reaction-route-ledger.ts / comment-route-ledger.ts). Pinned in `domains/comments.test.ts`' }, + note: 'the unreact door: a member removes their own comment reaction, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the comments slot\'s ICommentDoorsService.handleCommentDoor, resolved per request (plugin-audit registers the slot in init), and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller (resolved from the request\'s own credentials, 401 with none), every refusal and every answer are the mount\'s. No preamble-gate exemption: the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never the dispatcher's 404 ROUTE_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from plugin-audit\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the console\'s comment panel is the consumer, and the SDK gap is acknowledged once, on the mount\'s own ledger rows (plugin-audit comment-reaction-route-ledger.ts / comment-route-ledger.ts). Pinned in `domains/comments.test.ts`' }, { route: 'PUT /comments/:id/resolution', domain: '/comments', disposition: 'server-only', note: 'the resolution door: whoever can read a thread (and may post on it) resolves or reopens it, body exactly { resolved: boolean }. Same forwarding, credential, absence and door notes as the unreact row' }, { route: 'DELETE /comments/:id', domain: '/comments', disposition: 'server-only', diff --git a/packages/spec/src/contracts/comment-doors-service.ts b/packages/spec/src/contracts/comment-doors-service.ts index cd28dfc89f0..f254f231ed5 100644 --- a/packages/spec/src/contracts/comment-doors-service.ts +++ b/packages/spec/src/contracts/comment-doors-service.ts @@ -70,7 +70,8 @@ export interface ICommentDoorsService { * mounted twice. * * **Optional, and its absence is loud.** An empty `comments` slot or an - * absent member answers a typed `501`, ⛔ never `ENDPOINT_NOT_FOUND`: that + * absent member answers a typed `501`, ⛔ never the dispatcher's + * `404 ROUTE_NOT_FOUND` (nor a transport's `404 ENDPOINT_NOT_FOUND`): that * answer would tell a member the URL is wrong, when what is missing is the * service behind it. * From e7dcb26cc49a8cb61a3cddb0104b0371e7ffb7a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 21:28:08 +0000 Subject: [PATCH 12/12] fix(runtime): escape the apostrophe in the /comments unreact ledger note Claude-Session: https://claude.ai/code/session_01ADHkmRY38EZf38Yy3zthbY Co-authored-by: Claude --- packages/runtime/src/route-ledger.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index ab6717d0f5e..807a68e8486 100644 --- a/packages/runtime/src/route-ledger.ts +++ b/packages/runtime/src/route-ledger.ts @@ -730,7 +730,7 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ // ── comment doors (the hosted door) ─────────────────────────────────────── { route: 'DELETE /comments/reactions/:id', domain: '/comments', disposition: 'server-only', - note: 'the unreact door: a member removes their own comment reaction, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the comments slot\'s ICommentDoorsService.handleCommentDoor, resolved per request (plugin-audit registers the slot in init), and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller (resolved from the request\'s own credentials, 401 with none), every refusal and every answer are the mount\'s. No preamble-gate exemption: the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never the dispatcher's 404 ROUTE_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from plugin-audit\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the console\'s comment panel is the consumer, and the SDK gap is acknowledged once, on the mount\'s own ledger rows (plugin-audit comment-reaction-route-ledger.ts / comment-route-ledger.ts). Pinned in `domains/comments.test.ts`' }, + note: 'the unreact door: a member removes their own comment reaction, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the comments slot\'s ICommentDoorsService.handleCommentDoor, resolved per request (plugin-audit registers the slot in init), and the member\'s Response returned as it is: the member runs the very registration the self-hosted mount runs, so the caller (resolved from the request\'s own credentials, 401 with none), every refusal and every answer are the mount\'s. No preamble-gate exemption: the credential is the session, so the ADR-0069 auth gate and the project-membership gate both apply, which makes this door stricter than the self-hosted mount, never looser. An absent slot or member answers 501 NOT_IMPLEMENTED, never the dispatcher\'s 404 ROUTE_NOT_FOUND; a body consumed before it got here is a transport fault, answered 500 and logged. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from plugin-audit\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the console\'s comment panel is the consumer, and the SDK gap is acknowledged once, on the mount\'s own ledger rows (plugin-audit comment-reaction-route-ledger.ts / comment-route-ledger.ts). Pinned in `domains/comments.test.ts`' }, { route: 'PUT /comments/:id/resolution', domain: '/comments', disposition: 'server-only', note: 'the resolution door: whoever can read a thread (and may post on it) resolves or reopens it, body exactly { resolved: boolean }. Same forwarding, credential, absence and door notes as the unreact row' }, { route: 'DELETE /comments/:id', domain: '/comments', disposition: 'server-only',