From 21e9a8de48c29ecec037c1d9376266633cd9f6ea Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:33:37 +0000 Subject: [PATCH 1/6] fix(hosted): personal-view delete and attachment remove/rename reach a kernel with no http.server (WIP) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXs1Hrj1qNTkGdJbK1 --- .../plugins/plugin-auth/src/auth-plugin.ts | 29 +- .../src/personal-view-door-member.ts | 40 ++ .../src/door-table-member.ts | 83 +++++ .../plugins/plugin-hono-server/src/index.ts | 1 + packages/runtime/src/domains/attachments.ts | 42 +++ .../src/domains/own-door-bridge.test.ts | 348 ++++++++++++++++++ .../runtime/src/domains/own-door-bridge.ts | 215 +++++++++++ .../runtime/src/domains/personal-views.ts | 38 ++ packages/runtime/src/http-dispatcher.ts | 9 + .../services/service-storage/package.json | 1 + .../src/attachment-door-member.ts | 37 ++ .../src/file-attachment-service.ts | 25 +- .../src/storage-service-plugin.ts | 20 + .../services/service-storage/vitest.config.ts | 4 + .../attachment-doors-service.test.ts | 48 +++ .../src/contracts/attachment-doors-service.ts | 77 ++++ .../contracts/core-service-contracts.test.ts | 8 +- .../src/contracts/core-service-contracts.ts | 12 + packages/spec/src/contracts/index.ts | 4 + .../personal-view-doors-service.test.ts | 46 +++ .../contracts/personal-view-doors-service.ts | 69 ++++ pnpm-lock.yaml | 3 + 22 files changed, 1153 insertions(+), 6 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/personal-view-door-member.ts create mode 100644 packages/plugins/plugin-hono-server/src/door-table-member.ts create mode 100644 packages/runtime/src/domains/attachments.ts create mode 100644 packages/runtime/src/domains/own-door-bridge.test.ts create mode 100644 packages/runtime/src/domains/own-door-bridge.ts create mode 100644 packages/runtime/src/domains/personal-views.ts create mode 100644 packages/services/service-storage/src/attachment-door-member.ts create mode 100644 packages/spec/src/contracts/attachment-doors-service.test.ts create mode 100644 packages/spec/src/contracts/attachment-doors-service.ts create mode 100644 packages/spec/src/contracts/personal-view-doors-service.test.ts create mode 100644 packages/spec/src/contracts/personal-view-doors-service.ts diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 2edb4868ee3..c2e00f10a51 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -95,7 +95,8 @@ import { registerMfaRequiredEnrollmentPredicate } from './mfa-required-enrollmen import { registerPersonalViewHooks } from './personal-view-hooks.js'; import { registerUserPreferenceHooks } from './user-preference-hooks.js'; import { registerServiceAccountRowGuard } from './service-account-identity.js'; -import { personalViewCallerResolver, registerPersonalViewRoutes, PERSONAL_VIEW_REMOVE_ROUTE, type PersonalViewEngine } from './personal-view-routes.js'; +import { personalViewCallerResolver, registerPersonalViewRoutes, PERSONAL_VIEW_REMOVE_ROUTE, type PersonalViewEngine, type PersonalViewRoutesDeps } from './personal-view-routes.js'; +import { createPersonalViewDoorsService } from './personal-view-door-member.js'; import { registerMembershipEndedSessionTrigger } from './membership-ended-session.js'; import { IDP_GROUP_MAPPING_MATCH_PACKAGE_ID, @@ -1076,6 +1077,16 @@ export class AuthPlugin implements Plugin { ctx.registerService('tenancy', tenancy); this.tenancy = tenancy; + // [#36506] The personal-view delete door for a kernel with no + // `http.server` (a hosted tenant kernel runs `registerRoutes: false` and + // owns no socket): the runtime dispatcher's `/personal-views` domain + // forwards the request to this slot's `handlePersonalViewDoor`, which runs + // the registrar `mountPersonalViewDoor` runs, over the same deps, on a + // private table that never listens. Registered unconditionally, so the + // door answers wherever the plugin is composed; the self-hosted mount below + // is unchanged and nothing is mounted twice. + ctx.registerService('personal-views', createPersonalViewDoorsService(() => this.personalViewDoorDeps())); + // The stack's `demoStaff` — decided here, from configuration alone, so the // application's seed (which starts before `kernel:ready`) can wait for the // accounts it names. See `DemoStaffingService`. @@ -3839,15 +3850,25 @@ export class AuthPlugin implements Plugin { ); return; } - registerPersonalViewRoutes(httpServer, { + registerPersonalViewRoutes(httpServer, this.personalViewDoorDeps()); + ctx.logger.info(`Personal view delete door mounted at DELETE ${PERSONAL_VIEW_REMOVE_ROUTE}`); + } + + /** + * What the personal view door is composed over, on both of its faces: the + * self-hosted mount ({@link mountPersonalViewDoor}) and the `personal-views` + * slot's member (#36506). The engine, the auth service and the tenancy + * posture are read per request. + */ + private personalViewDoorDeps(): PersonalViewRoutesDeps { + return { getEngine: () => this.authManager?.getDataEngine() as unknown as PersonalViewEngine | undefined, resolveCaller: personalViewCallerResolver({ getEngine: () => this.authManager?.getDataEngine(), getAuth: () => (this.authManager ?? undefined) as unknown as RequestAuthService | undefined, tenancy: () => this.tenancy ?? undefined, }), - }); - ctx.logger.info(`Personal view delete door mounted at DELETE ${PERSONAL_VIEW_REMOVE_ROUTE}`); + }; } /** diff --git a/packages/plugins/plugin-auth/src/personal-view-door-member.ts b/packages/plugins/plugin-auth/src/personal-view-door-member.ts new file mode 100644 index 00000000000..702e7ef386b --- /dev/null +++ b/packages/plugins/plugin-auth/src/personal-view-door-member.ts @@ -0,0 +1,40 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] The personal-view delete door, served transport-neutrally: + * `IPersonalViewDoorsService.handlePersonalViewDoor` + * (`@objectstack/spec/contracts`), the occupant of the `personal-views` slot. + * + * `AuthPlugin` mounts the door on the kernel's `http.server` + * (`mountPersonalViewDoor`), and only under `registerRoutes`. A hosted tenant + * kernel owns no socket, registers no `http.server` and runs the plugin with + * `registerRoutes: false`, so on that shape the door was never mounted, and its + * host's `createHonoApp` catch-all handed every `DELETE + * /api/v1/personal-views/:id` to the runtime dispatcher, where no domain + * claimed it: `404 ROUTE_NOT_FOUND`. The dispatcher's `/personal-views` domain + * now forwards the request to this member on the request kernel (ruling A on + * #22438, applied to this member of the class). + * + * The member runs the SAME registrar the self-hosted mount runs + * (`registerPersonalViewRoutes`) over the SAME deps, on a private route table + * that never listens (`createDoorTableMember`), so every answer is the + * mount's own. + */ + +import type { IHttpServer, IPersonalViewDoorsService } from '@objectstack/spec/contracts'; +import { createDoorTableMember, type DoorTableRoute } from '@objectstack/plugin-hono-server'; + +import { PERSONAL_VIEW_REMOVE_ROUTE, registerPersonalViewRoutes, type PersonalViewRoutesDeps } from './personal-view-routes.js'; + +/** The one door, as the self-hosted mount registers it. */ +export const PERSONAL_VIEW_DOOR_ROUTES: readonly DoorTableRoute[] = Object.freeze([ + { method: 'DELETE', route: PERSONAL_VIEW_REMOVE_ROUTE }, +] as const); + +/** The `personal-views` service over `deps`, the deps the self-hosted mount is composed over. */ +export function createPersonalViewDoorsService(deps: () => PersonalViewRoutesDeps): Required { + const member = createDoorTableMember(PERSONAL_VIEW_DOOR_ROUTES, (http: IHttpServer) => + registerPersonalViewRoutes(http, deps()), + ); + return { handlePersonalViewDoor: member }; +} diff --git a/packages/plugins/plugin-hono-server/src/door-table-member.ts b/packages/plugins/plugin-hono-server/src/door-table-member.ts new file mode 100644 index 00000000000..ae0822a2d85 --- /dev/null +++ b/packages/plugins/plugin-hono-server/src/door-table-member.ts @@ -0,0 +1,83 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] A plugin's `IHttpServer`-mounted doors, served transport-neutrally + * as one `(request: Request) => Promise` member, for a kernel with no + * `http.server` (ruling A on #22438: the runtime dispatcher forwards the + * request to the member on the request kernel's service slot). + * + * ## One body, two faces + * + * The member runs the SAME registration the plugin's self-hosted mount runs + * (`mount`), on a private route table of its own: a {@link HonoHttpServer} that + * never listens. So the caller resolution, every refusal, the request-body + * reading 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 its routes + * + * A method and path that match none of `routes` answers + * `404 ENDPOINT_NOT_FOUND`, the transport's own unmatched answer, without + * reaching any door. The dispatcher claims exactly the doors' shapes and never + * forwards one. + */ + +import type { IHttpServer } from '@objectstack/spec/contracts'; +import { HonoHttpServer } from './adapter'; + +/** One door's method and wire route pattern (`/api/v1/...`, `:name` segments). */ +export interface DoorTableRoute { + readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; + readonly route: string; +} + +/** 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 door in `routes` that `method` and `pathname` name, or `undefined`. */ +export function matchDoorTableRoute( + routes: readonly DoorTableRoute[], + method: string, + pathname: string, +): DoorTableRoute | undefined { + const verb = method.toUpperCase(); + return routes.find((door) => door.method === verb && matchesRoute(door.route, pathname)); +} + +/** The transport's unmatched answer, as {@link HonoHttpServer}'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 the member over `mount`, the function that registers `routes` on an + * `IHttpServer` (the one the self-hosted mount calls too). + */ +export function createDoorTableMember( + routes: readonly DoorTableRoute[], + mount: (http: IHttpServer) => void, +): (request: Request) => Promise { + let table: HonoHttpServer | undefined; + return async (request: Request): Promise => { + if (!matchDoorTableRoute(routes, 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/packages/plugins/plugin-hono-server/src/index.ts b/packages/plugins/plugin-hono-server/src/index.ts index ae56c8e95ec..910e5a5ad35 100644 --- a/packages/plugins/plugin-hono-server/src/index.ts +++ b/packages/plugins/plugin-hono-server/src/index.ts @@ -18,3 +18,4 @@ export { resolveMaxRequestBodyBytes, type RequestBodyGuard, } from './body-limit'; +export * from './door-table-member'; diff --git a/packages/runtime/src/domains/attachments.ts b/packages/runtime/src/domains/attachments.ts new file mode 100644 index 00000000000..039deaae4bf --- /dev/null +++ b/packages/runtime/src/domains/attachments.ts @@ -0,0 +1,42 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `/attachments` domain — the attachment's removal and rename doors, reached + * through the dispatcher on a kernel with no `http.server` (#36506; ruling A + * on #22438, applied to this member of the class). The bridge itself is + * `own-door-bridge.ts`; this file names what it forwards. + * + * `DELETE /attachments/:id` removes one `sys_attachment` row the caller + * uploaded; `PATCH /attachments/:id` renames one. A self-hosted kernel serves + * both already: service-storage mounts them on the kernel's `http.server` + * (`mountAttachmentRemovalDoor`). A hosted tenant kernel owns no + * `http.server`, and its host's storage bridge covers only the storage + * family's own prefix (`/api/v1/storage`), so the host's `createHonoApp` + * catch-all handed both to `dispatch()`, where no domain claimed them: every + * attachment removal and rename answered `404 ROUTE_NOT_FOUND`. This domain + * forwards the request to the request kernel's `file-attachments` service, + * whose transport-neutral `IAttachmentDoorsService.handleAttachmentDoor` runs + * the doors, and returns its `Response` as it is. Only those two method and + * path shapes are claimed; every other one keeps the ordinary miss. + */ + +import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js'; +import { createOwnDoorBridgeDomain, type OwnDoorBridge } from './own-door-bridge.js'; + +/** What the bridge forwards, and to whom. */ +export const ATTACHMENTS_BRIDGE: OwnDoorBridge = Object.freeze({ + prefix: '/attachments', + doors: Object.freeze([ + { method: 'DELETE', pattern: '/attachments/:id' }, + { method: 'PATCH', pattern: '/attachments/:id' }, + ] as const), + slot: 'file-attachments', + member: 'handleAttachmentDoor', + producer: '@objectstack/service-storage (StorageServicePlugin)', + noun: 'the attachment removal and rename doors', + tag: 'attachments', +}); + +export function createAttachmentsDomain(deps: DomainHandlerDeps): DomainRoute { + return createOwnDoorBridgeDomain(deps, ATTACHMENTS_BRIDGE); +} diff --git a/packages/runtime/src/domains/own-door-bridge.test.ts b/packages/runtime/src/domains/own-door-bridge.test.ts new file mode 100644 index 00000000000..52d0a71d3ce --- /dev/null +++ b/packages/runtime/src/domains/own-door-bridge.test.ts @@ -0,0 +1,348 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] The `/personal-views` and `/attachments` dispatcher domains — the + * personal-view delete door and the attachment removal and rename doors for a + * kernel with no `http.server` (ruling A on #22438, applied to each member of + * the class), both through `own-door-bridge.ts`. + * + * Driven through the REAL `HttpDispatcher.dispatch()` on a kernel that + * registers no `http.server` (the hosted shape), with stub members that read + * the request they are handed (method, path, body). + * + * What this pins, for each domain: + * 1. each door shape 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 door shapes alone: every other method and path under + * the prefix keeps the dispatcher's ordinary miss, and the member never + * runs for one; + * 3. an absent slot, or a service with no member, answers + * `501 NOT_IMPLEMENTED` — ⛔ never a route miss — and the slot is read per + * request; + * 4. the slot is the REQUEST kernel's: a tenant kernel without the member is + * never served by the host kernel's member; + * 5. a member that throws, or a body the transport already consumed, answers + * a sanitised `500` and is logged; + * 6. the environment-scoped spelling reaches the member at the wire path; + * 7. no preamble-gate exemption: a signed-in non-member of the environment and + * a session owing an authentication step are stopped before the member. + * + * The wire half — `createHonoApp` over a kernel with the REAL plugins and no + * `http.server` — is + * `packages/qa/http-conformance/src/hono-own-row-doors.conformance.test.ts`. + */ + +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'; + +const ORIGIN = 'http://tenant.example'; +const JSON_HEADERS = { 'Content-Type': 'application/json' }; + +/** A member that records and echoes what it was handed. */ +function stubMember() { + const seen: Array<{ request: Request; method: string; path: string; body: string }> = []; + const fn = 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 { fn, seen }; +} + +/** + * A kernel with no `http.server` — only the services named. An unknown name + * answers `null`, except the names in `throwing`, which throw, as a real + * kernel's lookup of an unregistered name does. + */ +function kernelWith(services: Record, throwing: readonly string[] = []): any { + const get = (n: string) => { + if (services[n] == null && throwing.includes(n)) throw new Error(`Service '${n}' not found`); + return services[n] ?? null; + }; + return { + getState: () => 'running', + getService: get, + getServiceAsync: async (n: string) => get(n), + context: { getService: get }, + }; +} + +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 }); + +interface Family { + name: string; + slot: string; + member: string; + producer: string; + prefix: string; + doors: Array<[method: string, path: string, body?: unknown]>; + misses: Array<[method: string, path: string]>; + lexicalSibling: string; +} + +const FAMILIES: Family[] = [ + { + name: 'personal-views', + slot: 'personal-views', + member: 'handlePersonalViewDoor', + producer: '@objectstack/plugin-auth', + prefix: '/personal-views', + doors: [['DELETE', '/personal-views/pv_1']], + misses: [ + ['GET', '/personal-views/pv_1'], + ['POST', '/personal-views/pv_1'], + ['PATCH', '/personal-views/pv_1'], + ['PUT', '/personal-views/pv_1'], + ['DELETE', '/personal-views'], + ['DELETE', '/personal-views/'], + ['DELETE', '/personal-views/pv_1/x'], + ], + lexicalSibling: '/personal-viewsx/pv_1', + }, + { + name: 'attachments', + slot: 'file-attachments', + member: 'handleAttachmentDoor', + producer: '@objectstack/service-storage', + prefix: '/attachments', + doors: [ + ['DELETE', '/attachments/att_1'], + ['PATCH', '/attachments/att_1', { name: 'renamed.pdf' }], + ], + misses: [ + ['GET', '/attachments/att_1'], + ['POST', '/attachments/att_1'], + ['PUT', '/attachments/att_1'], + ['DELETE', '/attachments'], + ['PATCH', '/attachments/'], + ['DELETE', '/attachments/att_1/x'], + ['PATCH', '/attachments/att_1/name'], + ], + lexicalSibling: '/attachmentsx/att_1', + }, +]; + +describe.each(FAMILIES)('[#36506] $prefix forwards its doors to the $slot member on a kernel with no http.server', (family) => { + const withMember = (fn: unknown) => ({ [family.slot]: { [family.member]: fn } }); + + it.each(family.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(withMember(member.fn)); + const request = wire(method, path, body); + + const result = await dispatcher.dispatch(method, path, { name: 'not-this-one' }, {}, ctx(request)); + + expect(result.handled).toBe(true); + expect(result.response, JSON.stringify(result.response?.body)).toBeUndefined(); + expect(member.fn).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 door shapes: every other method and path keeps the ordinary miss, and the member never runs', async () => { + const member = stubMember(); + const { dispatcher } = makeDispatcher(withMember(member.fn)); + for (const [method, path] of family.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(family.lexicalSibling, 'DELETE')).toBeUndefined(); + expect(member.fn).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(withMember(member.fn)); + const [method, doorPath, body] = family.doors[family.doors.length - 1]!; + const path = `/environments/env_1${doorPath}`; + + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path, body))); + + expect(result.response, JSON.stringify(result.response?.body)).toBeUndefined(); + expect(member.seen).toHaveLength(1); + expect(member.seen[0]!.path).toBe(`/api/v1${doorPath}`); + expect(member.seen[0]!.body).toBe(body === undefined ? '' : JSON.stringify(body)); + }); + + it(`no ${family.slot} service on the kernel: 501 NOT_IMPLEMENTED naming the package that registers it, never a route miss`, async () => { + const { dispatcher } = makeDispatcher({}); + for (const [method, path, body] of family.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(family.producer); + } + }); + + it(`a kernel whose lookup of ${family.slot} throws reads as an empty slot: 501 NOT_IMPLEMENTED`, async () => { + const dispatcher = new HttpDispatcher(kernelWith({}, [family.slot]), undefined, { enforceProjectMembership: false }); + const [method, path] = family.doors[0]!; + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + expect(envelope(result)).toEqual({ status: 501, code: 'NOT_IMPLEMENTED' }); + }); + + it(`a ${family.slot} service with no ${family.member}: 501 NOT_IMPLEMENTED naming the member`, async () => { + const { dispatcher } = makeDispatcher({ [family.slot]: { somethingElse: vi.fn() } }); + const [method, path] = family.doors[0]!; + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + expect(envelope(result)).toEqual({ status: 501, code: 'NOT_IMPLEMENTED' }); + expect(result.response?.body?.error?.message).toContain(`does not implement ${family.member}`); + }); + + 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 [method, path] = family.doors[0]!; + + const before = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + expect(envelope(before)).toEqual({ status: 501, code: 'NOT_IMPLEMENTED' }); + + const member = stubMember(); + Object.assign(services, withMember(member.fn)); + const after = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + expect(after.response, JSON.stringify(after.response?.body)).toBeUndefined(); + expect((after.result as Response).status).toBe(200); + }); + + it('the slot is the REQUEST kernel\'s: a tenant kernel without the member is never served by the host kernel\'s', async () => { + const hostMember = stubMember(); + const tenant = kernelWith({}); + const resolver: KernelResolver = { resolveKernel: async () => tenant }; + const dispatcher = new HttpDispatcher(kernelWith(withMember(hostMember.fn)), undefined, { + kernelResolver: resolver, + enforceProjectMembership: false, + }); + const [method, path] = family.doors[0]!; + + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + + expect(envelope(result)).toEqual({ status: 501, code: 'NOT_IMPLEMENTED' }); + expect(hostMember.fn).not.toHaveBeenCalled(); + }); + + 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_secret_table'); + const { dispatcher, logger } = makeDispatcher(withMember(vi.fn().mockRejectedValue(boom))); + const [method, path] = family.doors[0]!; + + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + + expect(envelope(result)).toEqual({ status: 500, code: 'INTERNAL_ERROR' }); + expect(JSON.stringify(result.response?.body)).not.toContain('sys_secret_table'); + expect(logger.error).toHaveBeenCalledTimes(1); + expect(logger.error.mock.calls[0]![1]).toBe(boom); + }); + + it('a request whose body the transport already consumed: 500 and logged, and the member is never asked', async () => { + const member = stubMember(); + const { dispatcher, logger } = makeDispatcher(withMember(member.fn)); + const [method, path] = family.doors[0]!; + const request = wire(method, path, { any: 'body' }); + await request.text(); + + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(request)); + + expect(envelope(result)).toEqual({ status: 500, code: 'INTERNAL_ERROR' }); + expect(member.fn).not.toHaveBeenCalled(); + expect(String(logger.error.mock.calls[0]![0])).toContain('request body was consumed'); + }); + + describe('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 door = 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, ...withMember(door.fn) }); + const resolver: KernelResolver = { + resolveKernel: async (c: HttpProtocolContext) => { + c.environmentId = ENV; + return tenant; + }, + }; + const dispatcher = new HttpDispatcher(kernelWith({}), undefined, { + kernelResolver: resolver, + enforceProjectMembership: true, + }); + return { dispatcher, door }; + } + + it('a signed-in caller who is not a member of the environment is refused 403 before the member runs', async () => { + const { dispatcher, door } = makeTenantHost(); + const [method, path] = family.doors[0]!; + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + expect(envelope(result)).toEqual({ status: 403, code: 'PROJECT_MEMBERSHIP_REQUIRED' }); + expect(door.fn).not.toHaveBeenCalled(); + }); + + it('⭐ control: a member of the environment reaches the member', async () => { + const { dispatcher, door } = makeTenantHost({ member: true }); + const [method, path] = family.doors[0]!; + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + expect(result.response, JSON.stringify(result.response?.body)).toBeUndefined(); + expect(door.fn).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, door } = makeTenantHost({ + member: true, + authGate: { code: 'PASSWORD_EXPIRED', message: 'Your password has expired.' }, + }); + const [method, path] = family.doors[0]!; + const result = await dispatcher.dispatch(method, path, {}, {}, ctx(wire(method, path))); + expect(result.response?.status).toBe(403); + expect(result.response?.body?.error?.details?.code ?? result.response?.body?.error?.code).toBe('PASSWORD_EXPIRED'); + expect(door.fn).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/runtime/src/domains/own-door-bridge.ts b/packages/runtime/src/domains/own-door-bridge.ts new file mode 100644 index 00000000000..65e291d6da9 --- /dev/null +++ b/packages/runtime/src/domains/own-door-bridge.ts @@ -0,0 +1,215 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The shared body of a dispatcher bridge to a plugin's own-row door (#36506): + * one exact claim of a door's method and path shapes, forwarded to one + * transport-neutral member on the REQUEST kernel's service slot. Not a domain + * itself; `personal-views.ts` and `attachments.ts` are its two callers. + * + * ## Why a bridge, and for which kernel + * + * A plugin that mounts a door on the kernel's `http.server` serves it only + * where there is one. A hosted tenant kernel owns no socket and so registers no + * `http.server`: its host mounts `createHonoApp`'s `/api/v1/*` catch-all, + * which hands every request no other route claims to `dispatch()`, and with no + * domain for the door's path the answer was the dispatcher's + * `404 ROUTE_NOT_FOUND`. The bridge is ruling A on #22438, applied to each + * member of the class: the dispatcher owns the registration (ADR-0076 D11), + * the plugin serves the request through one member that runs the very + * registration its self-hosted mount runs, and the self-hosted mount is + * untouched. `comments.ts` is the same bridge, written out for its three + * doors. + * + * ## The claim is exact + * + * The registry claims the prefix for the doors' methods only; the handler then + * claims only the doors' method and path shapes and answers every other one + * with the dispatcher's ordinary miss, exactly what it answered before the + * domain existed. The member never runs for one. + * + * ## The request is forwarded, never read + * + * Neither the body nor the parsed `body` handed to `dispatch()` is read here: + * the member owns the read, and what it receives is the transport's own + * request (`context.request`), at the door's wire path. A request that arrived + * under the environment-scoped spelling is handed on with its URL rewritten to + * the wire path and its body still unread. A body the transport already + * consumed would reach the member empty, so that is answered loudly as a + * server fault instead. + * + * ## 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 (the ADR-0069 auth-gate allow-list, and + * `HttpDispatcher.enforceProjectMembership`), 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 the REQUEST kernel's, read per request + * + * The member is looked up with `getRequestKernelService`: the request's own + * resolved kernel, never the host kernel's scoped fallback. Each of these + * doors writes a row through the engine of the kernel whose member serves it, + * so a tenant kernel that lacks the member must answer `501`, ⛔ never be + * served by the host's member over the host's data. Read on every request, + * never recorded (AGENTS.md, "Startup registry reads"). An empty slot or a + * service without the member answers `501 NOT_IMPLEMENTED`, ⛔ never the + * dispatcher's `404 ROUTE_NOT_FOUND`: the route IS mounted, and what is + * missing is the implementation behind it. + */ + +import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types'; +import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js'; +import type { DomainHandlerDeps, DomainRequest, DomainRoute } from '../domain-handler-registry.js'; + +/** One door's method and route pattern, as a dispatcher path (API prefix stripped). */ +export interface OwnDoorShape { + readonly method: 'DELETE' | 'PATCH' | 'PUT' | 'POST'; + readonly pattern: string; +} + +/** What one bridge forwards, and to whom. */ +export interface OwnDoorBridge { + /** The prefix the registry claims (a segment claim, narrowed by the handler). */ + readonly prefix: string; + /** The doors, in the self-hosted mount's order. */ + readonly doors: readonly OwnDoorShape[]; + /** The service slot the member lives on. */ + readonly slot: string; + /** The member's name on that slot's service. */ + readonly member: string; + /** The package that registers the slot, named in the `501` for an empty slot. */ + readonly producer: string; + /** The doors' noun for answers and log lines, e.g. `the personal view door`. */ + readonly noun: string; + /** The log tag, e.g. `personal-views`. */ + readonly tag: string; +} + +/** The wire prefix the doors are mounted under by their plugins (their routes are fixed at `/api/v1`). */ +const DOOR_WIRE_PREFIX = '/api/v1'; + +/** + * Is `method path` one of `doors`? `path` is the dispatcher's clean path; each + * `:id` matches one non-empty segment. + */ +export function matchOwnDoorPath(doors: readonly OwnDoorShape[], method: string, path: string): boolean { + const verb = method.toUpperCase(); + const got = path.split('/'); + return doors.some((door) => { + if (door.method !== verb) return false; + const want = door.pattern.split('/'); + return want.length === got.length + && want.every((segment, i) => (segment.startsWith(':') ? got[i].length > 0 : segment === got[i])); + }); +} + +/** The registry entry for `bridge`. */ +export function createOwnDoorBridgeDomain(deps: DomainHandlerDeps, bridge: OwnDoorBridge): DomainRoute { + return { + prefix: bridge.prefix, + match: 'segment', + methods: [...new Set(bridge.doors.map((door) => door.method))], + handler: (req, context) => handleOwnDoorBridgeRequest(deps, bridge, 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 one door request to the request kernel's member and return its `Response` untouched. */ +export async function handleOwnDoorBridgeRequest( + deps: DomainHandlerDeps, + bridge: OwnDoorBridge, + req: DomainRequest, + context: HttpProtocolContext, +): Promise { + // Not one of the doors: the dispatcher's ordinary miss, the answer the + // path got before this domain existed. + if (!matchOwnDoorPath(bridge.doors, req.method, req.path)) { + return { handled: true, response: deps.routeNotFound(req.path) }; + } + + // A kernel that throws for an unregistered name reads as an empty slot. + let service: Record | null | undefined; + try { + service = await deps.getRequestKernelService(context, bridge.slot) as Record | null | undefined; + } catch { + service = undefined; + } + if (!service) { + return { + handled: true, + response: deps.error( + `${capitalize(bridge.noun)} is not available: no ${bridge.slot} service is registered on this kernel. ` + + `${bridge.producer} registers it.`, + 501, + ), + }; + } + const member = service[bridge.member]; + if (typeof member !== 'function') { + return { + handled: true, + response: deps.error( + `${capitalize(bridge.noun)} is not available: the registered ${bridge.slot} service ` + + `does not implement ${bridge.member}.`, + 501, + ), + }; + } + + const request = context.request as Request; + const logger = deps.logger ?? console; + + if (request?.bodyUsed === true) { + logger?.error?.( + `[${bridge.tag}] the request body was consumed before the ${bridge.prefix} 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 answer the door would have given', + ); + return { handled: true, response: deps.error(INTERNAL_ERROR_MESSAGE, 500) }; + } + + try { + const result = await (member as (request: Request) => Promise).call(service, atWirePath(request, req.path)); + return { handled: true, result }; + } catch (err) { + // As `/comments`: 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?.( + `[${bridge.tag}] the ${bridge.slot} service threw while serving ${bridge.noun}; 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) }; + } +} + +function capitalize(text: string): string { + return text.charAt(0).toUpperCase() + text.slice(1); +} diff --git a/packages/runtime/src/domains/personal-views.ts b/packages/runtime/src/domains/personal-views.ts new file mode 100644 index 00000000000..051b858091d --- /dev/null +++ b/packages/runtime/src/domains/personal-views.ts @@ -0,0 +1,38 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `/personal-views` domain — the personal-view delete door, reached through + * the dispatcher on a kernel with no `http.server` (#36506; ruling A on #22438, + * applied to this member of the class). The bridge itself is + * `own-door-bridge.ts`; this file names what it forwards. + * + * `DELETE /personal-views/:id` removes one `sys_personal_view` row, and only + * the caller's own. A self-hosted kernel serves it already: plugin-auth mounts + * it on the kernel's `http.server` (`mountPersonalViewDoor`). A hosted tenant + * kernel owns no `http.server` and runs `AuthPlugin` with + * `registerRoutes: false`, so there no route answered it, and the host's + * `createHonoApp` catch-all handed it to `dispatch()`, where no domain claimed + * it: every personal-view delete answered `404 ROUTE_NOT_FOUND`. This domain + * forwards the request to the request kernel's `personal-views` slot, the + * transport-neutral `IPersonalViewDoorsService.handlePersonalViewDoor`, and + * returns its `Response` as it is. Only `DELETE /personal-views/:id` is + * claimed; every other method and path keeps the ordinary miss. + */ + +import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js'; +import { createOwnDoorBridgeDomain, type OwnDoorBridge } from './own-door-bridge.js'; + +/** What the bridge forwards, and to whom. */ +export const PERSONAL_VIEWS_BRIDGE: OwnDoorBridge = Object.freeze({ + prefix: '/personal-views', + doors: Object.freeze([{ method: 'DELETE', pattern: '/personal-views/:id' }] as const), + slot: 'personal-views', + member: 'handlePersonalViewDoor', + producer: '@objectstack/plugin-auth (AuthPlugin)', + noun: 'the personal view delete door', + tag: 'personal-views', +}); + +export function createPersonalViewsDomain(deps: DomainHandlerDeps): DomainRoute { + return createOwnDoorBridgeDomain(deps, PERSONAL_VIEWS_BRIDGE); +} diff --git a/packages/runtime/src/http-dispatcher.ts b/packages/runtime/src/http-dispatcher.ts index 7cb31b65008..83faa5bc8cc 100644 --- a/packages/runtime/src/http-dispatcher.ts +++ b/packages/runtime/src/http-dispatcher.ts @@ -58,6 +58,8 @@ 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 { createPersonalViewsDomain } from './domains/personal-views.js'; +import { createAttachmentsDomain } from './domains/attachments.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'; @@ -1019,6 +1021,13 @@ export class HttpDispatcher { // forwarded to the `comments` slot's `handleCommentDoor`, resolved per // request. See `./domains/comments.ts`. this.domainRegistry.register(createCommentsDomain(this.domainDeps)); + // The personal-view delete door and the attachment removal and rename + // doors for a kernel with no `http.server` (#36506; ruling A on + // #22438): exactly their method and path shapes, forwarded to the + // REQUEST kernel's `personal-views` / `file-attachments` member, read + // per request. See `./domains/own-door-bridge.ts`. + this.domainRegistry.register(createPersonalViewsDomain(this.domainDeps)); + this.domainRegistry.register(createAttachmentsDomain(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/services/service-storage/package.json b/packages/services/service-storage/package.json index beb464242b0..49fd1bb65fd 100644 --- a/packages/services/service-storage/package.json +++ b/packages/services/service-storage/package.json @@ -29,6 +29,7 @@ "@objectstack/core": "workspace:*", "@objectstack/observability": "workspace:*", "@objectstack/platform-objects": "workspace:*", + "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/service-cluster": "workspace:*", "@objectstack/spec": "workspace:*", "@objectstack/types": "workspace:*" diff --git a/packages/services/service-storage/src/attachment-door-member.ts b/packages/services/service-storage/src/attachment-door-member.ts new file mode 100644 index 00000000000..827d28ad0d6 --- /dev/null +++ b/packages/services/service-storage/src/attachment-door-member.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] The attachment's own doors, served transport-neutrally: + * `IAttachmentDoorsService.handleAttachmentDoor` (`@objectstack/spec/contracts`), + * a member of the `file-attachments` service. + * + * `StorageServicePlugin` mounts the uploader's removal door and the rename door + * on the kernel's `http.server` (`mountAttachmentRemovalDoor`). A hosted tenant + * kernel owns no socket and registers no `http.server`, and its host's storage + * bridge covers only `/api/v1/storage`, so on that shape the doors were never + * mounted, and the host's `createHonoApp` catch-all handed every `DELETE` and + * `PATCH /api/v1/attachments/:id` to the runtime dispatcher, where no domain + * claimed it: `404 ROUTE_NOT_FOUND`. The dispatcher's `/attachments` domain now + * forwards the request to this member on the request kernel (ruling A on + * #22438, applied to this member of the class). + * + * The member runs the SAME mount the self-hosted kernel runs, over the same + * kernel, on a private route table that never listens + * (`createDoorTableMember`), so every answer is the mount's own. + */ + +import type { IHttpServer } from '@objectstack/spec/contracts'; +import { createDoorTableMember, type DoorTableRoute } from '@objectstack/plugin-hono-server'; + +import { ATTACHMENT_REMOVE_ROUTE, ATTACHMENT_RENAME_ROUTE } from './attachment-removal-routes.js'; + +/** The two doors, in the self-hosted mount's registration order. */ +export const ATTACHMENT_DOOR_ROUTES: readonly DoorTableRoute[] = Object.freeze([ + { method: 'DELETE', route: ATTACHMENT_REMOVE_ROUTE }, + { method: 'PATCH', route: ATTACHMENT_RENAME_ROUTE }, +] as const); + +/** `handleAttachmentDoor` over `mount`, the function the self-hosted mount calls too. */ +export function createAttachmentDoorMember(mount: (http: IHttpServer) => void): (request: Request) => Promise { + return createDoorTableMember(ATTACHMENT_DOOR_ROUTES, mount); +} diff --git a/packages/services/service-storage/src/file-attachment-service.ts b/packages/services/service-storage/src/file-attachment-service.ts index 4b0448dc0ba..ed53dae353a 100644 --- a/packages/services/service-storage/src/file-attachment-service.ts +++ b/packages/services/service-storage/src/file-attachment-service.ts @@ -6,6 +6,7 @@ import type { ISecurityService, AttachFileInput, AttachedFile, + IAttachmentDoorsService, IDataEngine, IFileAttachmentService, IObjectQLEngine, @@ -174,6 +175,14 @@ export interface FileAttachmentServiceDeps { RecordFileAccessDeps, 'judgeFileRead' | 'isServable' | 'resolveUserContext' | 'getDownloadTtl' | 'getBasePath' | 'getI18n' >; + /** + * [#36506] The attachment's own doors (removal and rename), served + * transport-neutrally: the member {@link FileAttachmentService.handleAttachmentDoor} + * is, built by the plugin over the same registration its `http.server` mount + * runs. Absent: the service has no such member, and the dispatcher's + * `/attachments` domain answers `501`. + */ + attachmentDoors?: (request: Request) => Promise; } /** @@ -318,11 +327,25 @@ function validateAttachUploadInput(input: AttachUploadInput): AttachUploadInput } export class FileAttachmentService - implements IFileAttachmentService, ICallerFileAttachmentService, ICallerRecordFileService, UploadLinkDoor + implements + IFileAttachmentService, + IAttachmentDoorsService, + ICallerFileAttachmentService, + ICallerRecordFileService, + UploadLinkDoor { private readonly recordFiles: RecordFileAccess | null; + /** + * [#36506] `IAttachmentDoorsService.handleAttachmentDoor`: the attachment's + * removal and rename doors for a kernel with no `http.server`, reached through + * the runtime dispatcher's `/attachments` domain. Present exactly when the + * composition supplied {@link FileAttachmentServiceDeps.attachmentDoors}. + */ + readonly handleAttachmentDoor?: (request: Request) => Promise; + constructor(private readonly deps: FileAttachmentServiceDeps) { + if (deps.attachmentDoors) this.handleAttachmentDoor = deps.attachmentDoors; // The host bound is judged where the verb is built, as at every host door. parseHostMaxUploadMb(deps.hostMaxUploadMb, 'FileAttachmentService'); const bound = deps.recordFiles; diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index f4aa2c3c0f7..c63a951d105 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -98,6 +98,7 @@ import { registerAttachmentRemovalRoutes, } from './attachment-removal-routes.js'; import { installAttachmentFilesOptInGate } from './attachment-files-opt-in.js'; +import { createAttachmentDoorMember } from './attachment-door-member.js'; import { FileAttachmentService, type FileAttachmentEngine, @@ -474,6 +475,22 @@ export class StorageServicePlugin implements Plugin { () => this.attachmentEngine, this.options.basePath ?? DEFAULT_STORAGE_BASE_PATH, ), + // [#36506] The attachment's removal and rename doors for a kernel with + // no `http.server` (a hosted tenant kernel): the runtime dispatcher's + // `/attachments` domain forwards the request to this service's + // `handleAttachmentDoor`, which runs `mountAttachmentRemovalDoor` — the + // mount the `http.server` branch at `kernel:ready` runs — over this + // kernel, on a private table that never listens, built on the first + // request. The data engine is read then, the one that mount reads. + attachmentDoors: createAttachmentDoorMember((http) => { + let doorEngine: IDataEngine | null = null; + try { + doorEngine = ctx.getService('objectql') ?? null; + } catch { + doorEngine = null; + } + mountAttachmentRemovalDoor(http, toGateRegistry(ctx), doorEngine, ctx.logger); + }), }), ); // [#25779] The server-side field-file verb, under `FIELD_FILE_SERVICE`. @@ -809,6 +826,9 @@ export class StorageServicePlugin implements Plugin { // removes an attachment they uploaded, with no delete bit on the // member grant. Beside the storage family, not in it — its route is // fixed and its ledger its own (`attachment-removal-routes.ts`). + // [#36506] With no `http.server` the same doors are served by the + // `file-attachments` service's `handleAttachmentDoor`, reached through + // the runtime dispatcher's `/attachments` domain. if (httpServer) mountAttachmentRemovalDoor(httpServer, toGateRegistry(ctx), engine, ctx.logger); } diff --git a/packages/services/service-storage/vitest.config.ts b/packages/services/service-storage/vitest.config.ts index c8881800a0c..92e36a95555 100644 --- a/packages/services/service-storage/vitest.config.ts +++ b/packages/services/service-storage/vitest.config.ts @@ -84,6 +84,10 @@ export default defineConfig({ { find: /^@objectstack\/core$/, replacement: path.resolve(__dirname, '../../core/src/index.ts') }, { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../../drivers/driver-sql/src/index.ts') }, { find: /^@objectstack\/plugin-audit$/, replacement: path.resolve(__dirname, '../../plugins/plugin-audit/src/index.ts') }, + // [#36506] The never-listening route table `attachment-door-member.ts` + // serves the attachment doors on for a kernel with no `http.server`: to + // source, so the suite's verdict is about the checkout. + { find: /^@objectstack\/plugin-hono-server$/, replacement: path.resolve(__dirname, '../../plugins/plugin-hono-server/src/index.ts') }, { find: /^@objectstack\/service-cluster$/, replacement: path.resolve(__dirname, '../service-cluster/src/index.ts') }, { find: /^@objectstack\/service-settings$/, replacement: path.resolve(__dirname, '../service-settings/src/index.ts') }, ], diff --git a/packages/spec/src/contracts/attachment-doors-service.test.ts b/packages/spec/src/contracts/attachment-doors-service.test.ts new file mode 100644 index 00000000000..53f453cea3f --- /dev/null +++ b/packages/spec/src/contracts/attachment-doors-service.test.ts @@ -0,0 +1,48 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#36506] `IAttachmentDoorsService.handleAttachmentDoor`: the attachment's +// removal and rename doors, declared transport-neutrally on the contract the +// `file-attachments` service implements beside `IFileAttachmentService`, so the +// runtime dispatcher can reach them on a kernel with no `http.server`. +// +// Type-level pins, the shape `comment-doors-service.test.ts` uses: the member is +// OPTIONAL, at the web-standard `(request: Request) => Promise` +// shape, and the barrel exports the same contract. 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 { IAttachmentDoorsService } from './attachment-doors-service'; +import type { IAttachmentDoorsService as FromBarrel, IFileAttachmentService } from './index'; + +type Eq = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; +type Assert = T; + +type HandleAttachmentDoor = NonNullable; + +/** Optional: a service may omit it. A required member turns this alias red. */ +export type AttachmentDoorIsOptional = Assert< + {} extends Pick ? true : false +>; + +/** One web-standard `Request` in: the whole input, with no execution context beside it. */ +export type AttachmentDoorTakesOneRequest = Assert, [request: Request]>>; + +/** A web-standard `Response` out, asynchronously. */ +export type AttachmentDoorAnswersAResponse = Assert, Promise>>; + +/** The barrel (`@objectstack/spec/contracts`) exports this contract, not a look-alike. */ +export type BarrelExportsTheContract = Assert>; + +/** It composes with the attach verb's contract on one service, member names apart. */ +export type ComposesWithTheAttachVerb = Assert< + Eq +>; + +describe('IAttachmentDoorsService.handleAttachmentDoor: the attachment doors, declared transport-neutrally', () => { + it('is optional: a service object without it still satisfies IAttachmentDoorsService', () => { + const service: IAttachmentDoorsService = {}; + + expect(service.handleAttachmentDoor).toBeUndefined(); + }); +}); diff --git a/packages/spec/src/contracts/attachment-doors-service.ts b/packages/spec/src/contracts/attachment-doors-service.ts new file mode 100644 index 00000000000..9e752fcdda8 --- /dev/null +++ b/packages/spec/src/contracts/attachment-doors-service.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * @objectstack/spec/contracts/attachment-doors-service + * + * Cross-package contract for the attachment's own doors, served off the + * `file-attachments` slot (`FILE_ATTACHMENT_SERVICE`). The + * implementation lives in `@objectstack/service-storage`, which owns + * `sys_attachment`: its `file-attachments` service implements this contract + * beside `IFileAttachmentService`, so the doors need no slot of their + * own. + * + * The doors, both at one route: + * + * - `DELETE /api/v1/attachments/:id` — the uploader removes an attachment + * they uploaded, and only their own, with no object-level delete grant; + * - `PATCH /api/v1/attachments/:id` — rename an attachment from the record's + * Attachments panel. + * + * A self-hosted kernel serves them from the storage plugin's own mount on the + * kernel's `http.server`. A hosted tenant kernel owns no socket and so has no + * `http.server`, and its host's storage bridge covers only the storage + * family's own prefix (`/api/v1/storage`), so the runtime dispatcher reaches + * these doors instead (#36506; the bridge the maintainer's ruling A on #22438 + * directs for every member of this class, as + * `ICommentDoorsService.handleCommentDoor` is bridged). + */ + +/** + * The attachment's own doors, as the `file-attachments` service serves them. + * + * Every member is optional. A kernel without `@objectstack/service-storage` + * leaves the slot empty, and a caller probes for the member it needs before + * calling it. + */ +export interface IAttachmentDoorsService { + /** + * **The attachment's two doors, served transport-neutrally.** One member for + * the two methods, because they are one route with one caller rule: the + * member matches the request's method and path 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. + * - A request whose method and path match neither door 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/attachments/:id`). 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 `/attachments` + * domain, which claims exactly the two method and path shapes and forwards + * the request with its body unread. The path is not on the ADR-0069 + * auth-gate allow-list and the project-membership gate does not skip it, so + * on that shape the dispatcher door is stricter than the self-hosted mount, + * never looser. + * + * **Optional, and its absence is loud.** An empty slot or an absent member + * answers a typed `501`, ⛔ never the dispatcher's `404 ROUTE_NOT_FOUND`. + * + * @param request - The forwarded request: the caller's credentials are in its + * headers, the attachment's id in its path, and the rename door's JSON body + * in its body + * @returns The door's JSON answer + */ + handleAttachmentDoor?(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 7f38cc7ca73..9c458fa2ce1 100644 --- a/packages/spec/src/contracts/core-service-contracts.test.ts +++ b/packages/spec/src/contracts/core-service-contracts.test.ts @@ -22,6 +22,7 @@ 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'; +import type { IPersonalViewDoorsService } from './personal-view-doors-service'; /** Compile-time assertion helper: fails to typecheck unless `T` is exactly `true`. */ type Expect = T; @@ -133,6 +134,10 @@ describe('slot → contract ledger beyond the enum', () => { expectTypeOf(getService('comments')).toEqualTypeOf(); expectTypeOf(getService('comments')?.handleCommentDoor) .toEqualTypeOf(); + // [#36506] The personal-view door's slot, probed for its one member. + expectTypeOf(getService('personal-views')).toEqualTypeOf(); + expectTypeOf(getService('personal-views')?.handlePersonalViewDoor) + .toEqualTypeOf(); // CONTROL: the same lookup resolves the slots that were already // mapped exactly as before. @@ -145,6 +150,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', 'comments', + 'personal-views', ] 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. @@ -157,7 +163,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(8); + expect(extra).toHaveLength(9); }); 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 e4b2b594f50..10c49f76787 100644 --- a/packages/spec/src/contracts/core-service-contracts.ts +++ b/packages/spec/src/contracts/core-service-contracts.ts @@ -44,6 +44,7 @@ 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'; +import type { IPersonalViewDoorsService } from './personal-view-doors-service'; /** * The evidenced slot → contract bindings. @@ -208,6 +209,17 @@ export interface ServiceSlotContracts extends CoreServiceContracts { * (`handleCommentDoor`). */ comments: ICommentDoorsService; + /** + * {@link IPersonalViewDoorsService}, registered by `@objectstack/plugin-auth`: + * `AuthPlugin` registers its personal-view delete door under + * `personal-views`, typed as this contract, so the runtime dispatcher's + * `/personal-views` domain reaches it on a kernel with no `http.server` + * (#36506). + * + * Every member is optional, so a reader still probes for the one it calls + * (`handlePersonalViewDoor`). + */ + 'personal-views': IPersonalViewDoorsService; } /** diff --git a/packages/spec/src/contracts/index.ts b/packages/spec/src/contracts/index.ts index 37ba4152690..847ad201da7 100644 --- a/packages/spec/src/contracts/index.ts +++ b/packages/spec/src/contracts/index.ts @@ -70,6 +70,10 @@ 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'; +// [#36506] The personal-view door's slot (`personal-views`) and the attachment +// doors served off `file-attachments`, for the dispatcher's hosted doors. +export * from './personal-view-doors-service.js'; +export * from './attachment-doors-service.js'; export * from './package-service.js'; export * from './knowledge-service.js'; export * from './knowledge-adapter.js'; diff --git a/packages/spec/src/contracts/personal-view-doors-service.test.ts b/packages/spec/src/contracts/personal-view-doors-service.test.ts new file mode 100644 index 00000000000..d21eec33c7d --- /dev/null +++ b/packages/spec/src/contracts/personal-view-doors-service.test.ts @@ -0,0 +1,46 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#36506] `IPersonalViewDoorsService.handlePersonalViewDoor`: the personal-view +// delete door, declared on the `personal-views` slot's contract +// transport-neutrally, so the runtime dispatcher can reach it on a kernel with +// no `http.server`. +// +// Type-level pins, the shape `comment-doors-service.test.ts` uses: the member is +// OPTIONAL, at the web-standard `(request: Request) => Promise` +// shape, the barrel exports the same contract, and the `personal-views` 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 { IPersonalViewDoorsService } from './personal-view-doors-service'; +import type { IPersonalViewDoorsService as FromBarrel, ServiceSlotContract } from './index'; + +type Eq = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; +type Assert = T; + +type HandlePersonalViewDoor = NonNullable; + +/** Optional: a service may omit it. A required member turns this alias red. */ +export type PersonalViewDoorIsOptional = Assert< + {} extends Pick ? true : false +>; + +/** One web-standard `Request` in: the whole input, with no execution context beside it. */ +export type PersonalViewDoorTakesOneRequest = Assert, [request: Request]>>; + +/** A web-standard `Response` out, asynchronously. */ +export type PersonalViewDoorAnswersAResponse = Assert, Promise>>; + +/** The barrel (`@objectstack/spec/contracts`) exports this contract, not a look-alike. */ +export type BarrelExportsTheContract = Assert>; + +/** The `personal-views` slot is typed by this contract, so the dispatcher's probe is typed. */ +export type PersonalViewsSlotIsTheContract = Assert, IPersonalViewDoorsService>>; + +describe('IPersonalViewDoorsService.handlePersonalViewDoor: the personal-view door, declared transport-neutrally', () => { + it('is optional: a service object without it still satisfies IPersonalViewDoorsService', () => { + const service: IPersonalViewDoorsService = {}; + + expect(service.handlePersonalViewDoor).toBeUndefined(); + }); +}); diff --git a/packages/spec/src/contracts/personal-view-doors-service.ts b/packages/spec/src/contracts/personal-view-doors-service.ts new file mode 100644 index 00000000000..89ad41a1469 --- /dev/null +++ b/packages/spec/src/contracts/personal-view-doors-service.ts @@ -0,0 +1,69 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * @objectstack/spec/contracts/personal-view-doors-service + * + * Cross-package contract for the personal-view door's service slot. The + * implementation lives in `@objectstack/plugin-auth`, which owns the + * `sys_personal_view` object, and is registered as the `personal-views` + * service. + * + * The door is `DELETE /api/v1/personal-views/:id`: a member removes a personal + * view they saved, and only their own, with no object-level delete grant. + * + * A self-hosted kernel serves it 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 runs `AuthPlugin` with `registerRoutes: false`), so the + * runtime dispatcher reaches it instead (#36506; the bridge the maintainer's + * ruling A on #22438 directs for every member of this class, as + * `ICommentDoorsService.handleCommentDoor` and `IWebhookService.handleRedeliver` + * are bridged). This slot is what the dispatcher forwards to. + */ + +/** + * The personal-view door's service: the occupant of the `personal-views` slot. + * + * Every member is optional. A kernel without `@objectstack/plugin-auth` leaves + * the slot empty, and a caller probes for the member it needs before calling + * it. + */ +export interface IPersonalViewDoorsService { + /** + * **The personal-view delete door, served transport-neutrally.** + * + * 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; a removal + * answers `{ id, deleted: true }`. + * - A request whose method and path are not the door's 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/personal-views/:id`). 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 `/personal-views` + * domain, which claims exactly the door's method and path shape and forwards + * the request unread. The path is not on the ADR-0069 auth-gate allow-list + * and the project-membership gate does not skip it, so on that shape the + * dispatcher door is stricter than the self-hosted mount, never looser. + * + * **Optional, and its absence is loud.** An empty `personal-views` slot or + * an absent member answers a typed `501`, ⛔ never the dispatcher's + * `404 ROUTE_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 and the personal view's id in its path + * @returns The door's JSON answer + */ + handlePersonalViewDoor?(request: Request): Promise; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b6a7e5340e2..661c919b393 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3427,6 +3427,9 @@ importers: '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects + '@objectstack/plugin-hono-server': + specifier: workspace:* + version: link:../../plugins/plugin-hono-server '@objectstack/service-cluster': specifier: workspace:* version: link:../service-cluster From f1b5901282f44cb6619e3f12fa2ff401a10a9b71 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:37:13 +0000 Subject: [PATCH 2/6] test(hosted): dispatcher-only door pins for personal views and attachments (WIP) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXs1Hrj1qNTkGdJbK1 --- .../dogfood/test/hosted-dispatcher.testkit.ts | 44 +++++++++++++++++++ ...member-attachment-baseline.dogfood.test.ts | 23 ++++++++++ .../personal-view-row-scope.dogfood.test.ts | 42 ++++++++++++++++++ .../src/domains/own-door-bridge.test.ts | 2 +- 4 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 packages/qa/dogfood/test/hosted-dispatcher.testkit.ts diff --git a/packages/qa/dogfood/test/hosted-dispatcher.testkit.ts b/packages/qa/dogfood/test/hosted-dispatcher.testkit.ts new file mode 100644 index 00000000000..2d473692591 --- /dev/null +++ b/packages/qa/dogfood/test/hosted-dispatcher.testkit.ts @@ -0,0 +1,44 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] The hosted door over a REAL composed kernel: a request answered by + * the runtime `HttpDispatcher` alone, the way a hosted tenant kernel is reached + * (its host's `createHonoApp` catch-all hands every unclaimed `/api/v1/*` + * request to `dispatch()`; the tenant kernel owns no `http.server`). + * + * The booted stack is self-hosted, so its own plugins also mount their doors + * on its `http.server`; this testkit never goes through that socket. What it + * drives is the dispatcher's domain for the path, which forwards to the + * kernel's service member — the path a hosted tenant request takes. Without + * that domain the answer here is the dispatcher's `404 ROUTE_NOT_FOUND`. + */ + +import { HttpDispatcher } from '@objectstack/runtime'; +import type { VerifyStack } from '@objectstack/verify'; + +/** A request through the dispatcher alone, answered as the wire would answer it. */ +export type HostedDoorCall = (token: string | undefined, method: string, path: string, body?: unknown) => Promise; + +/** The dispatcher-only door over `stack`'s kernel. `path` is the dispatcher path (no `/api/v1`). */ +export function hostedDispatcherDoor(stack: VerifyStack): HostedDoorCall { + const dispatcher = new HttpDispatcher(stack.kernel as never); + return async (token, method, path, body) => { + const request = new Request(`http://tenant.example/api/v1${path}`, { + method, + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + ...(body !== undefined ? { body: JSON.stringify(body) } : {}), + }); + const answer = await dispatcher.dispatch(method, path, undefined, {}, { request }); + if (answer.result instanceof Response) return answer.result; + if (answer.response) { + return new Response(JSON.stringify(answer.response.body), { + status: answer.response.status, + headers: { 'content-type': 'application/json' }, + }); + } + throw new Error(`the dispatcher answered ${method} ${path} with neither a Response nor an envelope`); + }; +} diff --git a/packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts b/packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts index e5637632e8c..7a79b391e3c 100644 --- a/packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts +++ b/packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts @@ -50,6 +50,7 @@ import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plug import { PermissionSetSchema } from '@objectstack/spec/security'; import { SysAttachment } from '@objectstack/platform-objects/audit'; import { attachmentsFixtureStack } from './fixtures/attachments-fixture.js'; +import { hostedDispatcherDoor } from './hosted-dispatcher.testkit.js'; const SYS = { isSystem: true } as const; const MEMBER_EMAIL = 'att-baseline-member@verify.test'; @@ -424,6 +425,28 @@ describe('a member attaches to the records they edit and sees the files of the r expect(await row(id)).toMatchObject({ id, uploaded_by: memberId }); }); + // [#36506] The same two doors on the hosted shape: the runtime dispatcher + // alone, the way a hosted tenant kernel with no `http.server` is reached, + // answers through its `/attachments` domain and the `file-attachments` + // service's member. Before that domain, both answered `404 ROUTE_NOT_FOUND`. + it('[hosted] on the dispatcher alone the uploader renames, then removes, their own attachment — and another member is refused the same 403', async () => { + const hosted = hostedDispatcherDoor(stack); + const id = await memberAttachment(); + + expect(await answerOf(await hosted(otherTok, 'DELETE', `/attachments/${id}`))).toMatchObject({ status: 403, code: 'PERMISSION_DENIED' }); + expect(await answerOf(await hosted(undefined, 'PATCH', `/attachments/${id}`, { file_name: 'anon.txt' }))).toMatchObject({ status: 401, code: 'UNAUTHENTICATED' }); + + const renamed = await answerOf(await hosted(memberTok, 'PATCH', `/attachments/${id}`, { file_name: ' renamed-on-hosted.txt ' })); + expect(renamed.status, JSON.stringify(renamed.body)).toBe(200); + expect(renamed.body).toEqual({ success: true, data: { id, file_name: 'renamed-on-hosted.txt' } }); + expect(await row(id)).toMatchObject({ id, file_name: 'renamed-on-hosted.txt' }); + + const removed = await answerOf(await hosted(memberTok, 'DELETE', `/attachments/${id}`)); + expect(removed.status, JSON.stringify(removed.body)).toBe(200); + expect(removed.body).toEqual({ success: true, data: { id, deleted: true } }); + expect(await row(id)).toBeNull(); + }); + it('an administrator still deletes any attachment through the data door; the door grants them nothing more', async () => { const id = await memberAttachment(); expect(await removeAs(adminTok, id)).toMatchObject({ status: 403, code: 'PERMISSION_DENIED' }); diff --git a/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts b/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts index e5d6dbb5abe..adaef8a4793 100644 --- a/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts +++ b/packages/qa/dogfood/test/personal-view-row-scope.dogfood.test.ts @@ -32,6 +32,12 @@ * still 403, because the door grants nothing (`member_default` is bound to * the `everyone` anchor and carries no delete bit, ADR-0090 D5). * + * - `[hosted]` the same door on the hosted shape (#36506): the runtime + * dispatcher alone, the way a hosted tenant kernel with no `http.server` is + * reached, answers through its `/personal-views` domain and the plugin's + * `personal-views` member: the owner removes their own view, another member + * gets the same unknown-id 404, anonymous the same 401. + * * - `[platform-admin]` the recorded boundary: `admin_full_access`'s bare * wildcard reads, edits and deletes a member's view through the generic * data door, as it does on `sys_user_preference` (the admin rescue path); @@ -45,6 +51,7 @@ import { type VerifyStack } from '@objectstack/verify'; import { bootShowcase } from './showcase-boot.js'; import { showcaseAppDefaultSecurity } from './showcase-security.js'; import { catalogPermissionSet } from './catalog-permission-set.js'; +import { hostedDispatcherDoor, type HostedDoorCall } from './hosted-dispatcher.testkit.js'; const OBJ = 'sys_personal_view'; const TARGET = 'showcase_project'; @@ -319,4 +326,39 @@ describe('sys_personal_view over REST: a reader\'s own named list views (ruling expect(await stillThere(row.id)).toBeTruthy(); }); }); + + describe('[hosted] the same door on the dispatcher alone: a hosted tenant kernel with no http.server (#36506)', () => { + let hosted: HostedDoorCall; + const door = (id: string) => `/personal-views/${id}`; + const stillThere = async (id: string) => ql.findOne(OBJ, { where: { id }, context: SYS }); + + beforeAll(() => { + hosted = hostedDispatcherDoor(stack); + }); + + it('[hosted] the owner removes their own view: 200 { id, deleted: true }, and the row is gone — not a route miss', async () => { + const row = await save(aliceTok, aliceId, 'Alice: removed on the hosted door'); + const r = await hosted(aliceTok, 'DELETE', door(row.id)); + expect(r.status, await r.clone().text()).toBe(200); + const body: any = await r.json(); + expect(body?.data ?? body).toEqual({ id: row.id, deleted: true }); + expect(await stillThere(row.id)).toBeFalsy(); + }); + + it('[hosted] another member: the same 404 RECORD_NOT_FOUND as the self-hosted door, and the row stays', async () => { + const row = await save(aliceTok, aliceId, 'Alice: not Bob\'s to remove on the hosted door'); + const r = await hosted(bobTok, 'DELETE', door(row.id)); + expect(r.status, await r.clone().text()).toBe(404); + expect(errorCodeOf(await r.json())).toBe('RECORD_NOT_FOUND'); + expect(await stillThere(row.id)).toBeTruthy(); + }); + + it('[hosted] anonymous: 401 UNAUTHENTICATED, and the row stays', async () => { + const row = await save(aliceTok, aliceId, 'Alice: not anonymous\'s to remove on the hosted door'); + const r = await hosted(undefined, 'DELETE', door(row.id)); + expect(r.status, await r.clone().text()).toBe(401); + expect(errorCodeOf(await r.json())).toBe('UNAUTHENTICATED'); + expect(await stillThere(row.id)).toBeTruthy(); + }); + }); }); diff --git a/packages/runtime/src/domains/own-door-bridge.test.ts b/packages/runtime/src/domains/own-door-bridge.test.ts index 52d0a71d3ce..da4e248348e 100644 --- a/packages/runtime/src/domains/own-door-bridge.test.ts +++ b/packages/runtime/src/domains/own-door-bridge.test.ts @@ -131,7 +131,7 @@ const FAMILIES: Family[] = [ prefix: '/attachments', doors: [ ['DELETE', '/attachments/att_1'], - ['PATCH', '/attachments/att_1', { name: 'renamed.pdf' }], + ['PATCH', '/attachments/att_1', { file_name: 'renamed.pdf' }], ], misses: [ ['GET', '/attachments/att_1'], From 4367ad4ad4a9416bc9b958c206be0cc271bad6d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:40:39 +0000 Subject: [PATCH 3/6] fix(hosted): ledgers, guards, changeset and member pins for the personal-view and attachment doors Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXs1Hrj1qNTkGdJbK1 --- .changeset/36506-own-row-doors-hosted.md | 19 ++++ .../src/personal-view-door-member.test.ts | 101 +++++++++++++++++ .../src/door-table-member.test.ts | 104 ++++++++++++++++++ .../dogfood/test/authz-conformance.matrix.ts | 24 +++- .../qa/dogfood/test/authz-conformance.test.ts | 4 + .../test/authz-ledger-population.baseline.ts | 5 +- packages/runtime/src/route-ledger.ts | 10 +- ...achment-removal-routes.integration.test.ts | 74 ++++++++++++- packages/spec/api-surface/contracts.json | 2 + packages/spec/export-origins/contracts.json | 2 + scripts/check-route-envelope.mjs | 11 ++ 11 files changed, 346 insertions(+), 10 deletions(-) create mode 100644 .changeset/36506-own-row-doors-hosted.md create mode 100644 packages/plugins/plugin-auth/src/personal-view-door-member.test.ts create mode 100644 packages/plugins/plugin-hono-server/src/door-table-member.test.ts diff --git a/.changeset/36506-own-row-doors-hosted.md b/.changeset/36506-own-row-doors-hosted.md new file mode 100644 index 00000000000..f07c966916d --- /dev/null +++ b/.changeset/36506-own-row-doors-hosted.md @@ -0,0 +1,19 @@ +--- +'@objectstack/spec': patch +'@objectstack/runtime': patch +'@objectstack/plugin-auth': patch +'@objectstack/service-storage': patch +'@objectstack/plugin-hono-server': patch +--- + +fix(hosted): deleting a personal view and removing or renaming an attachment work on a kernel with no `http.server` (a hosted tenant kernel) instead of answering 404 + +Clause-②: yes (widening) +Metadata-protocol: none + +`DELETE /api/v1/personal-views/:id` (plugin-auth) and `DELETE` / `PATCH /api/v1/attachments/:id` (service-storage) were mounted only on the kernel's `http.server`. A hosted tenant kernel owns no socket and registers no `http.server` (and runs `AuthPlugin` with `registerRoutes: false`), so the host's `createHonoApp` catch-all handed each request to the runtime dispatcher, which had no domain for them and answered `404 ROUTE_NOT_FOUND`: a member could not delete a personal view, or remove or rename an attachment, there. + +- `@objectstack/spec/contracts` declares `IPersonalViewDoorsService` (one optional, transport-neutral member, `handlePersonalViewDoor(request: Request): Promise`) and types the new `personal-views` service slot with it, and declares `IAttachmentDoorsService` (`handleAttachmentDoor`), which the existing `file-attachments` service implements beside `IFileAttachmentService`. A service without the member still satisfies either contract. +- `AuthPlugin` registers the `personal-views` service in `init()`, whatever `registerRoutes` says, and `StorageServicePlugin`'s `file-attachments` service gains `handleAttachmentDoor`. Each member runs the same registration 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` mounts are unchanged, and no path is mounted twice. The `personal-views` service name is now taken: a composition that registers its own `personal-views` service alongside `AuthPlugin` fails to boot with a duplicate-service error. `@objectstack/service-storage` now depends on `@objectstack/plugin-hono-server` at runtime (the private table is a `HonoHttpServer`). +- `@objectstack/plugin-hono-server` exports `createDoorTableMember(routes, mount)`, the private never-listening table both members are built on, and `matchDoorTableRoute`. +- The runtime dispatcher gains `/personal-views` and `/attachments` domains that claim exactly the door shapes and forward the request, body unread, to the REQUEST kernel's member (never the host kernel's scoped fallback). Every other shape under those prefixes keeps the dispatcher's `404 ROUTE_NOT_FOUND`. With no slot, or one without the member, the doors answer `501 NOT_IMPLEMENTED` naming the package that registers it. The doors stay behind the dispatcher's authentication and project-membership gates. diff --git a/packages/plugins/plugin-auth/src/personal-view-door-member.test.ts b/packages/plugins/plugin-auth/src/personal-view-door-member.test.ts new file mode 100644 index 00000000000..4a3615a9d3c --- /dev/null +++ b/packages/plugins/plugin-auth/src/personal-view-door-member.test.ts @@ -0,0 +1,101 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] `AuthPlugin` serves the personal-view delete door on its + * `personal-views` slot (`IPersonalViewDoorsService.handlePersonalViewDoor`), + * for a kernel with no `http.server`: a hosted tenant kernel runs the plugin + * with `registerRoutes: false` and owns no socket, and the runtime + * dispatcher's `/personal-views` domain forwards the request here. + * + * Every composition below is the real one: `AuthPlugin.init()` on a mock + * kernel context whose `data` service is the in-memory engine, + * `registerRoutes: false` (the per-environment kernel's shape). What this pins: + * 1. `init()` registers the slot with the member, whatever `registerRoutes` + * says, and nothing is mounted on any server; + * 2. the member runs the door: a request naming nobody answers the door's own + * `401 UNAUTHENTICATED`, byte for byte what the self-hosted mount answers; + * 3. a method or path that is not the door answers `404 ENDPOINT_NOT_FOUND`. + * + * The owner's removal and the refusals of everyone else are pinned on the + * real stack, on this member through the dispatcher alone, in the dogfood file + * `personal-view-row-scope.dogfood.test.ts` (`[hosted]`). + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import type { PluginContext } from '@objectstack/core'; +import type { IPersonalViewDoorsService } from '@objectstack/spec/contracts'; +import { HonoHttpServer } from '@objectstack/plugin-hono-server'; +import { AuthPlugin } from './auth-plugin'; +import { createMemoryEngine } from './impersonation-bearer-rotation.test'; + +const SECRET = 'test-secret-at-least-32-chars-long!!'; +const ORIGIN = 'http://localhost:3000'; + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +async function compose(options: Record = {}) { + const engine = createMemoryEngine(); + const ctx = { + registerService: vi.fn(), + getService: vi.fn((name: string) => { + if (name === 'data') return engine; + if (name === 'manifest') return { register: vi.fn() }; + return undefined; + }), + getServices: vi.fn(() => new Map()), + hook: vi.fn(), + trigger: vi.fn(), + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(), + } as unknown as PluginContext; + const plugin = new AuthPlugin({ secret: SECRET, baseUrl: ORIGIN, registerRoutes: false, ...options } as never); + await plugin.init(ctx); + const calls = (ctx.registerService as ReturnType).mock.calls; + const slot = calls.find(([name]) => name === 'personal-views')?.[1] as IPersonalViewDoorsService | undefined; + return { plugin, ctx, slot, calls }; +} + +const remove = (path = '/api/v1/personal-views/pv_1', method = 'DELETE') => + new Request(`${ORIGIN}${path}`, { method, headers: { 'content-type': 'application/json' } }); + +async function snapshot(res: Response) { + return { status: res.status, type: res.headers.get('content-type'), body: await res.text() }; +} + +describe('[#36506] AuthPlugin serves the personal-view door on its personal-views slot', () => { + it('init() registers the slot with handlePersonalViewDoor under registerRoutes: false, after auth', async () => { + const { slot, calls } = await compose(); + expect(typeof slot?.handlePersonalViewDoor).toBe('function'); + const names = calls.map(([name]) => name); + expect(names[0], 'auth stays the plugin\'s first service registration').toBe('auth'); + expect(names.filter((name) => name === 'personal-views')).toHaveLength(1); + }); + + it('a request naming nobody: the door\'s own 401 UNAUTHENTICATED, the same bytes the self-hosted mount answers', async () => { + const { plugin, ctx, slot } = await compose(); + const viaMember = await snapshot(await slot!.handlePersonalViewDoor!(remove())); + expect(viaMember.status).toBe(401); + expect(JSON.parse(viaMember.body)?.error?.code).toBe('UNAUTHENTICATED'); + + // The self-hosted face: the plugin's own mount, on a real server table. + const server = new HonoHttpServer(0); + (plugin as unknown as { mountPersonalViewDoor(http: unknown, c: PluginContext): void }).mountPersonalViewDoor(server, ctx); + const viaMount = await snapshot(await server.getRawApp().fetch(remove())); + expect(viaMember).toEqual(viaMount); + }); + + it('a method or path that is not the door: 404 ENDPOINT_NOT_FOUND', async () => { + const { slot } = await compose(); + for (const request of [remove('/api/v1/personal-views/pv_1', 'GET'), remove('/api/v1/personal-views'), remove('/api/v1/views/pv_1')]) { + const res = await slot!.handlePersonalViewDoor!(request); + expect(res.status, `${request.method} ${new URL(request.url).pathname}`).toBe(404); + expect((await res.json())?.error?.code).toBe('ENDPOINT_NOT_FOUND'); + } + }); +}); diff --git a/packages/plugins/plugin-hono-server/src/door-table-member.test.ts b/packages/plugins/plugin-hono-server/src/door-table-member.test.ts new file mode 100644 index 00000000000..eda31ce0252 --- /dev/null +++ b/packages/plugins/plugin-hono-server/src/door-table-member.test.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] `createDoorTableMember`: a plugin's `IHttpServer`-mounted doors as + * one transport-neutral `(request) => Promise` member, on a private + * `HonoHttpServer` that never listens. + * + * What this pins: + * 1. a request for one of the routes runs the mounted handler and answers + * exactly what the same registration answers on a `HonoHttpServer` the + * self-hosted way (one body, two faces); + * 2. a method or path outside the routes answers the transport's own + * `404 ENDPOINT_NOT_FOUND` without building the table or reaching a door; + * 3. the table is built once, on the first request that names a route. + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { IHttpServer } from '@objectstack/spec/contracts'; +import { HonoHttpServer } from './adapter'; +import { createDoorTableMember, matchDoorTableRoute, type DoorTableRoute } from './door-table-member'; + +const ROUTES: readonly DoorTableRoute[] = [ + { method: 'DELETE', route: '/api/v1/widgets/:id' }, + { method: 'PATCH', route: '/api/v1/widgets/:id' }, +]; + +/** A registrar shaped like a plugin's: two verbs at one route, echoing what they read. */ +function registrar(http: IHttpServer): void { + http.delete('/api/v1/widgets/:id', async (req, res) => { + res.status(200).json({ success: true, data: { id: req.params.id, deleted: true } }); + }); + http.patch('/api/v1/widgets/:id', async (req, res) => { + if (!req.headers['x-caller']) { + res.status(401).json({ success: false, error: { code: 'UNAUTHENTICATED', message: 'Sign in first.' } }); + return; + } + res.status(200).json({ success: true, data: { id: req.params.id, body: req.body } }); + }); +} + +const at = (method: string, path: string, init: RequestInit = {}) => + new Request(`http://tenant.example${path}`, { method, ...init }); + +async function snapshot(res: Response) { + return { status: res.status, type: res.headers.get('content-type'), body: await res.text() }; +} + +describe('[#36506] createDoorTableMember serves mounted doors as one transport-neutral member', () => { + it('a request for a route answers what the same registration answers on a HonoHttpServer', async () => { + const member = createDoorTableMember(ROUTES, registrar); + const selfHosted = new HonoHttpServer(0); + registrar(selfHosted); + + const requests = [ + () => at('DELETE', '/api/v1/widgets/w_1'), + () => at('PATCH', '/api/v1/widgets/w_1', { headers: { 'content-type': 'application/json' }, body: '{"name":"n"}' }), + () => at('PATCH', '/api/v1/widgets/w_1', { + headers: { 'content-type': 'application/json', 'x-caller': 'u_1' }, + body: '{"name":"n"}', + }), + ]; + for (const make of requests) { + const viaMember = await snapshot(await member(make())); + const viaMount = await snapshot(await selfHosted.getRawApp().fetch(make())); + expect(viaMember).toEqual(viaMount); + } + expect(JSON.parse((await snapshot(await member(requests[2]!()))).body)).toEqual({ + success: true, + data: { id: 'w_1', body: { name: 'n' } }, + }); + }); + + it('a method or path outside the routes answers 404 ENDPOINT_NOT_FOUND and never builds the table', async () => { + const mount = vi.fn(registrar); + const member = createDoorTableMember(ROUTES, mount); + for (const [method, path] of [ + ['GET', '/api/v1/widgets/w_1'], + ['PUT', '/api/v1/widgets/w_1'], + ['DELETE', '/api/v1/widgets'], + ['DELETE', '/api/v1/widgets/'], + ['DELETE', '/api/v1/widgets/w_1/x'], + ['DELETE', '/api/v1/gadgets/w_1'], + ] as const) { + const res = await member(at(method, path)); + expect(res.status, `${method} ${path}`).toBe(404); + expect(await res.json()).toEqual({ success: false, error: { code: 'ENDPOINT_NOT_FOUND', message: 'Not found' } }); + } + expect(mount).not.toHaveBeenCalled(); + }); + + it('the table is built once, on the first request that names a route', async () => { + const mount = vi.fn(registrar); + const member = createDoorTableMember(ROUTES, mount); + await member(at('DELETE', '/api/v1/widgets/a')); + await member(at('DELETE', '/api/v1/widgets/b')); + expect(mount).toHaveBeenCalledTimes(1); + }); + + it('matchDoorTableRoute names the route, method by method, one segment per parameter', () => { + expect(matchDoorTableRoute(ROUTES, 'delete', '/api/v1/widgets/w_1')).toEqual(ROUTES[0]); + expect(matchDoorTableRoute(ROUTES, 'PATCH', '/api/v1/widgets/w_1')).toEqual(ROUTES[1]); + expect(matchDoorTableRoute(ROUTES, 'DELETE', '/api/v1/widgets//')).toBeUndefined(); + }); +}); diff --git a/packages/qa/dogfood/test/authz-conformance.matrix.ts b/packages/qa/dogfood/test/authz-conformance.matrix.ts index b097113f9b7..4481526d934 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` (24 +// families) and `packages/runtime/src/route-ledger.ts` (26 // 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 42 ledger keys, 18 are classified by rows below (re-derived when the +// Of the 44 ledger keys, 20 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 `/comments` domain did, -// #36469, the `/webhooks/redeliver` domain did, #22755, `/approvals/act` did, #22576, and `/i18n` left the baseline, +// `/share-links` domains did under its first, the `/personal-views` and +// `/attachments` domains did, #36506, 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 @@ -439,6 +439,22 @@ export const AUTHZ_CONFORMANCE: AuthzPrimitive[] = [ 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.' }, + // #36506 — the `/personal-views` and `/attachments` dispatcher domains (ruling + // A on #22438, applied to the personal-view delete door and the attachment + // removal and rename doors), through the shared bridge `own-door-bridge.ts`. + // As `comment-doors-session`, the credential IS the session: each 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, for the reason `comment-doors-session` gives: each door + // writes one row after reading it AS THE CALLER, so it is no sibling read + // path around a data gate. + { id: 'own-row-doors-session', summary: 'Own-row doors (`DELETE /personal-views/:id`, `DELETE /attachments/:id`, `PATCH /attachments/:id`) — a signed-in member removes a personal view they saved, and removes or renames an attachment they uploaded; 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 personal-view and attachment removal doors) and service-storage/attachment-removal-routes.ts (the rename 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, the owner-only scope of sys_personal_view, the attachment read-visibility gate; unreadable = unknown 404), the owner column checked (403 PERMISSION_DENIED) or the update gate asked, then a system write attributed to the caller; reached through IPersonalViewDoorsService.handlePersonalViewDoor and IAttachmentDoorsService.handleAttachmentDoor by runtime/domains/own-door-bridge.ts (personal-views.ts, attachments.ts), which claims exactly the door shapes, forwards the transport\'s request UNREAD, reads the REQUEST kernel\'s 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. Each member runs the very registration its self-hosted mount runs (plugin-auth personal-view-door-member.ts, service-storage attachment-door-member.ts, over plugin-hono-server createDoorTableMember)', + covers: ['dispatcher-domain:route-ledger.ts:/personal-views', 'dispatcher-domain:route-ledger.ts:/attachments'], + note: 'The DISPATCHER domains only: on a self-hosted kernel the same paths are served from the plugins\' mounts on the kernel\'s http.server and never reach the dispatcher. Unit-, wire- and dogfood-proven: runtime domains/own-door-bridge.test.ts pins both domains on the real HttpDispatcher (the door shapes forwarded unread, every other method and path the ordinary miss, 501 for an absent slot or member, the slot read per request and only from the request kernel, the environment-scoped spelling forwarded at the wire path, a signed-in non-member and a gated session stopped before the member); personal-view-row-scope.dogfood.test.ts and member-attachment-baseline.dogfood.test.ts drive each door through a dispatcher alone over the real showcase and attachments stacks (`[hosted]`: the owner\'s removal and rename land, another member is refused as on the self-hosted door, anonymous is 401).' }, + // ── 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 8a0f9e0445a..1c7164ff7f2 100644 --- a/packages/qa/dogfood/test/authz-conformance.test.ts +++ b/packages/qa/dogfood/test/authz-conformance.test.ts @@ -1083,6 +1083,8 @@ describe('the ledger-sourced population and its baseline bite', () => { 'dispatcher-domain:route-ledger.ts:/analytics', // [#22576] classified by `approval-action-token`. 'dispatcher-domain:route-ledger.ts:/approvals/act', + // [#36506] classified by `own-row-doors-session`. + 'dispatcher-domain:route-ledger.ts:/attachments', 'dispatcher-domain:route-ledger.ts:/automation', // [#36469] classified by `comment-doors-session`. 'dispatcher-domain:route-ledger.ts:/comments', @@ -1097,6 +1099,8 @@ describe('the ledger-sourced population and its baseline bite', () => { // [ADR-0138 D2] classified by `anonymous-deny-notifications`. 'dispatcher-domain:route-ledger.ts:/notifications', 'dispatcher-domain:route-ledger.ts:/packages', + // [#36506] classified by `own-row-doors-session`. + 'dispatcher-domain:route-ledger.ts:/personal-views', // [ADR-0138 D2] classified by `anonymous-deny-share-links`. 'dispatcher-domain:route-ledger.ts:/share-links', // [ADR-0138 D2, second slice] classified by `anonymous-deny-ui`. diff --git a/packages/qa/dogfood/test/authz-ledger-population.baseline.ts b/packages/qa/dogfood/test/authz-ledger-population.baseline.ts index 9deac778c69..c31dd53d1c1 100644 --- a/packages/qa/dogfood/test/authz-ledger-population.baseline.ts +++ b/packages/qa/dogfood/test/authz-ledger-population.baseline.ts @@ -100,8 +100,9 @@ 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`, `/webhooks/redeliver` and `/comments` (#36469) were - // never enumerated here: they arrived classified. The other 9 domains are here. + // `/approvals/act`, `/webhooks/redeliver`, `/comments` (#36469), + // `/personal-views` and `/attachments` (#36506) 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/runtime/src/route-ledger.ts b/packages/runtime/src/route-ledger.ts index 807a68e8486..23360d0d32e 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 153 rows. + * CENSUS (generated): this list holds 156 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 @@ -736,6 +736,14 @@ export const ROUTE_LEDGER: readonly RouteLedgerEntry[] = [ { 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' }, + // ── personal-view and attachment doors (the hosted doors) ──────────────── + { route: 'DELETE /personal-views/:id', domain: '/personal-views', disposition: 'server-only', + note: 'the personal-view delete door: a member removes a personal view they saved, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the REQUEST kernel\'s personal-views slot (IPersonalViewDoorsService.handlePersonalViewDoor; plugin-auth registers it in init, whatever registerRoutes says), read per request and never from the host kernel\'s scoped fallback, 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-auth\'s own mount on its http.server, which never passes through the dispatcher. NOT JS-SDK surface here: the SDK gap is acknowledged once, on the mount\'s own ledger row (plugin-auth personal-view-route-ledger.ts). Pinned in `domains/own-door-bridge.test.ts`' }, + { route: 'DELETE /attachments/:id', domain: '/attachments', disposition: 'server-only', + note: 'the uploader\'s removal door: a member removes an attachment they uploaded, and only theirs, with no object delete grant. Forwarded with its body UNREAD to the REQUEST kernel\'s file-attachments service (IAttachmentDoorsService.handleAttachmentDoor; service-storage builds it in init), read per request and never from the host kernel\'s scoped fallback, and the member\'s Response returned as it is: the member runs the very mount the self-hosted kernel runs, so the caller, every refusal and every answer are the mount\'s. Same credential, preamble-gate, absence and body notes as the personal-view row. This is the door for a kernel with no http.server; a self-hosted kernel serves the same path from service-storage\'s own mount on its http.server, and a hosted host\'s storage bridge covers /api/v1/storage only. NOT JS-SDK surface here: the mount\'s own ledger rows (service-storage attachment-removal-route-ledger.ts) carry the disposition. Pinned in `domains/own-door-bridge.test.ts`' }, + { route: 'PATCH /attachments/:id', domain: '/attachments', disposition: 'server-only', + note: 'the rename door: rename an attachment from the Attachments panel, body exactly { file_name }. Same forwarding, credential, absence and door notes as the removal 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' }, diff --git a/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts b/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts index e4abe6e4b5c..980463e737e 100644 --- a/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts +++ b/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts @@ -83,6 +83,7 @@ type Answer = { status: number; body: any }; interface DoorStack { engine: ObjectQL; routes: Map; + services: Map; rootDir: string; caseId: string; } @@ -93,7 +94,7 @@ interface DoorStack { * a read middleware refuses DAVE every user row: the fixture's stand-in for a * reader without user-read rights. */ -async function bootDoorStack(): Promise { +async function bootDoorStack(opts: { httpServer?: boolean } = {}): Promise { const routes = new Map(); const services = new Map(); let rootDir: string; @@ -136,7 +137,10 @@ async function bootDoorStack(): Promise { hook: (event: string, fn: () => unknown) => { phases.set(event, [...(phases.get(event) ?? []), fn]); }, }; ctx.registerService('objectql', dataEngine); - ctx.registerService('http-server', { + // [#36506] `httpServer: false` is the hosted tenant kernel's shape: no + // `http-server`, so nothing is mounted and the doors are the + // `file-attachments` service's member. + if (opts.httpServer !== false) ctx.registerService('http-server', { get: mount('GET'), post: mount('POST'), put: mount('PUT'), delete: mount('DELETE'), patch: mount('PATCH'), use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), @@ -241,7 +245,7 @@ async function bootDoorStack(): Promise { for (const fn of phases.get('kernel:bootstrapped') ?? []) await fn(); caseId = String((await engine.insert(CASE, { name: 'the case', organization_id: ORG }, { context: SYS })).id); - return { engine, routes, rootDir, caseId }; + return { engine, routes, services, rootDir, caseId }; } async function stopDoorStack(stack: DoorStack | undefined): Promise { @@ -521,3 +525,67 @@ describe('an attachment read serves its uploader as the reader may read that use expect(JSON.stringify(row)).not.toContain('Alice Uploader'); }); }); + +// [#36506] The same two doors on a kernel with no `http.server` (a hosted +// tenant kernel): nothing is mounted, and the `file-attachments` service's +// `handleAttachmentDoor` — what the runtime dispatcher's `/attachments` domain +// forwards to — runs the very mount the `http.server` branch runs, over the +// same kernel. Driven with web-standard requests, as the dispatcher hands them. +describe('[#36506] with no http.server, the file-attachments member serves the removal and rename doors', () => { + let stack: DoorStack; + const { attachmentRow, seedFile, attachAs } = doorFixture(() => stack); + const member = () => { + const service = stack.services.get('file-attachments') as { handleAttachmentDoor?: (r: Request) => Promise }; + expect(typeof service?.handleAttachmentDoor, 'the file-attachments service carries the door member').toBe('function'); + return service.handleAttachmentDoor!; + }; + const send = async (method: string, id: string, user: string | null, body?: unknown): Promise => { + const res = await member()(new Request(`http://tenant.example/api/v1/attachments/${id}`, { + method, + headers: { 'content-type': 'application/json', ...(user === null ? {} : { 'x-test-user': user }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + })); + return { status: res.status, body: await res.json() }; + }; + + beforeAll(async () => { + stack = await bootDoorStack({ httpServer: false }); + }); + + afterAll(async () => { + await stopDoorStack(stack); + }); + + it('mounts nothing: the kernel has no http-server', () => { + expect(stack.routes.size).toBe(0); + }); + + it('the uploader renames, then removes, their own attachment: 200 each, and the store follows', async () => { + await seedFile('f_hosted_own', ALICE); + const id = await attachAs(ALICE, 'f_hosted_own'); + + const renamed = await send('PATCH', id, ALICE, { file_name: ' hosted-name.txt ' }); + expect(renamed, JSON.stringify(renamed.body)).toEqual({ status: 200, body: { success: true, data: { id, file_name: 'hosted-name.txt' } } }); + expect((await attachmentRow(id))?.file_name).toBe('hosted-name.txt'); + + const removed = await send('DELETE', id, ALICE); + expect(removed, JSON.stringify(removed.body)).toEqual({ status: 200, body: { success: true, data: { id, deleted: true } } }); + expect(await attachmentRow(id)).toBeFalsy(); + }); + + it('another member is refused 403 PERMISSION_DENIED, nobody named is 401, and the row stays', async () => { + await seedFile('f_hosted_kept', ALICE); + const id = await attachAs(ALICE, 'f_hosted_kept'); + + expect(await send('DELETE', id, BOB)).toMatchObject({ status: 403, body: { error: { code: 'PERMISSION_DENIED' } } }); + expect(await send('DELETE', id, null)).toMatchObject({ status: 401, body: { error: { code: 'UNAUTHENTICATED' } } }); + expect(await send('PATCH', id, null, { file_name: 'x.txt' })).toMatchObject({ status: 401, body: { error: { code: 'UNAUTHENTICATED' } } }); + expect(await attachmentRow(id)).toMatchObject({ id, uploaded_by: ALICE }); + }); + + it('a method or path that is neither door answers 404 ENDPOINT_NOT_FOUND without reaching a door', async () => { + const res = await member()(new Request('http://tenant.example/api/v1/attachments/a_1', { method: 'GET' })); + expect(res.status).toBe(404); + expect((await res.json())?.error?.code).toBe('ENDPOINT_NOT_FOUND'); + }); +}); diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 6b7e9a78ae1..1da6daed2c4 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -166,6 +166,7 @@ "IAnalyticsService (interface)", "IAppLifecycleService (interface)", "IApprovalService (interface)", + "IAttachmentDoorsService (interface)", "IAuditCheckpointSigner (interface)", "IAuditCheckpointSink (interface)", "IAuthService (interface)", @@ -203,6 +204,7 @@ "IObjectQLEngine (interface)", "IOwnershipQueueService (interface)", "IPackageService (interface)", + "IPersonalViewDoorsService (interface)", "IPluginLifecycleEvents (interface)", "IPluginValidator (interface)", "IPubSub (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 951a7fc810f..ddf59dddc53 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -166,6 +166,7 @@ "IAnalyticsService": "src/contracts/analytics-service.ts#IAnalyticsService (interface)", "IAppLifecycleService": "src/contracts/app-lifecycle-service.ts#IAppLifecycleService (interface)", "IApprovalService": "src/contracts/approval-service.ts#IApprovalService (interface)", + "IAttachmentDoorsService": "src/contracts/attachment-doors-service.ts#IAttachmentDoorsService (interface)", "IAuditCheckpointSigner": "src/contracts/audit-checkpoint.ts#IAuditCheckpointSigner (interface)", "IAuditCheckpointSink": "src/contracts/audit-checkpoint.ts#IAuditCheckpointSink (interface)", "IAuthService": "src/contracts/auth-service.ts#IAuthService (interface)", @@ -203,6 +204,7 @@ "IObjectQLEngine": "src/contracts/objectql-engine.ts#IObjectQLEngine (interface)", "IOwnershipQueueService": "src/contracts/ownership-queue-service.ts#IOwnershipQueueService (interface)", "IPackageService": "src/contracts/package-service.ts#IPackageService (interface)", + "IPersonalViewDoorsService": "src/contracts/personal-view-doors-service.ts#IPersonalViewDoorsService (interface)", "IPluginLifecycleEvents": "src/contracts/plugin-lifecycle-events.ts#IPluginLifecycleEvents (interface)", "IPluginValidator": "src/contracts/plugin-validator.ts#IPluginValidator (interface)", "IPubSub": "src/contracts/cluster-service.ts#IPubSub (interface)", diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 4dbb959988a..ad572f9775c 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -1099,6 +1099,9 @@ const DISPATCHER_DOMAINS = { // refusal it makes itself — the two 501s, the sanitised 500s — goes through // `deps.error`. 'approvals.ts': { handBuilt: 0 }, + // [#36506] The `/attachments` bridge: two lines naming what + // `own-door-bridge.ts` forwards; it builds no answer of its own. + 'attachments.ts': { handBuilt: 0 }, // [ADR-0150 D5] Kind 1: the `405` for a shape the domain serves under // another verb must carry an `Allow:` header (`deps.error` takes none), as // `/actions`' does; its body is `buildApiError`'s declared envelope. @@ -1142,11 +1145,19 @@ const DISPATCHER_DOMAINS = { // its one answer, `newSimilarTargetRefusalAnswer`, goes through `deps.error`. 'new-similar-target.ts': { handBuilt: 0 }, 'notifications.ts': { handBuilt: 0 }, + // [#36506] Not a domain: the shared bridge `/personal-views` and + // `/attachments` call. The member's own JSON `Response` is handed back as + // `result`, and every answer the bridge makes itself — the ordinary miss, + // the two 501s, the sanitised 500s — goes through `deps.routeNotFound` / + // `deps.error`. + 'own-door-bridge.ts': { handBuilt: 0 }, 'packages.ts': { handBuilt: 0 }, // The `/security` domain's permission-set clone door (ADR-0126 §7.1), beside // the activation door. Every answer goes through `deps.success` / // `deps.error` / `deps.errorFromThrown`. 'permission-set-clone.ts': { handBuilt: 0 }, + // [#36506] The `/personal-views` bridge, as `attachments.ts`. + 'personal-views.ts': { handBuilt: 0 }, 'security.ts': { handBuilt: 0 }, // No `storage.ts` — the `/storage` domain was retired in #4087 (it called // the storage contract with the wrong arity and read a Buffer as a From 0e6be1a2506e4a57895cc6cbf0b94db2e5ce9b5d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:44:35 +0000 Subject: [PATCH 4/6] fix(hosted): plugin-auth declares plugin-hono-server as a runtime dependency, and the unmatched-door pin typechecks The personal-view member imports plugin-hono-server, so it moves from devDependencies to dependencies. The storage hosted pin reads the 404 envelope through toMatchObject. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXs1Hrj1qNTkGdJbK1 --- .changeset/36506-own-row-doors-hosted.md | 2 +- packages/plugins/plugin-auth/package.json | 2 +- .../src/attachment-removal-routes.integration.test.ts | 2 +- pnpm-lock.yaml | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.changeset/36506-own-row-doors-hosted.md b/.changeset/36506-own-row-doors-hosted.md index f07c966916d..94dc83b82a5 100644 --- a/.changeset/36506-own-row-doors-hosted.md +++ b/.changeset/36506-own-row-doors-hosted.md @@ -14,6 +14,6 @@ Metadata-protocol: none `DELETE /api/v1/personal-views/:id` (plugin-auth) and `DELETE` / `PATCH /api/v1/attachments/:id` (service-storage) were mounted only on the kernel's `http.server`. A hosted tenant kernel owns no socket and registers no `http.server` (and runs `AuthPlugin` with `registerRoutes: false`), so the host's `createHonoApp` catch-all handed each request to the runtime dispatcher, which had no domain for them and answered `404 ROUTE_NOT_FOUND`: a member could not delete a personal view, or remove or rename an attachment, there. - `@objectstack/spec/contracts` declares `IPersonalViewDoorsService` (one optional, transport-neutral member, `handlePersonalViewDoor(request: Request): Promise`) and types the new `personal-views` service slot with it, and declares `IAttachmentDoorsService` (`handleAttachmentDoor`), which the existing `file-attachments` service implements beside `IFileAttachmentService`. A service without the member still satisfies either contract. -- `AuthPlugin` registers the `personal-views` service in `init()`, whatever `registerRoutes` says, and `StorageServicePlugin`'s `file-attachments` service gains `handleAttachmentDoor`. Each member runs the same registration 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` mounts are unchanged, and no path is mounted twice. The `personal-views` service name is now taken: a composition that registers its own `personal-views` service alongside `AuthPlugin` fails to boot with a duplicate-service error. `@objectstack/service-storage` now depends on `@objectstack/plugin-hono-server` at runtime (the private table is a `HonoHttpServer`). +- `AuthPlugin` registers the `personal-views` service in `init()`, whatever `registerRoutes` says, and `StorageServicePlugin`'s `file-attachments` service gains `handleAttachmentDoor`. Each member runs the same registration 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` mounts are unchanged, and no path is mounted twice. The `personal-views` service name is now taken: a composition that registers its own `personal-views` service alongside `AuthPlugin` fails to boot with a duplicate-service error. `@objectstack/plugin-auth` and `@objectstack/service-storage` now depend on `@objectstack/plugin-hono-server` at runtime (the private table is a `HonoHttpServer`; plugin-auth previously listed it as a dev dependency only). - `@objectstack/plugin-hono-server` exports `createDoorTableMember(routes, mount)`, the private never-listening table both members are built on, and `matchDoorTableRoute`. - The runtime dispatcher gains `/personal-views` and `/attachments` domains that claim exactly the door shapes and forward the request, body unread, to the REQUEST kernel's member (never the host kernel's scoped fallback). Every other shape under those prefixes keeps the dispatcher's `404 ROUTE_NOT_FOUND`. With no slot, or one without the member, the doors answer `501 NOT_IMPLEMENTED` naming the package that registers it. The doors stay behind the dispatcher's authentication and project-membership gates. diff --git a/packages/plugins/plugin-auth/package.json b/packages/plugins/plugin-auth/package.json index 61035ed0202..2464fa61a90 100644 --- a/packages/plugins/plugin-auth/package.json +++ b/packages/plugins/plugin-auth/package.json @@ -55,6 +55,7 @@ "@noble/hashes": "^2.4.0", "@objectstack/core": "workspace:*", "@objectstack/platform-objects": "workspace:*", + "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/rest": "workspace:*", "@objectstack/service-messaging": "workspace:*", "@objectstack/spec": "workspace:*", @@ -68,7 +69,6 @@ "@objectstack/driver-sql": "workspace:*", "@objectstack/formula": "workspace:*", "@objectstack/objectql": "workspace:*", - "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/plugin-security": "workspace:*", "@objectstack/service-cache": "workspace:*", "@objectstack/service-cluster": "workspace:*", diff --git a/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts b/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts index 980463e737e..0c47d09367a 100644 --- a/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts +++ b/packages/services/service-storage/src/attachment-removal-routes.integration.test.ts @@ -586,6 +586,6 @@ describe('[#36506] with no http.server, the file-attachments member serves the r it('a method or path that is neither door answers 404 ENDPOINT_NOT_FOUND without reaching a door', async () => { const res = await member()(new Request('http://tenant.example/api/v1/attachments/a_1', { method: 'GET' })); expect(res.status).toBe(404); - expect((await res.json())?.error?.code).toBe('ENDPOINT_NOT_FOUND'); + expect(await res.json()).toMatchObject({ success: false, error: { code: 'ENDPOINT_NOT_FOUND' } }); }); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 661c919b393..be6e97f9df8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1951,6 +1951,9 @@ importers: '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects + '@objectstack/plugin-hono-server': + specifier: workspace:* + version: link:../plugin-hono-server '@objectstack/rest': specifier: workspace:* version: link:../../rest @@ -1985,9 +1988,6 @@ importers: '@objectstack/objectql': specifier: workspace:* version: link:../../objectql - '@objectstack/plugin-hono-server': - specifier: workspace:* - version: link:../plugin-hono-server '@objectstack/plugin-security': specifier: workspace:* version: link:../plugin-security From 93007b05e91813b339066ee3a9ac8db061cd9807 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:00:11 +0000 Subject: [PATCH 5/6] test(hosted): the wire half for the personal-view and attachment doors on the hosted shape createHonoApp over a kernel with no http.server, the real AuthPlugin composed with registerRoutes: false, the real StorageServicePlugin, security and sharing, and real better-auth sessions: the owner removes their own personal view and renames then removes their own attachment (200 each, store follows), another member and anonymous are refused, the refusals are byte-identical to the self-hosted mount, and a kernel without service-storage answers 501. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXs1Hrj1qNTkGdJbK1 --- packages/qa/http-conformance/package.json | 4 + .../hono-own-row-doors.conformance.test.ts | 320 ++++++++++++++++++ packages/qa/http-conformance/vitest.config.ts | 10 + pnpm-lock.yaml | 12 + 4 files changed, 346 insertions(+) create mode 100644 packages/qa/http-conformance/src/hono-own-row-doors.conformance.test.ts diff --git a/packages/qa/http-conformance/package.json b/packages/qa/http-conformance/package.json index a63da903eef..3c23cce79d1 100644 --- a/packages/qa/http-conformance/package.json +++ b/packages/qa/http-conformance/package.json @@ -19,13 +19,17 @@ "@objectstack/hono": "workspace:*", "@objectstack/mcp": "workspace:*", "@objectstack/objectql": "workspace:*", + "@objectstack/platform-objects": "workspace:*", "@objectstack/plugin-approvals": "workspace:*", "@objectstack/plugin-audit": "workspace:*", "@objectstack/plugin-auth": "workspace:*", "@objectstack/plugin-hono-server": "workspace:*", + "@objectstack/plugin-security": "workspace:*", + "@objectstack/plugin-sharing": "workspace:*", "@objectstack/plugin-webhooks": "workspace:*", "@objectstack/runtime": "workspace:*", "@objectstack/service-messaging": "workspace:*", + "@objectstack/service-storage": "workspace:*", "@objectstack/spec": "workspace:*", "@types/node": "^26.6.5", "typescript": "^6.0.3", diff --git a/packages/qa/http-conformance/src/hono-own-row-doors.conformance.test.ts b/packages/qa/http-conformance/src/hono-own-row-doors.conformance.test.ts new file mode 100644 index 00000000000..5cf0de65450 --- /dev/null +++ b/packages/qa/http-conformance/src/hono-own-row-doors.conformance.test.ts @@ -0,0 +1,320 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#36506] The personal-view and attachment doors on the hosted shape: + * `createHonoApp` over a kernel with NO `http.server` (a hosted tenant kernel + * owns no socket), the REAL `AuthPlugin` composed with + * `registerRoutes: false` (the per-environment kernel's shape), the REAL + * `StorageServicePlugin`, the real security and sharing plugins, over a real + * store. Every credential is a real better-auth session, signed in through the + * same transport. + * + * Before the `/personal-views` and `/attachments` dispatcher domains existed, + * 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 asserts no door answers a route miss any more. + * + * What this pins: + * 1. on the hosted shape, a member removes their own personal view, and + * renames then removes their own attachment, each answered by the door + * with 200 and each landing in the store; another member and an anonymous + * caller are refused by the door's own rule, and the row stays; + * 2. the two doors answer the same refusals with the same bytes, because the + * member runs the very registration the self-hosted mount runs; + * 3. a hosted kernel without `@objectstack/service-storage` answers the + * attachment doors with a typed `501 NOT_IMPLEMENTED`, never a route miss. + * + * The domains' own claim, gates and faults are pinned on the real dispatcher + * in `packages/runtime/src/domains/own-door-bridge.test.ts`. + */ + +import { promises as fs } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; +import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; +import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; +import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; +import { StorageServicePlugin } from '@objectstack/service-storage'; +import { AppPlugin, DefaultDatasourcePlugin } from '@objectstack/runtime'; +import { createHonoApp } from '@objectstack/hono'; +import type { IHttpServer } from '@objectstack/spec/contracts'; + +const BOOT_TIMEOUT = 180_000; +const ORIGIN = 'http://localhost:3000'; +const API = '/api/v1'; +const SYS = { isSystem: true } as const; +const SECRET = 'own-row-doors-conformance-secret-0001'; +const NOTE = 'ord_note'; +const ALICE = { email: 'alice@own-row-doors.test', password: 'alice-own-row-doors-password-36506', name: 'Alice' }; +const BOB = { email: 'bob@own-row-doors.test', password: 'bob-own-row-doors-password-36506', name: 'Bob' }; + +const APP: any = { + manifest: { id: 'com.conformance.ownrowdoors', name: 'Own-row doors conformance', version: '1.0.0' }, + objects: [{ name: NOTE, label: 'Note', enable: { files: true }, fields: { title: { type: 'text', label: 'Title' } } }], +}; + +/** One booted composition and the requests it answers. */ +interface Door { + kernel: any; + engine: any; + /** One request at `path` (the full wire path), through this composition's door. */ + send: (path: string, init?: RequestInit) => Promise; + aliceToken: string; + bobToken: string; + aliceId: string; + bobId: string; + rootDir: string; +} + +/** + * One kernel. `hosted` is the tenant kernel's shape: no `http.server`, auth + * composed with `registerRoutes: false`, every request through + * `createHonoApp`'s catch-all. Without `hosted`, the self-hosted shape: the + * plugins mount their doors on the kernel's own server, over a real socket. + * `storage: false` leaves the `file-attachments` slot empty. + */ +async function boot(opts: { hosted: boolean; storage?: boolean }): Promise { + const rootDir = join(tmpdir(), `os-own-row-doors-${Date.now()}-${Math.random().toString(36).slice(2)}`); + await fs.mkdir(rootDir, { recursive: true }); + + const kernel: any = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new DefaultDatasourcePlugin({ driver: 'sqlite-wasm', config: { filename: ':memory:' } })); + if (!opts.hosted) await kernel.use(new HonoServerPlugin({ port: 0, cors: false })); + await kernel.use(new AppPlugin(APP)); + await kernel.use(new PlatformObjectsPlugin()); + await kernel.use(new AuthPlugin({ secret: SECRET, ...(opts.hosted ? { registerRoutes: false } : {}) } as never)); + await kernel.use(new SecurityPlugin(appSecurityPluginOptions(APP))); + await kernel.use(new SharingServicePlugin()); + if (opts.storage !== false) { + await kernel.use(new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false })); + } + await kernel.bootstrap(); + + let send: Door['send']; + if (opts.hosted) { + let server: unknown; + try { server = kernel.getService('http.server'); } catch { server = undefined; } + expect(server, 'the hosted shape owns no socket').toBeUndefined(); + const app = createHonoApp({ kernel, prefix: API, cors: false }); + send = async (path, init) => app.request(`${ORIGIN}${path}`, init); + } else { + const server = kernel.getService('http.server') as IHttpServer; + const base = `http://127.0.0.1:${server.getPort!()}`; + send = (path, init) => fetch(`${base}${path}`, init); + } + + const engine = await kernel.getServiceAsync('objectql'); + const auth = await kernel.getServiceAsync('auth'); + const door: Door = { kernel, engine, send, aliceToken: '', bobToken: '', aliceId: '', bobId: '', rootDir }; + door.aliceToken = await provision(door, auth, ALICE); + door.bobToken = await provision(door, auth, BOB); + door.aliceId = await userIdOf(engine, ALICE.email); + door.bobId = await userIdOf(engine, BOB.email); + return door; +} + +async function stop(door: Door | undefined): Promise { + if (!door) return; + await Promise.race([door.kernel.shutdown(), new Promise((resolve) => setTimeout(resolve, 10_000))]); + await fs.rm(door.rootDir, { recursive: true, force: true }); +} + +/** A member provisioned through the operator door, then signed in, both through the composition's own door. */ +async function provision(door: Door, auth: any, who: { email: string; password: string; name: string }): Promise { + const ticket = auth.stageOperatorProvisioning(who.email); + let signUp: Response; + try { + signUp = await door.send(`${API}/auth/sign-up/email`, { + method: 'POST', headers: { 'Content-Type': 'application/json', origin: ORIGIN }, + body: JSON.stringify({ ...who, [AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD]: ticket }), + }); + } finally { + auth.clearOperatorProvisioning(who.email); + } + expect(signUp.status, await signUp.clone().text()).toBe(200); + const signIn = await door.send(`${API}/auth/sign-in/email`, { + method: 'POST', headers: { 'Content-Type': 'application/json', origin: ORIGIN }, + body: JSON.stringify({ email: who.email, password: who.password }), + }); + expect(signIn.status, await signIn.clone().text()).toBe(200); + return ((await signIn.json()) as { token: string }).token; +} + +async function userIdOf(engine: any, email: string): Promise { + const row = await engine.findOne('sys_user', { where: { email }, context: SYS }); + expect(row?.id, `${email} provisioned`).toBeTruthy(); + return String(row.id); +} + +const as = (token: string | undefined, init: RequestInit = {}): RequestInit => ({ + ...init, + headers: { 'content-type': 'application/json', origin: ORIGIN, ...(token ? { Authorization: `Bearer ${token}` } : {}) }, +}); + +/** The record a data-door answer carries, in either envelope spelling. */ +const recordOf = (body: any) => body?.data?.record ?? body?.record ?? body?.data ?? body; + +/** Save a personal view as Alice, through the data door. */ +async function saveView(door: Door, label: string): Promise { + const res = await door.send(`${API}/data/sys_personal_view`, as(door.aliceToken, { + method: 'POST', + body: JSON.stringify({ + user_id: door.aliceId, object_name: NOTE, label, + config: { type: 'grid', data: { provider: 'object', object: NOTE }, columns: ['title'] }, + }), + })); + expect(res.status, await res.clone().text()).toBe(201); + const id = recordOf(await res.json())?.id; + expect(id, 'the saved view carries an id').toBeTruthy(); + return String(id); +} + +/** An attachment Alice uploaded, on a note of hers: the file row as a committed upload leaves it, attached through the data door. */ +async function attachAsAlice(door: Door, tag: string): Promise { + const note = await door.send(`${API}/data/${NOTE}`, as(door.aliceToken, { method: 'POST', body: JSON.stringify({ title: `note ${tag}` }) })); + expect(note.status, await note.clone().text()).toBe(201); + const noteRow = recordOf(await note.json()); + const fileId = `f_${tag}`; + await door.engine.insert('sys_file', { + id: fileId, key: `attachments/${fileId}.txt`, name: `${fileId}.txt`, scope: 'attachments', + status: 'committed', owner_id: door.aliceId, organization_id: noteRow.organization_id, + }, { context: SYS }); + const res = await door.send(`${API}/data/sys_attachment`, as(door.aliceToken, { + method: 'POST', + body: JSON.stringify({ parent_object: NOTE, parent_id: String(noteRow.id), file_id: fileId, file_name: `${fileId}.txt` }), + })); + expect(res.status, await res.clone().text()).toBe(201); + const id = recordOf(await res.json())?.id; + expect(id, 'the attachment carries an id').toBeTruthy(); + return String(id); +} + +const stored = (door: Door, object: string, id: string) => door.engine.findOne(object, { where: { id }, context: SYS }); + +/** 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('[#36506] the personal-view and attachment doors answer on the hosted shape (createHonoApp, no http.server, AuthPlugin registerRoutes: false)', () => { + let door: Door; + beforeAll(async () => { door = await boot({ hosted: true }); }, BOOT_TIMEOUT); + afterAll(async () => { await stop(door); }); + + it('no door answers a route miss (ROUTE_NOT_FOUND or ENDPOINT_NOT_FOUND) any more', async () => { + const requests: Array<[string, RequestInit]> = [ + [`${API}/personal-views/pv_missing`, as(undefined, { method: 'DELETE' })], + [`${API}/attachments/att_missing`, as(undefined, { method: 'DELETE' })], + [`${API}/attachments/att_missing`, as(undefined, { method: 'PATCH', body: JSON.stringify({ file_name: 'x.txt' }) })], + ]; + 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}`).toBe(401); + } + }); + + it('the owner removes their own personal view: 200 { id, deleted: true }, and the row is gone', async () => { + const id = await saveView(door, 'Alice: removed on the hosted shape'); + + const res = await door.send(`${API}/personal-views/${id}`, as(door.aliceToken, { method: 'DELETE' })); + + expect(res.status, await res.clone().text()).toBe(200); + expect(await res.json()).toEqual({ success: true, data: { id, deleted: true } }); + expect(await stored(door, 'sys_personal_view', id)).toBeFalsy(); + }); + + it('another member is answered 404 RECORD_NOT_FOUND for a view that is not theirs, anonymous 401, and the row stays', async () => { + const id = await saveView(door, 'Alice: kept on the hosted shape'); + + const bob = await door.send(`${API}/personal-views/${id}`, as(door.bobToken, { method: 'DELETE' })); + expect(bob.status, await bob.clone().text()).toBe(404); + expect(((await bob.json()) as any).error.code).toBe('RECORD_NOT_FOUND'); + + const anonymous = await door.send(`${API}/personal-views/${id}`, as(undefined, { method: 'DELETE' })); + expect(anonymous.status).toBe(401); + expect(((await anonymous.json()) as any).error.code).toBe('UNAUTHENTICATED'); + + expect(await stored(door, 'sys_personal_view', id)).toMatchObject({ id, user_id: door.aliceId }); + }); + + it('the uploader renames, then removes, their own attachment: 200 each, and the store follows', async () => { + const id = await attachAsAlice(door, 'renamed_then_removed'); + + const renamed = await door.send(`${API}/attachments/${id}`, as(door.aliceToken, { method: 'PATCH', body: JSON.stringify({ file_name: ' hosted-name.txt ' }) })); + expect(renamed.status, await renamed.clone().text()).toBe(200); + expect(await renamed.json()).toEqual({ success: true, data: { id, file_name: 'hosted-name.txt' } }); + expect((await stored(door, 'sys_attachment', id))?.file_name).toBe('hosted-name.txt'); + + const removed = await door.send(`${API}/attachments/${id}`, as(door.aliceToken, { method: 'DELETE' })); + expect(removed.status, await removed.clone().text()).toBe(200); + expect(await removed.json()).toEqual({ success: true, data: { id, deleted: true } }); + expect(await stored(door, 'sys_attachment', id)).toBeFalsy(); + }); + + it('anonymous is answered 401 on both attachment doors, and the row stays', async () => { + const id = await attachAsAlice(door, 'kept_anonymous'); + + for (const init of [as(undefined, { method: 'DELETE' }), as(undefined, { method: 'PATCH', body: JSON.stringify({ file_name: 'x.txt' }) })]) { + const res = await door.send(`${API}/attachments/${id}`, init); + expect(res.status, `${init.method}`).toBe(401); + expect(((await res.json()) as any).error.code).toBe('UNAUTHENTICATED'); + } + expect(await stored(door, 'sys_attachment', id)).toMatchObject({ id, file_name: `f_kept_anonymous.txt` }); + }); +}); + +describe('[#36506] both doors answer the same refusal with the same bytes', () => { + let hosted: Door; + let selfHosted: Door; + beforeAll(async () => { + hosted = await boot({ hosted: true }); + selfHosted = await boot({ hosted: false }); + }, BOOT_TIMEOUT); + afterAll(async () => { await stop(hosted); await stop(selfHosted); }); + + it('the anonymous refusals and a refused rename body are byte-identical at the mount and at the hosted door', async () => { + const cases: Array<[label: string, path: string, init: (d: Door) => RequestInit]> = [ + ['anonymous personal-view delete', `${API}/personal-views/pv_missing`, () => as(undefined, { method: 'DELETE' })], + ['anonymous attachment delete', `${API}/attachments/att_missing`, () => as(undefined, { method: 'DELETE' })], + ['anonymous attachment rename', `${API}/attachments/att_missing`, () => as(undefined, { method: 'PATCH', body: '{"file_name":"x.txt"}' })], + ['a rename body that is not JSON', `${API}/attachments/att_missing`, (d) => as(d.aliceToken, { method: 'PATCH', body: '{file_name:' })], + ]; + for (const [label, path, init] of cases) { + const viaHosted = await snapshot(await hosted.send(path, init(hosted))); + const viaMount = await snapshot(await selfHosted.send(path, init(selfHosted))); + expect(viaHosted.status, label).not.toBe(404); + expect(viaHosted, label).toEqual(viaMount); + } + }); +}); + +describe('[#36506] a hosted kernel without @objectstack/service-storage answers a typed 501, never a route miss', () => { + let door: Door; + beforeAll(async () => { door = await boot({ hosted: true, storage: false }); }, BOOT_TIMEOUT); + afterAll(async () => { await stop(door); }); + + it('each attachment door: 501 NOT_IMPLEMENTED naming the package', async () => { + for (const init of [as(door.aliceToken, { method: 'DELETE' }), as(door.aliceToken, { method: 'PATCH', body: '{"file_name":"x.txt"}' })]) { + const res = await door.send(`${API}/attachments/att_1`, init); + const body = (await res.json()) as any; + expect(res.status, `${init.method}`).toBe(501); + expect(body.error.code).toBe('NOT_IMPLEMENTED'); + expect(body.error.message).toContain('@objectstack/service-storage'); + } + }); +}); diff --git a/packages/qa/http-conformance/vitest.config.ts b/packages/qa/http-conformance/vitest.config.ts index badfc4f497d..a0038e30957 100644 --- a/packages/qa/http-conformance/vitest.config.ts +++ b/packages/qa/http-conformance/vitest.config.ts @@ -62,6 +62,16 @@ export default defineConfig({ find: /^@objectstack\/plugin-auth$/, replacement: path.resolve(__dirname, '../../plugins/plugin-auth/src/index.ts'), }, + // `hono-own-row-doors.conformance.test.ts` boots the REAL + // StorageServicePlugin on both of its doors — the self-hosted mount on + // `http.server` and the `handleAttachmentDoor` member behind the + // dispatcher's `/attachments` domain — so its verdict about either is + // about this checkout's storage source. (Its personal-view half rides the + // plugin-auth entry above.) + { + find: /^@objectstack\/service-storage$/, + replacement: path.resolve(__dirname, '../../services/service-storage/src/index.ts'), + }, // `hono-mcp-stateless-verbs.conformance.test.ts` serves `/api/v1/mcp` // from the REAL `MCPServerRuntime` on both doors, so its verdict on which // verbs the transport answers is about this checkout's mcp source. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be6e97f9df8..3eeb547a2db 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2517,6 +2517,9 @@ importers: '@objectstack/objectql': specifier: workspace:* version: link:../../objectql + '@objectstack/platform-objects': + specifier: workspace:* + version: link:../../platform-objects '@objectstack/plugin-approvals': specifier: workspace:* version: link:../../plugins/plugin-approvals @@ -2529,6 +2532,12 @@ importers: '@objectstack/plugin-hono-server': specifier: workspace:* version: link:../../plugins/plugin-hono-server + '@objectstack/plugin-security': + specifier: workspace:* + version: link:../../plugins/plugin-security + '@objectstack/plugin-sharing': + specifier: workspace:* + version: link:../../plugins/plugin-sharing '@objectstack/plugin-webhooks': specifier: workspace:* version: link:../../plugins/plugin-webhooks @@ -2538,6 +2547,9 @@ importers: '@objectstack/service-messaging': specifier: workspace:* version: link:../../services/service-messaging + '@objectstack/service-storage': + specifier: workspace:* + version: link:../../services/service-storage '@objectstack/spec': specifier: workspace:* version: link:../../spec From 8163e388bfd40b203f04433aa8038a680d64b03b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:04:39 +0000 Subject: [PATCH 6/6] test(hosted): the own-row doors conformance file reads platform objects, security and sharing from source Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbXs1Hrj1qNTkGdJbK1 --- packages/qa/http-conformance/vitest.config.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/qa/http-conformance/vitest.config.ts b/packages/qa/http-conformance/vitest.config.ts index a0038e30957..b16e896f5c8 100644 --- a/packages/qa/http-conformance/vitest.config.ts +++ b/packages/qa/http-conformance/vitest.config.ts @@ -72,6 +72,21 @@ export default defineConfig({ find: /^@objectstack\/service-storage$/, replacement: path.resolve(__dirname, '../../services/service-storage/src/index.ts'), }, + // The same file composes the platform objects, plugin-security and + // plugin-sharing around the doors: the identity, grant and sharing + // rules the doors read as the caller, so they are this checkout's too. + { + find: /^@objectstack\/platform-objects\/plugin$/, + replacement: path.resolve(__dirname, '../../platform-objects/src/plugin.ts'), + }, + { + find: /^@objectstack\/plugin-security$/, + replacement: path.resolve(__dirname, '../../plugins/plugin-security/src/index.ts'), + }, + { + find: /^@objectstack\/plugin-sharing$/, + replacement: path.resolve(__dirname, '../../plugins/plugin-sharing/src/index.ts'), + }, // `hono-mcp-stateless-verbs.conformance.test.ts` serves `/api/v1/mcp` // from the REAL `MCPServerRuntime` on both doors, so its verdict on which // verbs the transport answers is about this checkout's mcp source.