§10 gate the dashboard + make "/" replaceable by a plugin (todo §10); "/" is now gated to a signed-in session (anonymous → /login via loginRedirect, query preserved as return_to) and fully replaceable via a new optional home?: RouteHandler on PluginManifest — a handler with the same signature as any route (the most ergonomic shape). The app.ts "/" branch gates first, then renders the single home plugin's handler against its own views/ with the native shell via ctx.chrome (HEAD / void-return / response-hook parity with a plugin route), else the built-in mock-data People list. home mounts at the root above the /<id> namespace, so it can't shadow or be shadowed by a built-in route. Single-slot + loud: findConflicts errors on >1 home (new "home" kind), discovery rejects a non-function home — never last-write-wins. Tests-first (338 → 344 units): app.test.ts gate + home-override; plugin.test.ts home conflict; discovery.test.ts home validation. Docs: plugin-contract.md (manifest table + "The dashboard (home)" section + conflict row), README. E2E: visual.spec plants a dev-signed session (the anonymous plugin-gate probe uses the cookie-free request fixture); all e2e web/gateway healthchecks repointed from the gated "/" to /public/css/styles.css. stability-reviewer: APPROVE, no Critical/High/Medium. typecheck + 344 units + visual(9) + full-flow(7) E2E green.

This commit is contained in:
2026-06-20 17:18:30 +02:00
parent df53106a5a
commit 2eb5b84ccf
14 changed files with 192 additions and 41 deletions

View File

