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
12 changes: 12 additions & 0 deletions .changeset/36469-comment-doors-serve-host.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/runtime': patch
---

fix(comments): unreact, resolve and own-comment delete answer on an `objectstack serve` / `objectstack dev` multi-tenant host instead of `404 ENDPOINT_NOT_FOUND`

Clause-②: no
Metadata-protocol: none

On a multi-tenant host composed the way the framework CLI composes one (`HonoServerPlugin` + `DispatcherPlugin`, a `kernel-resolver`, and no `createHonoApp` catch-all), the three comment doors, `DELETE /api/v1/comments/reactions/:id`, `PUT /api/v1/comments/:id/resolution` and `DELETE /api/v1/comments/:id`, never reached the dispatcher's `/comments` domain: `AuditPlugin` runs on the per-environment kernel, which owns no `http.server`, and `DispatcherPlugin`'s fallback seam handed on only domain-decided and app-endpoint paths. So the transport answered its own `404 ENDPOINT_NOT_FOUND`.

`DispatcherPlugin`'s fallback now hands exactly those three method and path shapes (bare or environment-scoped) to `dispatch()` on a multi-tenant host, with the transport's request rebuilt as a Web `Request` carrying its original body, and writes the door's `Response` back unchanged. Any other shape still writes nothing, so the transport's own miss stands; a single-kernel host keeps today's answers; and the fallback runs only after every mounted route missed, so a kernel that mounts the doors itself is never reached here.
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
* which this kernel does not have, and the catch-all's `dispatch()` had no
* domain for them. The first pin here asserts no door answers a route miss
* any more, door by door. (The card's hosted reading spelled the miss
* `ENDPOINT_NOT_FOUND`, the transport's own; this tree does not explain that
* spelling, so the pin refuses both.)
* `ENDPOINT_NOT_FOUND`, the transport's own: item 4 below explains it.)
*
* What this pins:
* 1. on the hosted shape, a member removes their own reaction, resolves and
Expand All @@ -22,20 +21,28 @@
* anonymous refusal and a refused body — because the member runs the very
* registration the self-hosted mount runs;
* 3. a hosted kernel without plugin-audit answers a typed
* `501 NOT_IMPLEMENTED`, never a route miss.
* `501 NOT_IMPLEMENTED`, never a route miss;
* 4. on the `objectstack serve` / `objectstack dev` host shape (HonoServerPlugin
* + DispatcherPlugin on the host, a kernel-resolver, NO catch-all) the same
* member answers, with the same bytes, through DispatcherPlugin's fallback.
* Without that fallback arm this shape answered the transport's own
* `{"success":false,"error":{"code":"ENDPOINT_NOT_FOUND","message":"Not found"}}`,
* byte for byte the card's hosted reading (cloud's local rig runs
* `apps/objectos` under `objectstack dev`).
*
* The domain's own claim, gates and faults are pinned on the real dispatcher
* in `packages/runtime/src/domains/comments.test.ts`.
*/

import { describe, it, expect, afterEach } from 'vitest';
import { ObjectKernel } from '@objectstack/core';
import { ObjectKernel, LiteKernel } from '@objectstack/core';
import type { Plugin, PluginContext } from '@objectstack/core';
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm';
import { AuditPlugin } from '@objectstack/plugin-audit';
import { createHonoApp } from '@objectstack/hono';
import { createDispatcherPlugin } from '@objectstack/runtime';
import type { IHttpServer } from '@objectstack/spec/contracts';
import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-organization.testkit.js';

Expand Down Expand Up @@ -284,3 +291,97 @@ describe('[#36469] a hosted kernel without plugin-audit answers a typed 501, nev
}
});
});

