fix(authz): fix prod boot-order (C1), dev HMR staleness (I2), add prod coverage (I4)
Fix round 2 for Task 14, addressing a critical review finding reproduced on
a real built server.
C1 (critical): the generated production entry set the authz catalog inside
createProductionServer's BODY, but ES modules evaluate every static import
(including app middleware, emitted as a static import) before the importing
module's body runs. Middleware reading getAuthzCatalog() at module scope —
the same eager shape authzMiddleware({ catalog, ... }) itself requires, and
the pattern app/middleware/logger.ts's `export default requestLogger({...})`
already uses — saw an unset catalog and crashed the whole process at import
time, after every other gate (typecheck/lint/tests/a plain `bun run build`)
stayed green.
Fix: packages/cli/src/build.ts now emits a small side-effecting
`.authz-setup.ts` module containing the static imports of every
app/authz/*.ts declaration plus a call to the new
applyAuthzManifestEarly(entries) (packages/dev-server/src/prod.ts), and
imports THAT MODULE FIRST in the generated entry — before pages, api,
realtime, middleware, components, and layouts. applyAuthzManifestEarly is
deliberately silent (no missing-default-export warnings, though a genuine
conflict still throws and fails the boot at import time); createProductionHandlers
keeps its own unconditional merge+set as an idempotent, always-warning second
pass, so an adapter that bypasses the generated entry and calls it directly
still gets a correctly merged, validated catalog, and so the function stays
independently testable.
I3: corrected packages/authz/src/client.ts's WRN-AUTHZ-SETUP message, which
claimed prod always sets the catalog before middleware runs — true again for
the generated entry after the C1 fix, but not for a custom entry that calls
createProductionHandlers directly.
I2: dev HMR editing app/authz/*.ts reloaded the page while the OLD catalog
stayed authoritative (watch.ts classifies any non-CSS change as "server";
hotUpdate had no authz/ branch) — a false security signal, since tightening
or removing a permission looked like it took effect but didn't until a
restart. Added the branch (packages/dev-server/src/index.ts), and gave
loadAppAuthzCatalog (authz-boot.ts) an injectable importer: a raw import()
would have silently no-op'd on the re-import (Bun caches local TS/JS modules
by filesystem path and ignores query strings), so the hot path routes through
loadModule (pipeline.ts) instead, which copies the edited file to a versioned
sibling specifically to defeat that cache.
I4: added direct createProductionHandlers/applyAuthzManifestEarly tests
(packages/dev-server/test/authz-prod.test.ts: conflict throws naming both
files, missing default export warns and skips, empty array yields an empty
catalog, a second call re-validates rather than trusting a stale singleton)
and the regression test that matters most
(packages/cli/test/authz-prod-coldstart.test.ts): a real `runBuild` + a real
`bun dist/server.js` boot, with a middleware module reading
getAuthzCatalog() at module scope, asserting it actually serves a request.
M5: startServer built its own router once, then loadAppAuthzCatalog built a
second one from scratch on every dev boot and every authz/ hot reload.
loadAppAuthzCatalog now accepts either an appDir (still used standalone, e.g.
by the test suite) or an already-built Router, and both call sites in
index.ts now pass the router they already have.
Every fix in this round was verified non-vacuous by sabotaging it and
confirming the corresponding test fails, then reverting.
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { buildRouter } from "@wrnexus/router";
|
||||
import { buildRouter, type Router } from "@wrnexus/router";
|
||||
import {
|
||||
emptyCatalog,
|
||||
mergeCatalogs,
|
||||
@@ -8,14 +8,39 @@ import {
|
||||
type CatalogSource,
|
||||
} from "@wrnexus/authz";
|
||||
|
||||
/** Imports one declaration module. Defaults to a raw `import()`; the hot-reload
|
||||
* call site passes `loadModule` instead (see the note below on why). */
|
||||
export type AuthzImporter = (file: string) => Promise<{ default?: AuthzModule }>;
|
||||
|
||||
const rawImport: AuthzImporter = (file) =>
|
||||
import(pathToFileURL(file).href) as Promise<{ default?: AuthzModule }>;
|
||||
|
||||
/**
|
||||
* Load and merge every `app/authz/*.ts` declaration. Conflicts throw so a
|
||||
* misconfigured catalog fails the boot rather than silently changing who can
|
||||
* do what. An app with no `app/authz/` directory gets an empty catalog rather
|
||||
* than an error, since not every app uses permissions.
|
||||
*
|
||||
* Accepts either an app directory — the original, standalone shape, still
|
||||
* used by the test suite and by any caller without a router on hand — or an
|
||||
* already-built `Router`. `startServer` passes its own router (built once at
|
||||
* `:315` with the full `componentDirs`/`externalRoutes`/`middlewareFiles`
|
||||
* options) to avoid a second, redundant filesystem scan of the whole `app/`
|
||||
* tree on every dev boot and on every hot reload of an `app/authz/*.ts` file.
|
||||
*
|
||||
* `importModule` defaults to a raw dynamic `import()`, correct for the
|
||||
* initial boot. On a HOT reload, the caller must instead pass `loadModule`
|
||||
* (from `./pipeline.ts`): Bun caches local TS/JS modules by filesystem path
|
||||
* and ignores query strings, so re-`import()`-ing the same absolute path
|
||||
* after an edit silently returns the stale, already-cached module —
|
||||
* `loadModule` is what copies an edited file to a versioned sibling path
|
||||
* specifically to defeat that cache.
|
||||
*/
|
||||
export async function loadAppAuthzCatalog(appDir: string): Promise<AuthzCatalog> {
|
||||
const router = buildRouter(appDir);
|
||||
export async function loadAppAuthzCatalog(
|
||||
appDirOrRouter: string | Router,
|
||||
importModule: AuthzImporter = rawImport,
|
||||
): Promise<AuthzCatalog> {
|
||||
const router = typeof appDirOrRouter === "string" ? buildRouter(appDirOrRouter) : appDirOrRouter;
|
||||
if (!router.authz.length) return emptyCatalog();
|
||||
const sources: CatalogSource[] = [];
|
||||
for (const entry of router.authz) {
|
||||
@@ -24,7 +49,7 @@ export async function loadAppAuthzCatalog(appDir: string): Promise<AuthzCatalog>
|
||||
// same failure class as a genuine conflict (a broken/misconfigured catalog),
|
||||
// and letting it propagate fails the boot loudly instead of silently
|
||||
// producing a partial catalog. Do not "helpfully" wrap this in a try/catch.
|
||||
const imported = (await import(pathToFileURL(entry.file).href)) as { default?: AuthzModule };
|
||||
const imported = await importModule(entry.file);
|
||||
if (!imported.default) {
|
||||
console.warn(`[wrnexus] authz declaration ${entry.file} has no default export; skipping.`);
|
||||
continue;
|
||||
|
||||
Reference in New Issue
Block a user