@@ -23,7 +23,21 @@ import { contentTypeFor, resolveStaticPath, routePublic } from "./static.ts";
const viewsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "views");
const server = createApp();
// A session JWT signed with a throwaway test key — the §4 verify path. Wired into the shared
// `server` (and the per-test apps) so a request can present a valid session; the dashboard and the
// gated routes need one (§10). `staticJwks([ecJwk])` is the matching verify side.
const ec = generateKeyPairSync("ec", { namedCurve: "P-256" });
const ecJwk: JsonWebKey = { ...(ec.publicKey.export({ format: "jwk" }) as JsonWebKey), alg: "ES256", kid: "test-kid" };
const b64url = (i: Buffer | string): string => Buffer.from(i).toString("base64url");
function mintJwt(payload: Record<string, unknown>): string {
const input = `${b64url(JSON.stringify({ alg: "ES256", kid: "test-kid", typ: "JWT" }))}.${b64url(JSON.stringify(payload))}`;
return `${input}.${b64url(sign("SHA256", Buffer.from(input), { dsaEncoding: "ieee-p1363", key: ec.privateKey }))}`;
}
// A session cookie carrying `roles`, valid for 10 min — the auth most tests need to reach a gated page.
const session = (roles: string[] = []): string =>
`${SESSION_COOKIE}=${mintJwt({ email: "a@b.c", exp: Math.floor(Date.now() / 1000) + 600, roles, sub: "u1" })}`;
const server = createApp({ jwks: staticJwks([ecJwk]) });
let base = "";
before(async () => {
@@ -34,7 +48,8 @@ before(async () => {
after(() => server.close());
test("serves the home page: the app-shell People dashboard, filterable via the URL", async () => {
const res = await fetch(base + "/");
// The dashboard is gated to a signed-in user (§10), so present a session.
const res = await fetch(base + "/", { headers: { cookie: session() } });
assert.equal(res.status, 200);
assert.match(res.headers.get("content-type") ?? "", /text\/html/);
const html = await res.text();
@@ -54,15 +69,52 @@ test("serves the home page: the app-shell People dashboard, filterable via the U
assert.match(html, new RegExp(`name="_csrf" value="${csrfCookie!.replace(/[.]/g, "\\.")}"`));
// A search query filters server-side: a no-match query drops every row.
const empty = await fetch(base + "/?q=zzz-no-such-person");
const empty = await fetch(base + "/?q=zzz-no-such-person", { headers: { cookie: session() } });
assert.doesNotMatch(await empty.text(), /Avery Kline/);
});
test("renders branding from the menu config into the shell: logo + default theme", async (t) => {
const app = createApp({ menu: { branding: { logo: "/public/brand/logo.svg", name: "Acme Ops", theme: "dark" }, override: {} } });
test("the dashboard is gated (§10): an anonymous visitor is bounced to sign in, not shown the page", async () => {
const res = await fetch(base + "/", { redirect: "manual" });
assert.equal(res.status, 303);
assert.equal(res.headers.get("location"), "/login");
});
test("a `home` plugin fully replaces the dashboard, rendered in the native shell from ctx.chrome; still gated (§10)", async (t) => {
const dir = mkdtempSync(join(tmpdir(), "pp-home-"));
mkdirSync(join(dir, "portal", "views"), { recursive: true });
// The home view renders the native app shell from ctx.chrome — the blessed plugin ergonomics:
// its own title/body, the global menu (chrome.nav), the signed-in user, the Sign-out CSRF token.
writeFileSync(join(dir, "portal", "views", "home.ejs"),
`<%- include("partials/shell", { body: "<p>Welcome " + user.email + "</p>", brand: chrome.brand, csrfToken: chrome.csrfToken, nav: include("partials/nav-tree", { nodes: chrome.nav }), theme: chrome.theme, title: "My Portal", user: chrome.user }) %>`);
t.after(() => rmSync(dir, { force: true, recursive: true }));
const portal: Plugin = {
apiVersion: "1.0.0",
home: (ctx) => ({ data: { chrome: ctx.chrome, user: ctx.user }, view: "home" }),
id: "portal",
};
const app = createApp({ jwks: staticJwks([ecJwk]), plugins: [portal], pluginsDir: dir });
await new Promise<void>((r) => app.listen(0, r));
t.after(() => app.close());
const html = await (await fetch(`http://localhost:${(app.address() as AddressInfo).port}/`)).text();
const url = `http://localhost:${(app.address() as AddressInfo).port}`;
// Gate still applies — the home plugin doesn't open the page up.
assert.equal((await fetch(url + "/", { redirect: "manual" })).status, 303);
// Signed in: the plugin's dashboard renders, fully replacing the built-in People list.
const page = await fetch(url + "/", { headers: { cookie: session() } });
assert.equal(page.status, 200);
const html = await page.text();
assert.match(html, /<h1 class="page-title">My Portal<\/h1>/); // the plugin's own title in the native shell
assert.match(html, /Welcome a@b\.c/); // its handler rendered, with ctx.user
assert.match(html, /<aside class="sidebar"/); // composed chrome (global nav) is available
assert.doesNotMatch(html, /Avery Kline/); // the built-in mock People list is gone — fully replaced
});
test("renders branding from the menu config into the shell: logo + default theme", async (t) => {
const app = createApp({ jwks: staticJwks([ecJwk]), menu: { branding: { logo: "/public/brand/logo.svg", name: "Acme Ops", theme: "dark" }, override: {} } });
await new Promise<void>((r) => app.listen(0, r));
t.after(() => app.close());
const html = await (await fetch(`http://localhost:${(app.address() as AddressInfo).port}/`, { headers: { cookie: session() } })).text();
assert.match(html, /<img class="brand-logo" src="\/public\/brand\/logo\.svg"/);
assert.match(html, /Acme Ops/);
@@ -71,10 +123,10 @@ test("renders branding from the menu config into the shell: logo + default theme
test("emits a structured access-log line per request (the injected §9 logger)", async (t) => {
const lines: string[] = [];
const app = createApp({ log: createLogger({ format: "json", level: "info", stderr: () => {}, stdout: (m) => lines.push(m) }) });
const app = createApp({ jwks: staticJwks([ecJwk]), log: createLogger({ format: "json", level: "info", stderr: () => {}, stdout: (m) => lines.push(m) }) });
await new Promise<void>((r) => app.listen(0, r));
t.after(() => app.close());
const res = await fetch(`http://localhost:${(app.address() as AddressInfo).port}/?q=zz`);
const res = await fetch(`http://localhost:${(app.address() as AddressInfo).port}/?q=zz`, { headers: { cookie: session() } });
assert.equal(res.status, 200);
await res.text(); // consume the body so the connection closes (the access line emits on close)
@@ -199,7 +251,7 @@ test("every response carries the security headers; HSTS follows SECURE_COOKIES (
// Default app (secureCookies off): a page and a static asset both carry the hardening headers,
// proving they're set once up front and survive each writeHead (the html + static paths merge).
for (const path of ["/", "/public/css/styles.css"]) {
const res = await fetch(base + path);
const res = await fetch(base + path, { headers: { cookie: session() } });
assert.equal(res.headers.get("x-content-type-options"), "nosniff", path);
assert.equal(res.headers.get("x-frame-options"), "DENY", path);
assert.match(res.headers.get("content-security-policy") ?? "", /default-src 'self'/, path);
@@ -207,21 +259,21 @@ test("every response carries the security headers; HSTS follows SECURE_COOKIES (
}
// A https deployment (SECURE_COOKIES=true) adds HSTS.
const secure = createApp({ secureCookies: true });
const secure = createApp({ jwks: staticJwks([ecJwk]), secureCookies: true });
await new Promise<void>((r) => secure.listen(0, r));
t.after(() => secure.close());
const res = await fetch(`http://localhost:${(secure.address() as AddressInfo).port}/`);
const res = await fetch(`http://localhost:${(secure.address() as AddressInfo).port}/`, { headers: { cookie: session() } });
assert.match(res.headers.get("strict-transport-security") ?? "", /max-age=\d+/);
});
// Production caches compiled templates; rendering must stay correct across repeated requests.
test("renders correctly with template caching enabled", async () => {
const app = createApp({ cache: true });
const app = createApp({ cache: true, jwks: staticJwks([ecJwk]) });
try {
await new Promise<void>((resolve) => app.listen(0, resolve));
const url = `http://localhost:${(app.address() as AddressInfo).port}/`;
for (let i = 0; i < 2; i++) {
const res = await fetch(url);
const res = await fetch(url, { headers: { cookie: session() } });
assert.equal(res.status, 200);
assert.match(await res.text(), /Plainpages/);
}
@@ -241,10 +293,11 @@ test("renders the 500 HTML page when a handler throws", async () => {
const dir = mkdtempSync(join(tmpdir(), "pp-views-"));
writeFileSync(join(dir, "index.ejs"), "<% throw new Error('boom'); %>");
cpSync(join(viewsDir, "500.ejs"), join(dir, "500.ejs"));
const app = createApp({ viewsDir: dir });
const app = createApp({ jwks: staticJwks([ecJwk]), viewsDir: dir });
try {
await new Promise<void>((resolve) => app.listen(0, resolve));
const res = await fetch(`http://localhost:${(app.address() as AddressInfo).port}/`);
// A session reaches the (throwing) index render; the gate would otherwise bounce anonymous to /login.
const res = await fetch(`http://localhost:${(app.address() as AddressInfo).port}/`, { headers: { cookie: session() } });
assert.equal(res.status, 500);
assert.match(res.headers.get("content-type") ?? "", /text\/html/);
assert.match(await res.text(), /500/);
@@ -378,14 +431,7 @@ test("a plugin view renders the native chrome; its forms are CSRF-guarded via ct
});
// JWT middleware (§4): a verified session cookie populates ctx.user/roles, which the gate reads.
const ec = generateKeyPairSync("ec", { namedCurve: "P-256" });
const ecJwk: JsonWebKey = { ...(ec.publicKey.export({ format: "jwk" }) as JsonWebKey), alg: "ES256", kid: "test-kid" };
const b64url = (i: Buffer | string): string => Buffer.from(i).toString("base64url");
function mintJwt(payload: Record<string, unknown>): string {
const input = `${b64url(JSON.stringify({ alg: "ES256", kid: "test-kid", typ: "JWT" }))}.${b64url(JSON.stringify(payload))}`;
return `${input}.${b64url(sign("SHA256", Buffer.from(input), { dsaEncoding: "ieee-p1363", key: ec.privateKey }))}`;
}
// The key + mintJwt + session() helper are hoisted above the shared `server` (top of file).
test("a verified session JWT authorizes a role-gated route; no cookie / expired token → sign in", async (t) => {
const app = createApp({ jwks: staticJwks([ecJwk]), plugins: [demoPlugin] });
await new Promise<void>((r) => app.listen(0, r));
@@ -406,10 +452,13 @@ test("a verified session JWT authorizes a role-gated route; no cookie / expired
assert.equal(noCookie.headers.get("location"), "/login?return_to=%2Fdemo%2Fsecret");
assert.equal((await secret(`${SESSION_COOKIE}=${mintJwt({ email: "a@b.c", exp: nowSec - 600, roles: ["demo:read"], sub: "u1" })}`)).status, 303);
// The home menu wires in the permission-gated Admin section: an admin's roles surface the links.
const home = (cookie?: string) => fetch(url + "/", cookie ? { headers: { cookie } } : {});
assert.match(await (await home(`${SESSION_COOKIE}=${mintJwt({ email: "a@b.c", exp: nowSec + 600, roles: ["admin"], sub: "u1" })}`)).text(), /href="\/admin\/users"/);
assert.doesNotMatch(await (await home()).text(), /href="\/admin\/users"/); // anonymous → no admin section
// The dashboard wires in the permission-gated Admin section: an admin's roles surface the links;
// anonymous is bounced to sign in before any page renders (§10 gate).
const admin = await fetch(url + "/", { headers: { cookie: `${SESSION_COOKIE}=${mintJwt({ email: "a@b.c", exp: nowSec + 600, roles: ["admin"], sub: "u1" })}` } });
assert.match(await admin.text(), /href="\/admin\/users"/);
const anonHome = await fetch(url + "/", { redirect: "manual" });
assert.equal(anonHome.status, 303);
assert.equal(anonHome.headers.get("location"), "/login");
});
test("revocation denylist (§9): a revoked subject's token stops authorizing on the hot path; a fresh re-login passes", async (t) => {

View File

@@ -29,7 +29,7 @@ import { clearSessionCookie, completeLogin, remintSession, sessionCookie } from
import { resolveLoginChallenge } from "./oauth-login.ts";
import { acceptConsent, rejectConsent, resolveConsentChallenge } from "./oauth-consent.ts";
import { DEFAULT_MENU, type MenuConfig } from "./menu-config.ts";
import type { Plugin, RouteResult } from "./plugin.ts";
import type { Plugin, RouteHandler, RouteResult } from "./plugin.ts";
import { allowedMethods, isAuthorized, matchRoute } from "./router.ts";
import { securityHeaders } from "./security-headers.ts";
import { localPath } from "./safe-url.ts";
@@ -79,6 +79,9 @@ export function createApp(options: AppOptions = {}): Server {
const menu = options.menu ?? DEFAULT_MENU;
const plugins = options.plugins ?? [];
const pluginIds = new Set(plugins.map((p) => p.id));
// A plugin may fully replace the dashboard "/" by declaring `home` (§10). Discovery's findConflicts
// guarantees at most one, so `find` is unambiguous; the predicate narrows `home` to defined.
const homePlugin = plugins.find((p): p is Plugin & { home: RouteHandler } => typeof p.home === "function");
// Skip the hook pipeline entirely unless a plugin declares the hook (keeps the hot path free).
const anyRequestHooks = plugins.some((p) => p.hooks?.onRequest);
const anyResponseHooks = plugins.some((p) => p.hooks?.onResponse);
@@ -430,9 +433,21 @@ export function createApp(options: AppOptions = {}): Server {
}
if (pathname === "/" && (method === "GET" || method === "HEAD")) {
// Roles from the verified JWT (anonymous ⇒ []); branding/override come from config/menu.ts.
// The dashboard is the post-login landing page, gated to a signed-in user (§10): anonymous
// bounces to sign in (loginRedirect yields a bare /login for "/").
if (!user) { res.writeHead(303, { location: loginRedirect(ctx) }).end(); return; }
// The page carries the Sign-out form, so Set-Cookie a fresh CSRF token here when absent.
if (csrf.fresh) res.appendHeader("set-cookie", csrfCookie(csrf.token, { secure: secureCookies }));
// A plugin may fully own the dashboard (§10): render its handler against its own views, native
// shell via ctx.chrome — same path as a plugin route. Else the built-in mock-data People list.
if (homePlugin) {
const homeCtx = buildContext(req, res, { chrome: chrome(), log: reqLog, user, verifyCsrf });
const result = (await homePlugin.home(homeCtx)) ?? null;
if (anyResponseHooks) await runResponseHooks(plugins, homeCtx, result);
await sendResult(res, result, (view, data) => renderView(homePlugin.id, view, data));
return;
}
// Roles from the verified JWT; branding/override come from config/menu.ts.
sendHtml(res, 200, await render("index", { model: buildDashboardModel(ctx.url, ctx.roles, menu, csrf.token, user, plugins) }));
return;
}

View File

@@ -47,7 +47,9 @@ const badCases: Array<{ name: string; files: Record<string, string>; match: RegE
{ name: "import throws", files: { "explodes/plugin.ts": "throw new Error('boom');" }, match: /explodes.*boom/s },
{ name: "incompatible apiVersion", files: { "future/plugin.ts": `export default { apiVersion: "2.0.0" };` }, match: /future.*apiVersion/s },
{ name: "non-array routes", files: { "weird/plugin.ts": `export default { apiVersion: "1.0.0", routes: "nope" };` }, match: /weird.*routes.*array/s },
{ name: "non-function home", files: { "weirdhome/plugin.ts": `export default { apiVersion: "1.0.0", home: "nope" };` }, match: /weirdhome.*home.*function/s },
{ name: "duplicate nav id across plugins", files: { "a/plugin.ts": full("a").replace("a:root", "dup"), "b/plugin.ts": full("b").replace("b:root", "dup") }, match: /nav id "dup"/ },
{ name: "two plugins claim the dashboard home", files: { "a/plugin.ts": `export default { apiVersion: "1.0.0", home: () => ({ html: "a" }) };`, "b/plugin.ts": `export default { apiVersion: "1.0.0", home: () => ({ html: "b" }) };` }, match: /home/ },
];
for (const c of badCases) {
@@ -56,6 +58,13 @@ for (const c of badCases) {
});
}
test("a plugin may declare `home` (a function) to own the dashboard (§10)", async (t) => {
const dir = scaffold(t, { "portal/plugin.ts": `export default { apiVersion: "1.0.0", home: () => ({ view: "home" }) };` });
const plugins = await discoverPlugins({ dir });
assert.equal(plugins.length, 1);
assert.equal(typeof plugins[0]?.home, "function");
});
test("a shared permission token only warns — both plugins still load", async (t) => {
const perm = `export default { apiVersion: "1.0.0", permissions: [{ token: "shared:read" }] };`;
const dir = scaffold(t, { "x/plugin.ts": perm, "y/plugin.ts": perm });

View File

@@ -88,6 +88,8 @@ function shapeError(manifest: PluginManifest): string | null {
for (const field of ["nav", "permissions", "routes"] as const) {
if (manifest[field] !== undefined && !Array.isArray(manifest[field])) return `"${field}" must be an array`;
}
// `home` (the §10 dashboard override) is a route handler; the host calls it, so a non-function fails loud.
if (manifest.home !== undefined && typeof manifest.home !== "function") return `"home" must be a function (a route handler)`;
return null;
}

View File

@@ -99,3 +99,11 @@ test("findConflicts: duplicate nav id is an error, a shared permission token onl
]);
assert.ok(permDup.some((c) => c.kind === "permission" && c.level === "warn"));
});
test("findConflicts: only one plugin may claim the dashboard (`home`) — two is a loud error (§10)", () => {
const home = () => ({ html: "dash" });
const dup = findConflicts([p({ id: "a", home }), p({ id: "b", home })]);
assert.ok(dup.some((c) => c.kind === "home" && c.level === "error" && c.plugins.includes("a") && c.plugins.includes("b")));
// One home (or none) is fine.
assert.deepEqual(findConflicts([p({ id: "a", home }), p({ id: "b" })]).filter((c) => c.kind === "home"), []);
});

View File

@@ -50,6 +50,10 @@ export interface PluginHooks {
// host derives them from the folder name at discovery (see Plugin).
export interface PluginManifest {
apiVersion: string; // semver of the host contract this targets — write a literal, NOT HOST_API_VERSION (see docs)
// Take over the dashboard "/" — the post-login landing page (§10). A handler like any route's,
// gated by the host to a signed-in session (anonymous → /login); render its own view via ctx.chrome.
// At most one plugin may declare it (findConflicts → error, never last-write-wins).
home?: RouteHandler;
hooks?: PluginHooks;
nav?: NavNode[]; // fragment merged into the menu (composeNav); node `icon` is a Lucide sprite id (src/icons.ts), node ids must be globally unique
permissions?: PermissionDecl[];
@@ -134,7 +138,7 @@ export function checkApiVersion(pluginVersion: unknown, hostVersion: string = HO
}
export interface PluginConflict {
kind: "id" | "nav-id" | "permission" | "route";
kind: "home" | "id" | "nav-id" | "permission" | "route";
level: "error" | "warn";
message: string;
plugins: string[]; // unique ids involved
@@ -153,6 +157,10 @@ export function findConflicts(plugins: Plugin[]): PluginConflict[] {
if (n > 1) out.push({ kind: "id", level: "error", message: `${n} plugins share id "${id}"; ids must be globally unique`, plugins: [id] });
}
// The dashboard "/" is a single slot (§10): two plugins claiming `home` is a loud error, not a race.
const homeOwners = plugins.filter((plugin) => plugin.home).map((plugin) => plugin.id);
if (homeOwners.length > 1) out.push({ kind: "home", level: "error", message: `${homeOwners.length} plugins claim the dashboard "home" (${homeOwners.join(", ")}); only one may`, plugins: uniq(homeOwners) });
collect(plugins, (plugin, push) => {
for (const route of plugin.routes ?? []) push(`${route.method} ${fullPath(plugin.id, route.path)}`);
}).forEach((owners, key) => {