/**
* [#36469] The `objectstack serve` / `objectstack dev` host shape: the HOST
* kernel has `HonoServerPlugin` and `DispatcherPlugin` but NO `createHonoApp`
* catch-all, and a `kernel-resolver` places each request on a per-environment
* kernel that runs the real AuditPlugin with no `http.server` (cloud's local
* rig runs this way, `apps/objectos` under `objectstack dev`). Before
* `DispatcherPlugin`'s fallback handed the door shapes on, every request below
* answered the transport's own `404 ENDPOINT_NOT_FOUND`: the card's literal
* hosted reading.
*/
async function serveShapedHost() {
const tenant = await hostedDoor();
// A host kernel with no data engine of its own, as the runtime's
// multi-tenant fallback tests compose one: the doors' data is the tenant's.
const host = new LiteKernel({ logger: { level: 'silent' } } as any);
liveKernels.push(host as unknown as ObjectKernel);
await host.use(new HonoServerPlugin({ port: 0, cors: false }));
await host.use(new TestAuth());
await host.use({
name: 'test.comment-doors-kernel-resolver',
version: '1.0.0',
type: 'standard',
init: async (ctx: PluginContext) => {
ctx.registerService('kernel-resolver', {
resolveKernel: async (context: any) => {
const headers = context?.request?.headers;
const envId = typeof headers?.get === 'function' ? headers.get(ENVIRONMENT) : headers?.[ENVIRONMENT];
if (envId !== TENANT_ENV) return undefined;
context.environmentId = TENANT_ENV;
return tenant.kernel;
},
});
},
} as Plugin);
await host.use(createDispatcherPlugin({ prefix: PREFIX, securityHeaders: false }) as any);
await host.bootstrap();
const base = `http://127.0.0.1:${host.getService<IHttpServer>('http.server').getPort!()}`;
const send = (path: string, init: RequestInit = {}) =>
fetch(`${base}${path}`, { ...init, headers: { ...(init.headers as Record<string, string>), [ENVIRONMENT]: TENANT_ENV } });
return { ...tenant, send };
}

const ENVIRONMENT = 'x-environment-id';
const TENANT_ENV = 'env_tenant';

describe('[#36469] the comment doors answer on an `objectstack serve`-shaped multi-tenant host (no catch-all)', () => {
it('a member removes their own reaction: 200, and the row is gone on the tenant', async () => {
const door = await serveShapedHost();
const { reactionId } = await door.seed();

const res = await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' }));

expect(await res.clone().text()).not.toContain('ENDPOINT_NOT_FOUND');
expect(res.status, await res.clone().text()).toBe(200);
expect(await res.json()).toEqual({ success: true, data: { id: reactionId, deleted: true } });
expect(await door.stored(REACTION, reactionId)).toBeNull();
});

it('a member resolves and reopens a thread, then removes their own comment', async () => {
const door = await serveShapedHost();
const { commentId, reactionId } = await door.seed();
const resolution = `${PREFIX}/comments/${commentId}/resolution`;

const resolved = await door.send(resolution, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: true }) }));
expect(resolved.status, await resolved.clone().text()).toBe(200);
expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeTruthy();

const reopened = await door.send(resolution, as(ALICE, { method: 'PUT', body: JSON.stringify({ resolved: false }) }));
expect(reopened.status, await reopened.clone().text()).toBe(200);
expect((await door.stored(COMMENT, commentId) as any)?.is_resolved).toBeFalsy();

await door.send(`${PREFIX}/comments/reactions/${reactionId}`, as(ALICE, { method: 'DELETE' }));
const removed = await door.send(`${PREFIX}/comments/${commentId}`, as(ALICE, { method: 'DELETE' }));
expect(removed.status, await removed.clone().text()).toBe(200);
expect(await door.stored(COMMENT, commentId)).toBeNull();
});

