feat(authz): reach the merged catalog from boot via a process-wide singleton

Fix round 1 for Task 14 — closes the gap flagged in the last report:
loadAppAuthzCatalog existed but nothing called it.

- packages/authz/src/client.ts (new): setAuthzCatalog/getAuthzCatalog/
  hasAuthzCatalog, mirroring @wrnexus/db's client.ts. App middleware runs
  at module-eval time and needs the catalog then, so ctx cannot carry it;
  getAuthzCatalog() throws a setup error naming the fix, like getDb() does.
  Exported from packages/authz/src/index.ts.
- packages/dev-server/src/index.ts: startServer calls loadAppAuthzCatalog +
  setAuthzCatalog before middleware is resolved (schemasJs precedent),
  and populates the new RuntimeDeps.authz field.
- packages/dev-server/src/runtime.ts: RuntimeDeps gains authz?: AuthzCatalog.
- packages/cli/src/build.ts: emits static imports of each app/authz/*.ts
  file into the generated entry (components/layouts precedent) and passes
  { source, module } pairs through ProdOptions.authz — the catalog holds
  policy functions, so it cannot be JSON-baked like schemasJs.
- packages/dev-server/src/prod.ts: createProductionHandlers merges those
  declarations and calls setAuthzCatalog before the server accepts
  traffic, so a conflict fails the boot instead of surfacing on the first
  request. Runs for every deployment adapter, not only Bun.serve.

The framework never installs authzMiddleware itself; the app still
registers it with its own store.

Verified end-to-end: added a temporary app/authz declaration to
examples/basic-app, ran `bun run build`, inspected the generated entry's
static import + authz array, and booted dist/server.js to confirm the
merge/setAuthzCatalog call succeeds against real bundled code (reverted
before commit).
This commit is contained in:
2026-08-04 22:40:42 +05:30
parent daea59cf5d
commit 226217ecbf
10 changed files with 307 additions and 1 deletions
+4
View File
@@ -20,6 +20,10 @@ export async function loadAppAuthzCatalog(appDir: string): Promise<AuthzCatalog>
const sources: CatalogSource[] = [];
for (const entry of router.authz) {
// buildRouter already skips *.gen.ts, so only real declarations arrive here.
// A file that throws on import is intentionally NOT caught here: it is the
// 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 };
if (!imported.default) {
console.warn(`[wrnexus] authz declaration ${entry.file} has no default export; skipping.`);
+13
View File
@@ -32,6 +32,8 @@ import {
} from "@wrnexus/db";
import { connectFromConfig } from "@wrnexus/db/connect";
import { configureStorage, type StorageConfig } from "@wrnexus/uploader";
import { setAuthzCatalog, type AuthzCatalog } from "@wrnexus/authz";
import { loadAppAuthzCatalog } from "./authz-boot.ts";
import { realtimeBusFromConfig } from "./realtime-bus.ts";
import {
invalidateModule,
@@ -336,6 +338,16 @@ export async function startServer(opts: ServeOptions): Promise<RunningServer> {
const schemasJs = await schemaRuntime(router);
// Authorization: load and merge every app/authz/*.ts declaration, then stash
// it in the process-wide registry BEFORE middleware is resolved. App
// middleware (which registers authzMiddleware itself, with its own store —
// the framework never installs one) runs at request time and needs
// getAuthzCatalog() already populated by then. An app with no declarations
// gets an empty catalog; a genuine conflict between declarations throws and
// fails this boot loudly.
const authzCatalog: AuthzCatalog = await loadAppAuthzCatalog(appDir);
setAuthzCatalog(authzCatalog);
// i18n is opt-in by the presence of app/locales/*.json.
const localeMessages = loadLocales(join(appDir, "locales"), { strict: opts.i18n?.strict });
const i18n = Object.keys(localeMessages).length
@@ -457,6 +469,7 @@ export async function startServer(opts: ServeOptions): Promise<RunningServer> {
security: opts.security,
observability: opts.observability,
tenancy: opts.tenancy,
authz: authzCatalog,
navigation: opts.navigation,
clientRuntimes: pluginContributions.clientRuntimes,
hub,
+29
View File
@@ -38,6 +38,7 @@ import { VALIDATE_RUNTIME } from "@wrnexus/validation";
import { I18N_RUNTIME, type ResolvedI18n } from "@wrnexus/i18n";
import { setDb, registerLazyDb, getDb, hasDb, migrate } from "@wrnexus/db";
import { connectFromConfig } from "@wrnexus/db/connect";
import { mergeCatalogs, setAuthzCatalog, type AuthzModule } from "@wrnexus/authz";
import {
configureStorage,
serveStoredFile,
@@ -103,6 +104,15 @@ export interface ProdOptions {
frameworkCssPath?: string;
/** Pre-built `window.__wireSchemas = {...}` script for client validation. */
schemasJs?: string;
/**
* Authorization declarations discovered by `wrnexus build` from
* `app/authz/*.ts`, statically imported into the generated entry (the
* catalog holds policy FUNCTIONS, so — unlike `schemasJs` — it cannot be
* JSON-serialised). `module` is `undefined` for a file with no default
* export; `createProductionHandlers` warns and skips it, then merges the
* rest into the process-wide catalog before the server accepts traffic.
*/
authz?: { source: string; module?: AuthzModule }[];
/** Resolved i18n bundle (default lang + locale messages). */
i18n?: ResolvedI18n;
/** Default database connection (driver + url); enables `getDb()`. */
@@ -353,6 +363,24 @@ export function createProductionHandlers(
// (NOT dist/, which is rebuilt) so uploads persist across deploys.
configureStorage(opts.storage, process.cwd());
// Authorization: merge the build's statically-imported app/authz/*.ts
// declarations into the process-wide catalog BEFORE the handlers (and thus
// any request) exist, so a conflicting pair of declarations fails the boot
// loudly instead of surfacing on the first request. This runs for every
// deployment adapter that calls createProductionHandlers, not only the
// Bun.serve path in createProductionServer below. The app still registers
// authzMiddleware itself with its own store; this only makes the merged
// catalog reachable. No declarations -> an empty catalog, no error.
const authzSources = (opts.authz ?? []).flatMap((entry) => {
if (!entry.module) {
console.warn(`[wrnexus] authz declaration ${entry.source} has no default export; skipping.`);
return [];
}
return [{ source: entry.source, module: entry.module }];
});
const authzCatalog = mergeCatalogs(authzSources);
setAuthzCatalog(authzCatalog);
// Middleware is already an ordered array of functions.
const getMiddleware = async (): Promise<Middleware[]> => manifest.middleware;
@@ -388,6 +416,7 @@ export function createProductionHandlers(
security: opts.security,
observability: opts.observability,
tenancy: opts.tenancy,
authz: authzCatalog,
navigation: opts.navigation,
maxBodyBytes: opts.maxBodyBytes,
realtimeBus: realtimeBusFromConfig(opts.realtime),
+12
View File
@@ -63,6 +63,7 @@ import {
requestStoreContainer,
} from "@wrnexus/ssr/store-context";
import type { StoreDefinition } from "@wrnexus/store";
import type { AuthzCatalog } from "@wrnexus/authz";
import type { ClientRuntimeDefinition } from "@wrnexus/plugin";
import { CacheCoordinator } from "@wrnexus/cache";
import { generateServiceWorker } from "@wrnexus/pwa";
@@ -185,6 +186,17 @@ export interface RuntimeDeps {
health?: HealthRegistry;
/** Built-in tenant identity resolution. */
tenancy?: TenancyConfig;
/**
* Process-wide authorization catalog, merged from `app/authz/*.ts` at boot
* (dev: `loadAppAuthzCatalog`; prod: `mergeCatalogs` over the build's static
* imports). Also reachable via `@wrnexus/authz`'s `getAuthzCatalog()`
* singleton, which is what the app's own `authzMiddleware` registration
* actually reads — this field exists so the request pipeline can see the
* catalog without importing that singleton directly. The framework never
* installs `authzMiddleware` itself; the app always registers it with its
* own store.
*/
authz?: AuthzCatalog;
/** Max request body size in bytes (413 above this). Default 10 MB. */
maxBodyBytes?: number;
/** HMR hub for browser live-update sockets (dev only). */
@@ -0,0 +1,103 @@
import { afterAll, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { getAuthzCatalog, hasAuthzCatalog } from "@wrnexus/authz";
import { startServer } from "../src/index.ts";
// Fixtures live inside the repo tree, not os.tmpdir(): a scaffolded file under
// app/authz importing "@wrnexus/authz" by bare specifier resolves via the root
// tsconfig.json `paths` map, walked from the *imported file's* location — an
// out-of-tree path (os.tmpdir(), often a different drive on Windows) never
// reaches it.
const scratchRoot = join(import.meta.dir, ".tmp-authz-startserver");
mkdirSync(scratchRoot, { recursive: true });
function scaffold(name: string, authzFiles: Record<string, string>): string {
const root = mkdtempSync(join(scratchRoot, `${name}-`));
const appDir = join(root, "app");
mkdirSync(join(appDir, "pages"), { recursive: true });
writeFileSync(
join(root, "package.json"),
JSON.stringify({ name: `authz-startserver-${name}` }),
"utf8",
);
if (Object.keys(authzFiles).length) {
mkdirSync(join(appDir, "authz"), { recursive: true });
for (const [file, body] of Object.entries(authzFiles)) {
writeFileSync(join(appDir, "authz", file), body, "utf8");
}
}
return appDir;
}
afterAll(() => {
rmSync(scratchRoot, { recursive: true, force: true });
});
describe("dev boot loads the authz catalog before middleware is resolved", () => {
test("an app with declarations makes getAuthzCatalog() return them after boot", async () => {
const appDir = scaffold("has-decls", {
"main.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": { title: "View posts" } } });`,
});
const server = await startServer({
appDir,
hostname: "127.0.0.1",
port: 0,
mode: "development",
hmr: false,
});
try {
expect(hasAuthzCatalog()).toBe(true);
expect(getAuthzCatalog().permissions.has("post:read")).toBe(true);
} finally {
server.stop();
}
});
test("an app with no app/authz declarations boots without throwing", async () => {
const appDir = scaffold("no-decls", {});
const server = await startServer({
appDir,
hostname: "127.0.0.1",
port: 0,
mode: "development",
hmr: false,
});
try {
expect(getAuthzCatalog().permissions.size).toBe(0);
} finally {
server.stop();
}
});
test("a conflicting pair of declarations fails the boot, naming both source files", async () => {
const appDir = scaffold("conflict", {
"a.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": { risk: "low" } } });`,
"b.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": { risk: "high" } } });`,
});
let thrown: unknown;
try {
const server = await startServer({
appDir,
hostname: "127.0.0.1",
port: 0,
mode: "development",
hmr: false,
});
// Should be unreachable; stop it anyway so a regression doesn't leak a port.
server.stop();
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(Error);
const message = (thrown as Error).message;
expect(message).toContain("WRN-AUTHZ-CONFLICT");
expect(message).toContain(join(appDir, "authz", "a.ts"));
expect(message).toContain(join(appDir, "authz", "b.ts"));
});
});