diff --git a/docs/public-api-0.8.json b/docs/public-api-0.8.json index b01a003e..83d15413 100644 --- a/docs/public-api-0.8.json +++ b/docs/public-api-0.8.json @@ -506,7 +506,9 @@ "filterAuthorized", "filterCan", "generatePermissionTypes", + "getAuthzCatalog", "guardPermission", + "hasAuthzCatalog", "hasRole", "memoryAuditSink", "memoryPermissionStore", @@ -516,7 +518,8 @@ "requirePermission", "requireRole", "safeRecord", - "scopeKey" + "scopeKey", + "setAuthzCatalog" ], "./db": [ "authzMigrationSql", diff --git a/packages/authz/src/client.ts b/packages/authz/src/client.ts new file mode 100644 index 00000000..dba562d2 --- /dev/null +++ b/packages/authz/src/client.ts @@ -0,0 +1,44 @@ +/** + * A process-wide authorization catalog registry, mirroring `@wrnexus/db`'s + * `client.ts` (`setDb`/`getDb`/`hasDb`). It exists for the same reason: app + * middleware runs at module-eval time — `app/middleware/*.ts` registers + * `authzMiddleware({ catalog, store, ... })` itself, and it needs the merged + * catalog *then*, before the first request. Passing it through `ctx` does not + * work at that point, so the framework loads and merges every `app/authz/*.ts` + * declaration at boot (dev: `loadAppAuthzCatalog` + `setAuthzCatalog`, before + * middleware is resolved; prod: `mergeCatalogs` over the statically-imported + * declarations + `setAuthzCatalog`, before the server starts listening) and + * stashes it here. The framework never installs `authzMiddleware` itself — the + * app always chooses its own store and registers the middleware; this registry + * only makes the merged catalog reachable when it does. + */ + +import type { AuthzCatalog } from "./types.ts"; + +let catalog: AuthzCatalog | undefined; + +/** Set the process-wide authorization catalog (called by the framework at boot). */ +export function setAuthzCatalog(next: AuthzCatalog): AuthzCatalog { + catalog = next; + return next; +} + +/** The process-wide authorization catalog. Throws if it hasn't been set. */ +export function getAuthzCatalog(): AuthzCatalog { + if (!catalog) { + throw new Error( + "WRN-AUTHZ-SETUP: no authorization catalog is configured. The dev server and " + + "production build call loadAppAuthzCatalog()/mergeCatalogs() and setAuthzCatalog() " + + "automatically before your app's middleware runs. If you're seeing this, either " + + "getAuthzCatalog() ran before that boot step (e.g. at import time) or you're " + + "outside the normal boot path (a standalone script or test) and must call " + + "setAuthzCatalog(catalog) yourself first.", + ); + } + return catalog; +} + +/** Whether the process-wide authorization catalog has been set. */ +export function hasAuthzCatalog(): boolean { + return catalog !== undefined; +} diff --git a/packages/authz/src/index.ts b/packages/authz/src/index.ts index a05b6d20..e91b8443 100644 --- a/packages/authz/src/index.ts +++ b/packages/authz/src/index.ts @@ -143,6 +143,7 @@ export type { AuthorizationDecision, DecisionPolicy } from "./advanced.ts"; export { defineAuthz } from "./registry.ts"; export { mergeCatalogs, emptyCatalog } from "./catalog.ts"; export type { CatalogSource } from "./catalog.ts"; +export { setAuthzCatalog, getAuthzCatalog, hasAuthzCatalog } from "./client.ts"; export { memoryPermissionStore, cachedPermissionStore, scopeKey } from "./store.ts"; export type { PermissionStore, CachedPermissionStore, CacheOptions, GrantEffect } from "./store.ts"; export { memoryAuditSink, consoleAuditSink, safeRecord } from "./audit.ts"; diff --git a/packages/authz/test/client.test.ts b/packages/authz/test/client.test.ts new file mode 100644 index 00000000..9587c2d5 --- /dev/null +++ b/packages/authz/test/client.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, test } from "bun:test"; +import { pathToFileURL } from "node:url"; +import { join } from "node:path"; +import { defineAuthz } from "../src/registry.ts"; +import { mergeCatalogs } from "../src/catalog.ts"; +import { getAuthzCatalog, hasAuthzCatalog, setAuthzCatalog } from "../src/client.ts"; + +const CLIENT_URL = pathToFileURL(join(import.meta.dir, "..", "src", "client.ts")).href; + +describe("authz process-wide catalog singleton", () => { + // `catalog` is module-level state, and bun test does NOT isolate module + // instances between test files run in the same `bun test` invocation (a + // single import in one file is visible to every other file in the run). So + // "before any setAuthzCatalog call anywhere in the whole suite" cannot be + // observed reliably in-process — a fresh subprocess is the only way to + // guarantee the catalog genuinely has never been set. + test("getAuthzCatalog throws a setup error before setAuthzCatalog is ever called, in a fresh process", async () => { + const proc = Bun.spawn({ + cmd: [ + "bun", + "-e", + `const mod = await import(${JSON.stringify(CLIENT_URL)}); + if (mod.hasAuthzCatalog()) { console.log("UNEXPECTED_HAS_CATALOG"); process.exit(1); } + try { + mod.getAuthzCatalog(); + console.log("UNEXPECTED_NO_THROW"); + process.exit(1); + } catch (e) { + console.log("THREW:" + (e instanceof Error ? e.message : String(e))); + }`, + ], + stdout: "pipe", + stderr: "pipe", + cwd: join(import.meta.dir, ".."), + }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + expect(stdout).toContain("THREW:"); + // Names the fix, like getDb()'s "No database configured. Add `db: ...`" message. + expect(stdout).toContain("WRN-AUTHZ-SETUP"); + expect(stdout).toContain("setAuthzCatalog"); + }); + + test("setAuthzCatalog/getAuthzCatalog round-trip, and hasAuthzCatalog reflects the set state", () => { + const catalog = mergeCatalogs([ + { + source: "client.test.ts", + module: defineAuthz({ permissions: { "post:read": { title: "View posts" } } }), + }, + ]); + + const returned = setAuthzCatalog(catalog); + expect(returned).toBe(catalog); + expect(hasAuthzCatalog()).toBe(true); + expect(getAuthzCatalog()).toBe(catalog); + expect(getAuthzCatalog().permissions.get("post:read")).toEqual({ title: "View posts" }); + }); + + test("setAuthzCatalog overwrites a previously set catalog", () => { + const first = mergeCatalogs([ + { source: "a.ts", module: defineAuthz({ permissions: { "a:read": {} } }) }, + ]); + const second = mergeCatalogs([ + { source: "b.ts", module: defineAuthz({ permissions: { "b:read": {} } }) }, + ]); + setAuthzCatalog(first); + expect(getAuthzCatalog()).toBe(first); + setAuthzCatalog(second); + expect(getAuthzCatalog()).toBe(second); + expect(getAuthzCatalog().permissions.has("a:read")).toBe(false); + expect(getAuthzCatalog().permissions.has("b:read")).toBe(true); + }); +}); diff --git a/packages/cli/src/build.ts b/packages/cli/src/build.ts index 607cb9d2..dde41c08 100644 --- a/packages/cli/src/build.ts +++ b/packages/cli/src/build.ts @@ -604,6 +604,24 @@ export async function runBuild(appRoot: string): Promise { .join(", "); if (router.layouts.length) console.log(`✓ Layouts: ${router.layouts.length}`); + // Authorization declarations (app/authz/*.ts), statically imported like + // components/layouts — NOT baked into JSON like schemasJs, because the + // catalog contains policy FUNCTIONS, which JSON.stringify cannot carry. + // Each module is passed through by reference in ProdOptions.authz and + // merged into the process-wide catalog at prod startup (prod.ts), before + // the server begins listening, so a conflicting pair of declarations fails + // the boot instead of surfacing on the first request. A file with no + // default export becomes `module: undefined` here; prod.ts warns and skips + // it, matching the dev loader (authz-boot.ts). + const authzLit = router.authz + .map((a) => { + const v = `az${counter++}`; + imports.push(`import * as ${v} from ${JSON.stringify(fwd(a.file))};`); + return `{ source: ${JSON.stringify(fwd(a.file))}, module: ${v}.default }`; + }) + .join(", "); + if (router.authz.length) console.log(`✓ Authz: ${router.authz.length} declaration(s)`); + const entry = `// AUTO-GENERATED production server entry — do not edit. import { join } from "node:path"; import { createProductionServer } from ${JSON.stringify(PROD_MODULE)}; @@ -627,6 +645,7 @@ await createProductionServer( uiCssPath: join(import.meta.dir, "ui.css"), frameworkCssPath: join(import.meta.dir, "framework.css"), schemasJs: ${JSON.stringify(schemasJs)}, + authz: [${authzLit}], i18n: ${i18n ? JSON.stringify(i18n) : "undefined"}, db: ${config.db ? JSON.stringify(config.db) : "undefined"}, databases: ${config.databases ? JSON.stringify(config.databases) : "undefined"}, diff --git a/packages/dev-server/src/authz-boot.ts b/packages/dev-server/src/authz-boot.ts index d22022e7..4b24b056 100644 --- a/packages/dev-server/src/authz-boot.ts +++ b/packages/dev-server/src/authz-boot.ts @@ -20,6 +20,10 @@ export async function loadAppAuthzCatalog(appDir: string): Promise 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.`); diff --git a/packages/dev-server/src/index.ts b/packages/dev-server/src/index.ts index 4519d03b..e95a579e 100644 --- a/packages/dev-server/src/index.ts +++ b/packages/dev-server/src/index.ts @@ -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 { 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 { security: opts.security, observability: opts.observability, tenancy: opts.tenancy, + authz: authzCatalog, navigation: opts.navigation, clientRuntimes: pluginContributions.clientRuntimes, hub, diff --git a/packages/dev-server/src/prod.ts b/packages/dev-server/src/prod.ts index b54fe2ae..9b4832fe 100644 --- a/packages/dev-server/src/prod.ts +++ b/packages/dev-server/src/prod.ts @@ -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 => 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), diff --git a/packages/dev-server/src/runtime.ts b/packages/dev-server/src/runtime.ts index e8534bc2..f572b354 100644 --- a/packages/dev-server/src/runtime.ts +++ b/packages/dev-server/src/runtime.ts @@ -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). */ diff --git a/packages/dev-server/test/authz-startserver.test.ts b/packages/dev-server/test/authz-startserver.test.ts new file mode 100644 index 00000000..5644076d --- /dev/null +++ b/packages/dev-server/test/authz-startserver.test.ts @@ -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 { + 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")); + }); +});