it('the anonymous refusal and the refused body are byte-identical to the self-hosted mount', async () => {
const host = await serveShapedHost();
const selfHosted = await selfHostedDoor();
const cases: Array<[label: string, path: string, init: RequestInit]> = [
['anonymous unreact', `${PREFIX}/comments/reactions/rx_missing`, as(undefined, { method: 'DELETE' })],
['a body that is not JSON', `${PREFIX}/comments/c_missing/resolution`, as(ALICE, { method: 'PUT', body: '{resolved:' })],
['a body that is not exactly { resolved }', `${PREFIX}/comments/c_missing/resolution`, as(ALICE, { method: 'PUT', body: '{"resolved":"yes"}' })],
];
for (const [label, path, init] of cases) {
const viaHost = await snapshot(await host.send(path, init));
const viaMount = await snapshot(await selfHosted.send(path, init));
expect(viaHost.status, label).not.toBe(404);
expect(viaHost, label).toEqual(viaMount);
}
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#36469] The comment doors on a multi-tenant host composed the way
* `objectstack serve` / `objectstack dev` composes one: `HonoServerPlugin`
* plus `DispatcherPlugin` on the HOST kernel, a `kernel-resolver` that places
* each request on a per-environment kernel, and NO `createHonoApp` catch-all.
*
* `plugin-audit` runs on the tenant kernels, which own no `http.server`, so
* its doors are never mounted on the host's route table. #36539 gave them a
* `/comments` dispatcher domain, but on this shape nothing routes the request
* into `dispatch()`: `DispatcherPlugin`'s fallback seam hands on only
* domain-decided and app-endpoint paths, so the transport's own
* `404 ENDPOINT_NOT_FOUND` stood — the card's exact hosted reading.
*/

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { LiteKernel, Plugin, PluginContext } from '@objectstack/core';
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
import type { IHttpServer } from '@objectstack/spec/contracts';

import { createDispatcherPlugin } from './dispatcher-plugin.js';
// Paid during collection, not inside a case's clock: `standalone-stack.ts`,
// reached through the dispatcher, loads it lazily (`check:test-source-alias`).
import '@objectstack/metadata';

/** Every request the tenant's comment-doors member received. */
const served: Array<{ tenant: string; method: string; path: string; body?: string }> = [];

function makeTenantKernel(tenant: string) {
const services: Record<string, unknown> = {
comments: {
handleCommentDoor: async (request: Request) => {
const body = request.method === 'PUT' ? await request.text() : undefined;
served.push({ tenant, method: request.method, path: new URL(request.url).pathname, ...(body !== undefined ? { body } : {}) });
return Response.json(
{ success: true, data: { servedBy: tenant } },
{ headers: { 'x-door-answer': tenant, 'cache-control': 'no-store' } },
);
},
},
};
return {
__tag: tenant,
getServiceAsync: async (name: string) => services[name] ?? null,
getService: (name: string) => services[name] ?? null,
context: { getService: (name: string) => services[name] ?? null },
};
}

const TENANTS: Record<string, ReturnType<typeof makeTenantKernel>> = {
'env-1': makeTenantKernel('env-1'),
};

function tenantResolverPlugin(): Plugin {
return {
name: 'com.objectstack.test.kernel-resolver',
version: '1.0.0',
init: async (ctx: PluginContext) => {
ctx.registerService('kernel-resolver', {
resolveKernel: async (context: any) => {
// Fetch `Headers` or a plain record, as the cloud host's
// resolver reads them (`headerAccessor`, objectos-runtime).
const headers = context?.request?.headers;
const envId: string | undefined = typeof headers?.get === 'function'
? headers.get('x-environment-id') ?? undefined
: headers?.['x-environment-id'];
const kernel = envId ? TENANTS[envId] : undefined;
if (!kernel) return undefined;
context.environmentId = envId;
return kernel;
},
});
},
};
}

let kernel: LiteKernel | undefined;
let baseUrl = '';

beforeAll(async () => {
kernel = new LiteKernel();
kernel.use(new HonoServerPlugin({ port: 0, cors: false }));
kernel.use(tenantResolverPlugin());
kernel.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false }));
await kernel.bootstrap();
const httpServer = kernel.getService<IHttpServer>('http.server');
baseUrl = `http://127.0.0.1:${httpServer.getPort!()}`;
}, 60_000);

afterAll(async () => {
if (!kernel) return;
await Promise.race([kernel.shutdown(), new Promise<void>((resolve) => setTimeout(resolve, 10_000))]);
}, 60_000);

/** The envelope fields these assertions read. */
type Answer = { success?: boolean; data?: unknown; error?: { code?: string } };

const SIGNED_IN = { 'X-Environment-Id': 'env-1', 'content-type': 'application/json' };

