Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/36506-own-row-doors-hosted.md
Original file line number Diff line number Diff line change
@@ -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<Response>`) 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/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.
2 changes: 1 addition & 1 deletion packages/plugins/plugin-auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand All @@ -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:*",
Expand Down
29 changes: 25 additions & 4 deletions packages/plugins/plugin-auth/src/auth-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -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}`);
};
}

/**
Expand Down
101 changes: 101 additions & 0 deletions packages/plugins/plugin-auth/src/personal-view-door-member.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = {}) {
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<typeof vi.fn>).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');
}
});
});
40 changes: 40 additions & 0 deletions packages/plugins/plugin-auth/src/personal-view-door-member.ts
Original file line number Diff line number Diff line change
@@ -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<IPersonalViewDoorsService> {
const member = createDoorTableMember(PERSONAL_VIEW_DOOR_ROUTES, (http: IHttpServer) =>
registerPersonalViewRoutes(http, deps()),
);
return { handlePersonalViewDoor: member };
}
104 changes: 104 additions & 0 deletions packages/plugins/plugin-hono-server/src/door-table-member.test.ts
Original file line number Diff line number Diff line change
@@ -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<Response>` 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();
});
});
Loading
Loading