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
18 changes: 18 additions & 0 deletions .changeset/22420-console-drift-responder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@objectstack/cli': patch
---

fix(cli): a dev server that refuses a drifted Console answers `503` at `/_console/` naming the rebuild, instead of a bare `404` (#22420)

Clause-②: no

A refused Console mount answers `503` naming the remedy instead of the router's bare `404` on the same routes, as the not-built position already does. No accepted input, key or export changes.

`os dev` refuses to mount a Console whose built `dist/.objectui-sha` differs from the repository's `.objectui-sha` pin. The terminal printed the refusal, but nothing was mounted, so `GET /_console/` and `GET /` answered `404 ENDPOINT_NOT_FOUND`, the same answer as a wrong URL. That boot now mounts the same routes as the not-built answer:

- `GET /_console/` and every path under it answer `503` (`text/plain`, `no-store`). The body is the refusal's own text: both objectui SHAs, why the stale build is refused, `pnpm objectui:build`, and the `OS_ALLOW_CONSOLE_DRIFT=1` escape hatch. The pin file is named without its absolute path.
- `GET /` and `GET /_console` redirect to `/_console/`, as they do when the Console is served.

The same answer now covers an install where `@objectstack/console` does not resolve at all. That boot used to print nothing and mount nothing. It now prints ``Console package `@objectstack/console` not found``, followed by the reinstall sentence an install with no `dist/` already gets. `/_console/` answers `503` saying the Console is not installed.

`--no-ui` and `--no-console` still mount nothing, so those routes answer `404`.
39 changes: 21 additions & 18 deletions packages/cli/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ import {
formatConsoleDistMissingWarning,
createConsoleStaticPlugin,
createConsoleNotBuiltPlugin,
createConsoleShaDriftRefusalPlugin,
createRuntimeAssetsPlugin,
type ConsoleShaDrift,
} from '../utils/console.js';
Expand Down Expand Up @@ -4954,25 +4955,27 @@ export default class Serve extends Command {
// present, it owns the root `/` redirect (preferred default UI). It is
// optional — we only mount it when the package resolves and a
// pre-built `dist/` is present, and — in dev — only when that build
// matches the repo's objectui pin (#7752). A package that resolves
// with no `dist/` gets the not-built answer on those same routes, so
// `/_console/` names the remedy the boot warning prints instead of
// answering a bare 404.
if (consolePath) {
if (consoleWillMount) {
if (consoleDrift) {
console.warn(chalk.yellow(formatConsoleShaDriftWarning(consoleDrift)));
}
const consoleDistPath = path.join(consolePath, 'dist');
await kernel.use(createConsoleStaticPlugin(consoleDistPath, { isDev }));
trackPlugin('ConsoleUI');
} else if (refusedForDrift && consoleDrift) {
console.error(chalk.red(formatConsoleShaDriftRefusal(consoleDrift)));
} else {
console.warn(chalk.yellow(formatConsoleDistMissingWarning(consolePath)));
await kernel.use(createConsoleNotBuiltPlugin(consolePath));
trackPlugin('ConsoleNotBuilt');
// matches the repo's objectui pin (#7752). Every other boot that wants
// a Console gets a responder on those same routes instead, so
// `/_console/` answers `503` naming the remedy its boot message prints
// rather than a bare 404 (#22420): the drift refusal; a package with no
// `dist/`; no package at all (`consolePath` null). Only `--no-ui` /
// `--no-console` mount nothing, by the operator's own choice.
if (consolePath && consoleWillMount) {
if (consoleDrift) {
console.warn(chalk.yellow(formatConsoleShaDriftWarning(consoleDrift)));
}
const consoleDistPath = path.join(consolePath, 'dist');
await kernel.use(createConsoleStaticPlugin(consoleDistPath, { isDev }));
trackPlugin('ConsoleUI');
} else if (refusedForDrift && consoleDrift) {
console.error(chalk.red(formatConsoleShaDriftRefusal(consoleDrift)));
await kernel.use(createConsoleShaDriftRefusalPlugin(consoleDrift));
trackPlugin('ConsoleShaDriftRefused');
} else if (consoleEnabled) {
console.warn(chalk.yellow(formatConsoleDistMissingWarning(consolePath)));
await kernel.use(createConsoleNotBuiltPlugin(consolePath));
trackPlugin('ConsoleNotBuilt');
}
}

Expand Down
26 changes: 19 additions & 7 deletions packages/cli/src/utils/console-route-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,28 +113,36 @@ export interface ConsoleRouteLedgerEntry {
}

export const CONSOLE_ROUTE_LEDGER: readonly ConsoleRouteLedgerEntry[] = [
// ── console SPA static serving (createConsoleStaticPlugin) ─────────
// ── console SPA static serving (createConsoleStaticPlugin), and the ────
// ── responders mounted on the same routes when the Console is refused ──
// ── (createConsoleNotBuiltPlugin, createConsoleShaDriftRefusalPlugin) ──
{
route: 'GET /',
family: 'console-static',
family: 'console-static | console-unavailable',
mountedIn: 'utils/console.ts',
disposition: 'static-asset',
conditional: 'options.rootRedirect !== false (default: mounted)',
note:
'redirects the site root to `/_console/`. The Console is the default end-user surface, so claiming `/` is the '
+ 'intended behaviour in both dev and production once the Console is mounted at all; `os serve` gates whether '
+ 'it mounts via `--no-console` / `OS_DISABLE_CONSOLE=1`. Not API surface — a redirect to a static bundle. '
+ 'CONDITIONAL, and the ledger says so because the census reads the mount call and cannot see the branch.',
+ 'CONDITIONAL, and the ledger says so because the census reads the mount call and cannot see the branch. '
+ 'Also mounted, unconditionally, by the `console-unavailable` responders `os serve` mounts on a boot that '
+ 'wants a Console and refuses it — `createConsoleNotBuiltPlugin` (no built `dist/`, or no console package) '
+ 'and `createConsoleShaDriftRefusalPlugin` (a dev build that is not the repo\'s objectui pin): the same '
+ 'redirect, to the `503` that `GET /_console/*` answers there. One mount per boot; the boots are exclusive.',
},
{
route: 'GET /_console',
family: 'console-static',
family: 'console-static | console-unavailable',
mountedIn: 'utils/console.ts',
disposition: 'static-asset',
note:
'redirects the bare mount path to its trailing-slash form, the ordinary SPA convention — the Console is built '
+ 'with `base: \'/_console/\'`, so relative asset URLs only resolve from the slashed path. Pure navigation '
+ 'plumbing for a static bundle; there is nothing here for an SDK to express.',
+ 'plumbing for a static bundle; there is nothing here for an SDK to express. Also mounted by the '
+ '`console-unavailable` responders (`createConsoleNotBuiltPlugin`, `createConsoleShaDriftRefusalPlugin`) on a '
+ 'boot that refuses the Console: the same redirect.',
},
{
route: 'GET /forms/:slug',
Expand All @@ -151,14 +159,18 @@ export const CONSOLE_ROUTE_LEDGER: readonly ConsoleRouteLedgerEntry[] = [
},
{
route: 'GET /_console/*',
family: 'console-static',
family: 'console-static | console-unavailable',
mountedIn: 'utils/console.ts',
disposition: 'static-asset',
note:
'serves the pre-built Console SPA verbatim from `dist/`, with HTML entry points routed through base-tag '
+ 'injection and an SPA fallback for client-side routes. Reads files off disk behind a path-traversal guard '
+ '(any resolved path escaping `dist/` is refused 403). A file server, not an endpoint: its peer group is a '
+ 'CDN origin, so no client method builds these URLs and none should.',
+ 'CDN origin, so no client method builds these URLs and none should. On a boot that refuses the Console, '
+ 'the `console-unavailable` responders mount it instead and answer `503` with a `no-store` plain-text body '
+ 'naming the remedy the boot message prints, without host paths: `createConsoleNotBuiltPlugin` (build it, '
+ 'or reinstall `@objectstack/console`) and `createConsoleShaDriftRefusalPlugin` (rebuild the dist at the '
+ 'repo\'s objectui pin). Still the bundle\'s address, answering why there is no bundle to serve.',
},

// ── runtime asset serving (second factory in the same module) ──────
Expand Down
46 changes: 46 additions & 0 deletions packages/cli/src/utils/console.not-built.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
* - `GET /_console/` (and every path under it) answers `503` with the remedy
* the boot warning names — the same sentence from the same picker, with
* the host's absolute paths left out;
* - the same holds when the console package does not resolve at all
* (`consolePath` is `null`), which used to print nothing and mount nothing:
* the answer says the Console is not installed and names the reinstall
* sentence the picker already gives an install with no `dist/`;
* - `GET /` and `GET /_console` redirect to `/_console/`, exactly as they do
* once the Console is built (the control below), so neither route changes
* owner with the build.
Expand All @@ -38,6 +42,10 @@ const ORIGIN = 'http://console.example.test';
/** The first line of the not-built answer, which says what is wrong before saying how to fix it. */
const NOT_BUILT_HEADLINE = 'The ObjectStack Console is not built, so this server has no Console to serve at /_console/.';

/** The same line when the console package did not resolve at all. */
const NOT_INSTALLED_HEADLINE =
'The ObjectStack Console is not installed, so this server has no Console to serve at /_console/.';

/** The framework repo's remedy. */
const BUILD_REMEDY = 'pnpm objectui:build';

Expand Down Expand Up @@ -176,6 +184,44 @@ describe('an installed CLI whose `@objectstack/console` has no `dist/`', () => {
});
});

describe('an install where `@objectstack/console` does not resolve at all', () => {
let request: Request;
beforeAll(async () => {
request = await serve(createConsoleNotBuiltPlugin(null));
});

it.each(CONSOLE_REQUESTS)('GET %s answers 503 saying the Console is not installed', async (p) => {
const res = await request(p);
expect(res.status).toBe(503);
expect(res.headers.get('content-type')).toMatch(/^text\/plain/);
expect(res.headers.get('cache-control')).toBe('no-store');
const body = await res.text();
expect(body.split('\n')[0]).toBe(NOT_INSTALLED_HEADLINE);
expect(body).toContain('@objectstack/console');
expect(body).not.toContain(BUILD_REMEDY);
});

it('is the boot warning\'s sentence verbatim — it names no host path to leave out', async () => {
const warning = formatConsoleDistMissingWarning(null);
expect(warning.startsWith(WARNING_PREFIX)).toBe(true);
const body = await (await request('/_console/')).text();
expect(body).toContain(warning.slice(WARNING_PREFIX.length));
expect(body).not.toContain(scratch);
});

it('names the same reinstall sentence as an install whose package has no `dist/`', () => {
// One picker: the unresolved arm differs from the installed-without-dist
// arm only in what it says is missing, never in the fix.
const { consoleDir } = installTree();
const tail = (s: string) => s.slice(s.indexOf(' — '));
expect(tail(formatConsoleDistMissingWarning(null))).toBe(tail(formatConsoleDistMissingWarning(consoleDir)));
});

it('redirects `/` and `/_console` to `/_console/`', async () => {
await expectRedirectsToConsole(request);
});
});

describe('controls', () => {
it('a BUILT Console serves its SPA shell at `/_console/` and the same redirects', async () => {
const dist = path.join(scratch, 'built', 'dist');
Expand Down
133 changes: 132 additions & 1 deletion packages/cli/src/utils/console.sha-drift.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,29 @@
* server does not mount the Console at all, so the stale bundle is
* unreachable rather than silently authoritative. Detection semantics
* (`detectConsoleShaDrift`) are pinned in `test/console-resolve.test.ts`.
*
* Unreachable must not mean silent. A refused boot used to mount nothing, so
* `GET /_console/` and `GET /` answered the router's bare 404, the same answer
* a wrong URL gets, and only the terminal said why. `os serve` now mounts
* `createConsoleShaDriftRefusalPlugin` on that boot — the not-built answer's
* routes (`console.not-built.test.ts`) with the refusal's own text — and the
* last block below pins what it answers, on a REAL Hono app, from a fixture
* tree whose pin and stamp are made up here (never the repo's live pin).
*/
import { describe, it, expect } from 'vitest';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { HonoHttpServer } from '@objectstack/plugin-hono-server';
import {
createConsoleShaDriftRefusalPlugin,
createConsoleStaticPlugin,
decideConsoleMount,
detectConsoleShaDrift,
formatConsoleShaDriftRefusal,
formatConsoleShaDriftWarning,
DRIFT_OVERRIDE_ENV,
type ConsoleShaDrift,
} from './console.js';

/** The exact gap #7752 measured: pin two days ahead of the served bundle. */
Expand Down Expand Up @@ -111,3 +127,118 @@ describe('drift messages', () => {
expect(message).toContain(DRIFT_OVERRIDE_ENV);
});
});

describe('what a dev server that refused a drifted Console answers', () => {
const ORIGIN = 'http://console.example.test';
const PIN = 'aaaaaaaaaaaa1111111111111111111111111111';
const STAMP = 'bbbbbbbbbbbb2222222222222222222222222222';
const HEADLINE =
'The ObjectStack Console here was built from a different objectui commit than this checkout pins, ' +
'so this dev server refuses to serve it at /_console/.';
/** The shell, a client-side route and a hashed asset: the refusal covers every path under the mount. */
const CONSOLE_REQUESTS = ['/_console/', '/_console/apps/crm/records/42', '/_console/assets/index-ocmkyCt6.js'];

type Request = (p: string) => Promise<Response>;
let scratch: string;

beforeAll(() => {
scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'os-test-console-drift-refusal-')));
});

afterAll(() => {
fs.rmSync(scratch, { recursive: true, force: true });
});

/** A checkout pinned at `PIN` whose console dist is stamped `stamp` — what `os dev` resolves. */
function pinnedTree(tag: string, stamp: string): { root: string; consoleDir: string } {
const root = path.join(scratch, tag);
const consoleDir = path.join(root, 'packages', 'console');
fs.mkdirSync(path.join(consoleDir, 'dist'), { recursive: true });
fs.writeFileSync(path.join(root, '.objectui-sha'), `${PIN}\n`);
fs.writeFileSync(path.join(consoleDir, 'package.json'), JSON.stringify({ name: '@objectstack/console' }));
fs.writeFileSync(
path.join(consoleDir, 'dist', 'index.html'),
'<!doctype html><html><head></head><body>console shell</body></html>',
);
fs.writeFileSync(path.join(consoleDir, 'dist', '.objectui-sha'), `${stamp}\n`);
return { root, consoleDir };
}

async function serve(plugin: { start: (ctx: any) => Promise<void> }): Promise<Request> {
const server = new HonoHttpServer(0);
await plugin.start({ getServiceAsync: async () => server, logger: { warn: () => {} } });
const app = server.getRawApp();
return async (p) => app.request(`${ORIGIN}${p}`);
}

describe('the build is not the pin', () => {
let root: string;
let drift: ConsoleShaDrift;
let request: Request;
beforeAll(async () => {
const tree = pinnedTree('drifted', STAMP);
root = tree.root;
const found = detectConsoleShaDrift(tree.consoleDir);
expect(found, 'the fixture must be a drift detectConsoleShaDrift can prove').not.toBeNull();
drift = found!;
// The premise: this is the boot `os dev` refuses, not one it serves.
expect(decideConsoleMount({ hasDist: true, drift, isDev: true, env: {} })).toEqual({
mount: false,
refusedForDrift: true,
});
request = await serve(createConsoleShaDriftRefusalPlugin(drift));
});

it.each(CONSOLE_REQUESTS)('GET %s answers 503 naming `pnpm objectui:build`, not the SPA', async (p) => {
const res = await request(p);
expect(res.status).toBe(503);
expect(res.headers.get('content-type')).toMatch(/^text\/plain/);
expect(res.headers.get('cache-control')).toBe('no-store');
const body = await res.text();
expect(body.split('\n')[0]).toBe(HEADLINE);
expect(body).toContain('pnpm objectui:build');
expect(body).toContain(PIN.slice(0, 12));
expect(body).toContain(STAMP.slice(0, 12));
expect(body).toContain(DRIFT_OVERRIDE_ENV);
expect(body).not.toContain('console shell');
});

it('is the terminal refusal\'s text, with only the absolute pin-file path left out', async () => {
const refusal = formatConsoleShaDriftRefusal(drift);
expect(drift.pinFile.startsWith(root)).toBe(true);
// The refusal block names the pin file by its path on this host; the
// HTTP answer says where it is in words. Everything below the block's
// headline, either side of that path, is the same text.
const [before, after] = refusal.slice(refusal.indexOf('pinned')).split(drift.pinFile);
expect(after, 'the refusal no longer names the pin file this test splits on').toBeDefined();

const body = await (await request('/_console/')).text();
expect(body).toContain(before);
expect(body).toContain(after);
expect(body).not.toContain(root);
});

it('redirects `/` and `/_console` to `/_console/`, as a served Console does', async () => {
for (const p of ['/', '/_console']) {
const res = await request(p);
expect(res.status, `GET ${p}`).toBe(302);
expect(res.headers.get('location'), `GET ${p}`).toBe('/_console/');
}
});
});

it('control: a build that matches the pin is no drift, mounts, and serves the SPA shell', async () => {
const { consoleDir } = pinnedTree('matching', PIN);
const drift = detectConsoleShaDrift(consoleDir);
expect(drift).toBeNull();
expect(decideConsoleMount({ hasDist: true, drift, isDev: true, env: {} })).toEqual({
mount: true,
refusedForDrift: false,
});
const request = await serve(createConsoleStaticPlugin(path.join(consoleDir, 'dist')));
const res = await request('/_console/');
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toMatch(/^text\/html/);
expect(await res.text()).toContain('console shell');
});
});
Loading
Loading