describe('[#36469] comment doors on an `objectstack serve`-shaped multi-tenant host', () => {
it.each([
['DELETE', '/api/v1/comments/reactions/rxn_1'],
['PUT', '/api/v1/comments/cmt_1/resolution'],
['DELETE', '/api/v1/comments/cmt_1'],
])('%s %s reaches the placed tenant\'s comments member', async (method, path) => {
served.length = 0;
const res = await fetch(`${baseUrl}${path}`, {
method,
headers: SIGNED_IN,
...(method === 'PUT' ? { body: JSON.stringify({ resolved: true }) } : {}),
});
const body = await res.json() as Answer;
// Before the bridge: the transport's own unmatched answer, the card's reading.
expect(body?.error?.code).not.toBe('ENDPOINT_NOT_FOUND');
expect(res.status).toBe(200);
expect(body).toEqual({ success: true, data: { servedBy: 'env-1' } });
// The member's own headers reach the client.
expect(res.headers.get('x-door-answer')).toBe('env-1');
expect(res.headers.get('cache-control')).toBe('no-store');
expect(served).toEqual([
{ tenant: 'env-1', method, path, ...(method === 'PUT' ? { body: JSON.stringify({ resolved: true }) } : {}) },
]);
}, 60_000);

it('serves the environment-scoped spelling at the door\'s wire path', async () => {
served.length = 0;
const res = await fetch(`${baseUrl}/api/v1/environments/env-1/comments/reactions/rxn_2`, {
method: 'DELETE',
headers: SIGNED_IN,
});
expect(res.status).toBe(200);
expect(served).toEqual([{ tenant: 'env-1', method: 'DELETE', path: '/api/v1/comments/reactions/rxn_2' }]);
}, 60_000);

it.each([
['DELETE', '/api/v1/comments/reactions/rxn_1/extra'],
['PUT', '/api/v1/comments/cmt_1'],
['GET', '/api/v1/comments/reactions/rxn_1'],
])('%s %s is not a door: the transport\'s own miss stands', async (method, path) => {
served.length = 0;
const res = await fetch(`${baseUrl}${path}`, { method, headers: SIGNED_IN });
const body = await res.json() as Answer;
expect(res.status).toBe(404);
expect(body?.error?.code).toBe('ENDPOINT_NOT_FOUND');
expect(served).toEqual([]);
}, 60_000);

it('an unplaced request is never served out of a tenant kernel', async () => {
served.length = 0;
const res = await fetch(`${baseUrl}/api/v1/comments/reactions/rxn_1`, { method: 'DELETE' });
expect(res.status).not.toBe(200);
expect(served).toEqual([]);
}, 60_000);
});

describe('[#36469] a single-kernel host keeps today\'s answer', () => {
let single: LiteKernel | undefined;
let singleUrl = '';
beforeAll(async () => {
single = new LiteKernel();
single.use(new HonoServerPlugin({ port: 0, cors: false }));
single.use(createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false }));
await single.bootstrap();
singleUrl = `http://127.0.0.1:${single.getService<IHttpServer>('http.server').getPort!()}`;
}, 60_000);
afterAll(async () => {
if (!single) return;
await Promise.race([single.shutdown(), new Promise<void>((resolve) => setTimeout(resolve, 10_000))]);
}, 60_000);

it('no kernel-resolver: an unmounted door is the transport\'s miss, not handed to dispatch()', async () => {
const res = await fetch(`${singleUrl}/api/v1/comments/reactions/rxn_1`, { method: 'DELETE' });
expect(res.status).toBe(404);
expect(((await res.json()) as Answer)?.error?.code).toBe('ENDPOINT_NOT_FOUND');
}, 60_000);
});
25 changes: 25 additions & 0 deletions packages/runtime/src/dispatcher-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { deferRequestBody } from './deferred-request-body.js';
import { validationFailureDetails, VALIDATION_FAILED_STATUS } from './validation-failure.js';
import { buildApiError } from './error-envelope.js';
import { appEndpointMountPrefix, isAppEndpointPath, runAppEndpointStep } from './api-endpoint-step.js';
import { matchForwardedDoorPath, sendWebResponse, toWebRequest } from './forwarded-door-fallback.js';
import type { EndpointExecutorDeps } from './endpoint-executor.js';
import { callData } from './action-execution.js';
import { createEndpointRateLimiterRegistry } from './endpoint-policy.js';
Expand Down Expand Up @@ -2470,6 +2471,30 @@ export function createDispatcherPlugin(config: DispatcherPluginConfig = {}): Plu
sendResult(result, res);
return;
}
// ── [#36469] A forwarded door on a multi-tenant host ────
// A door whose plugin lives on the per-environment
// kernel (the comment doors) is mounted on no route table
// here, and this host has no `createHonoApp` catch-all to
// carry it into `dispatch()`. Exact door shapes only, so
// a miss still writes nothing; multi-tenant only, so a
// single-kernel host keeps today's answers byte for byte.
// See `forwarded-door-fallback.ts`.
if (dispatcher.isMultiTenantHost() && matchForwardedDoorPath(req.method, path, prefix)) {
const result = await dispatcher.dispatch(
req.method,
path.substring(prefix.length),
undefined,
req.query,
{ request: await toWebRequest(req) },
prefix,
);
if (result.handled && result.result instanceof Response) {
await sendWebResponse(result.result, res);
return;
}
sendResult(result, res);
return;
}
// ── Scoping test FIRST, before any resolution ────────
// Everything below costs something (a kernel resolve, a
// session lookup), and an unmatched request that is not
Expand Down
Loading
Loading