feat: integrate module authorization

Wires composePlatformPermissionRegistry into apps/api's production
startup: startApi() discovers every installed module, composes the one
immutable platform permission registry (Core's own declarations plus
every module's), and only then constructs the shared PostgreSQL pool,
Better Auth, and the HTTP server. A discovery or composition failure —
an invalid manifest, a reserved core.* namespace claim, or a duplicate
declaration — propagates before anything exists to close; there is no
Core-only registry fallback. apps/api/src/platform-permissions.ts
resolves the repository root from its own file location, never
process.cwd(), so package-scoped test runs discover the right modules/
directory.

createApiApp/createGrantsRoutes now require the composed registry as
an injected authorization option, replacing the previous hard-coded
CORE_PERMISSION_REGISTRY; requirePermission continues to work
identically for Core-owned and module-owned permissions, since it has
no concept of the distinction.

Extends pnpm doctor with a modules.permissions check (reusing the
already-discovered module list, distinguishing reserved-namespace from
generic-duplicate failures, never re-discovering modules) and pnpm
modules:validate to compose the same registry before a module is
considered installable.

Adds focused coverage: startup-ordering and failure-isolation tests in
apps/api/tests/lifecycle.test.ts, module-owned-declaration enforcement
tests in apps/api/tests/authorization-middleware.test.ts, Doctor
composition tests in core/tests/doctor.test.ts, and a live PostgreSQL
end-to-end scenario proving a real installed module's permission is
discoverable, grantable, and deniable once the module is absent again
after a restart, without ever executing its server entrypoint.
This commit is contained in:
ekklesia
2026-07-24 14:24:50 -05:00
parent d9dd409aa3
commit edd7148aa8
17 changed files with 1205 additions and 46 deletions
+9 -5
View File
@@ -1,8 +1,8 @@
import { isAuthenticatedPrincipal } from "@ekklesia/contracts";
import {
type AuthorizationEvaluator,
type AuthorizationStore,
CORE_PERMISSION_REGISTRY,
import type {
AuthorizationEvaluator,
AuthorizationStore,
PermissionRegistry,
} from "@ekklesia/core/authorization";
import { type EkklesiaIdentityRuntime, IdentityRuntimeError } from "@ekklesia/core/identity";
import { Hono } from "hono";
@@ -12,6 +12,10 @@ import { createGrantsRoutes } from "./grants-routes.js";
export interface CreateApiAppAuthorizationOptions {
readonly evaluator: AuthorizationEvaluator;
/** The complete platform permission registry (Core's own declarations plus every installed
* module's) — always the caller-composed registry `startApi` produces via
* `composeStartupPermissionRegistry`, never a Core-only fallback constructed here. */
readonly registry: PermissionRegistry;
readonly store: AuthorizationStore;
}
@@ -80,7 +84,7 @@ export function createApiApp(options: CreateApiAppOptions): Hono {
"/",
createGrantsRoutes({
evaluator: options.authorization.evaluator,
registry: CORE_PERMISSION_REGISTRY,
registry: options.authorization.registry,
runtime,
store: options.authorization.store,
trustedOrigins: allowedOrigins,
+104
View File
@@ -0,0 +1,104 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { PermissionRegistry } from "@ekklesia/core/authorization";
import {
composePlatformPermissionRegistry,
discoverModules,
type DiscoveredModule,
} from "@ekklesia/core/modules";
export type PlatformPermissionConfigurationErrorCode = "PLATFORM_PERMISSION_CONFIGURATION_INVALID";
/** Never carries the underlying package.json path, filesystem error, module directory, manifest
* content, or any other machine detail — a broken repository layout is a startup-time
* configuration problem, not something to describe in detail to whatever eventually logs it. */
export class PlatformPermissionConfigurationError extends Error {
readonly code: PlatformPermissionConfigurationErrorCode;
constructor() {
super("Module discovery configuration could not be resolved.");
this.name = "PlatformPermissionConfigurationError";
this.code = "PLATFORM_PERMISSION_CONFIGURATION_INVALID";
this.stack = `${this.name}: ${this.message}`;
Object.freeze(this);
}
}
/**
* Resolves the repository root from this compiled/source file's own location, never
* `process.cwd()` — package-scoped test runs execute with `apps/api` as the working directory,
* which would silently point discovery at the wrong `modules/` directory. `apps/api/dist/*.js`
* (compiled) and `apps/api/src/*.ts` (source, under a test runner transforming TypeScript
* on the fly) sit at the identical depth from the repository root, so the same fixed number of
* `..` segments resolves correctly in both.
*/
function resolveRepositoryRoot(): string {
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
}
interface PackageVersionFile {
readonly version?: unknown;
}
async function readPackageVersion(packagePath: string): Promise<string> {
let packageData: PackageVersionFile;
try {
packageData = JSON.parse(await readFile(packagePath, "utf8")) as PackageVersionFile;
} catch {
throw new PlatformPermissionConfigurationError();
}
if (typeof packageData.version !== "string" || packageData.version.trim().length === 0) {
throw new PlatformPermissionConfigurationError();
}
return packageData.version;
}
export interface ComposeStartupPermissionRegistryOptions {
/** Test-only escape hatch: overrides the directory module discovery scans for installed
* modules. Never set by the executable entry point — production always discovers the real
* repository's `modules/` directory. Platform and Module SDK versions are always read from the
* real repository's own `package.json` files regardless of this override. */
readonly modulesDirectoryOverride?: string;
/** Test-only escape hatch: supplies an already-discovered module list directly, skipping the
* filesystem discovery step entirely, while still running the real `composePlatformPermissionRegistry`
* on it. Exists because a genuine exact permission-id collision between two modules — or between
* a module and Core — is unreachable through real discovery: module ids are unique (discovery
* itself rejects a duplicate) and every permission id is namespaced by its own module's id, so
* no two really-discovered modules can ever contribute the same permission id. Proving
* composition's own duplicate-rejection behavior, and that startup has created no pool before it
* runs, requires supplying deliberately conflicting declarations directly. Never set by the
* executable entry point; mutually exclusive with `modulesDirectoryOverride` in practice, since
* only one discovery-bypass is ever needed for a given scenario.
*/
readonly discoveredModulesOverride?: readonly DiscoveredModule[];
}
/**
* Discovers every installed module's manifest and composes the one immutable platform permission
* registry (Core's own declarations plus every module's) — the production source of truth
* `apps/api` enforces every request against. Only manifests are read; no module server entrypoint
* is imported or executed, and no module lifecycle hook runs. Read the platform and Module SDK
* versions only when this function actually executes, never at import time.
*/
export async function composeStartupPermissionRegistry(
options: ComposeStartupPermissionRegistryOptions = {},
): Promise<PermissionRegistry> {
if (options.discoveredModulesOverride) {
return composePlatformPermissionRegistry(options.discoveredModulesOverride);
}
const repositoryRoot = resolveRepositoryRoot();
const [platformVersion, moduleSdkVersion] = await Promise.all([
readPackageVersion(path.join(repositoryRoot, "package.json")),
readPackageVersion(path.join(repositoryRoot, "packages/module-sdk/package.json")),
]);
const modules = await discoverModules({
moduleSdkVersion,
modulesDirectory: options.modulesDirectoryOverride ?? path.join(repositoryRoot, "modules"),
platformVersion,
});
return composePlatformPermissionRegistry(modules);
}
+32 -8
View File
@@ -5,11 +5,13 @@ import {
createAuthorizationStore,
} from "@ekklesia/core/authorization";
import { createIdentityRuntime, type IdentityRateLimitOverride } from "@ekklesia/core/identity";
import type { DiscoveredModule } from "@ekklesia/core/modules";
import { serve, type ServerType } from "@hono/node-server";
import type { Hono } from "hono";
import { createApiApp } from "./app.js";
import { type ApiRuntimeConfig, createApiRuntimeConfig } from "./config.js";
import { type ApiDatabaseHandle, createApiDatabase } from "./database.js";
import { composeStartupPermissionRegistry } from "./platform-permissions.js";
const connectionTimeoutMs = 10_000;
const operationTimeoutMs = 10_000;
@@ -24,6 +26,13 @@ export interface StartApiOptions {
/** Test-only escape hatch: never set by the executable entry point. See
* `IdentityRateLimitOverride` for why production must leave this unset. */
readonly rateLimitOverride?: IdentityRateLimitOverride;
/** Test-only escape hatch: overrides the directory permission-composition module discovery
* scans. Never set by the executable entry point. See `composeStartupPermissionRegistry`. */
readonly modulesDirectoryOverride?: string;
/** Test-only escape hatch: supplies an already-discovered module list directly to permission
* composition, skipping filesystem discovery entirely. Never set by the executable entry
* point. See `composeStartupPermissionRegistry`. */
readonly discoveredModulesOverride?: readonly DiscoveredModule[];
}
async function safeCloseDatabase(handle: ApiDatabaseHandle): Promise<void> {
@@ -54,18 +63,33 @@ function bindServer(app: Hono, host: string, port: number): Promise<ServerType>
}
/**
* Explicit runtime composition: constructs the one shared PostgreSQL pool (identity and
* authorization each get a typed Drizzle view over it — see `./database.js`), the Core identity
* runtime, the Core authorization store and evaluator, and the Hono application, then starts the
* Node HTTP server. Returns a handle with an idempotent `shutdown()` so both the executable entry
* point and tests can stop the server and close the shared pool deterministically. Never applies
* migrations or generates schema — the database must already be migrated through
* `pnpm migrations:apply`.
* Explicit runtime composition, in a fixed order: discover every installed module's manifest and
* compose the one immutable platform permission registry from Core's own declarations plus every
* module's (`./platform-permissions.js`); only then construct the one shared PostgreSQL pool
* (identity and authorization each get a typed Drizzle view over it — see `./database.js`), the
* Core identity runtime, the Core authorization store and evaluator, and the Hono application;
* finally start the Node HTTP server. Permission composition happens before any pool, Better
* Auth instance, or HTTP server exists, so a discovery or composition failure — an invalid
* manifest, a dependency-graph problem, a module claiming the reserved `core.*` permission
* namespace, or a duplicate permission declaration — leaves nothing to close: it propagates
* directly, and startup never falls back to a Core-only registry. Returns a handle with an
* idempotent `shutdown()` so both the executable entry point and tests can stop the server and
* close the shared pool deterministically. Never applies migrations or generates schema — the
* database must already be migrated through `pnpm migrations:apply`.
*/
export async function startApi(
config: ApiRuntimeConfig,
options: StartApiOptions = {},
): Promise<RunningApi> {
const permissionRegistry = await composeStartupPermissionRegistry({
...(options.modulesDirectoryOverride === undefined
? {}
: { modulesDirectoryOverride: options.modulesDirectoryOverride }),
...(options.discoveredModulesOverride === undefined
? {}
: { discoveredModulesOverride: options.discoveredModulesOverride }),
});
const databaseHandle = createApiDatabase(config.databaseUrl, {
connectionTimeoutMs,
operationTimeoutMs,
@@ -91,7 +115,7 @@ export async function startApi(
});
const app = createApiApp({
authorization: { evaluator, store: authorizationStore },
authorization: { evaluator, registry: permissionRegistry, store: authorizationStore },
runtime,
trustedOrigins: config.identity.trustedOrigins,
});