The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Accounts 2: actor context, role and permission registries, audit writer
Claudebce01e8abff1
diff --git a/src/proxy.ts b/src/proxy.tsindex dba67ef8..78d0e81f 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -3,7 +3,7 @@ import { APPS } from "@/lib/catalog/apps";import { recordForPath, unknownHubMode } from "@/lib/record-pages";import { countsAsView, SHARE_VIEW_HEADER, shareRoute } from "@/lib/share";import { clientIp, crossSite, hostAllowed, LoginGuard } from "@/server/auth";-import { refreshSession, resolvePrincipal } from "@/server/identity/principal";+import { CLIENT_IP_HEADER, refreshSession, resolvePrincipal } from "@/server/identity/principal";import { refusal } from "@/server/identity/refusals";import { signInRequired } from "@/server/mode";import { recordExists } from "@/server/records";@@ -37,7 +37,7 @@ const crossSiteExempt = (pathname: string) => CROSS_SITE_EXEMPT.some((r) => ruleconst noStore = (pathname: string) => NO_STORE.some((r) => ruleMatches(r, pathname));/** The header Better Auth reads the client's address from; only this proxy may write it. */-export const CLIENT_IP_HEADER = "x-fuobe-client-ip";+export { CLIENT_IP_HEADER };/*** The request headers handed on: any x-fuobe-client-ip a client sent is dropped, and one is written only when adiff --git a/src/server/access/actor.ts b/src/server/access/actor.tsnew file mode 100644index 00000000..2620dcf5--- /dev/null+++ b/src/server/access/actor.ts@@ -0,0 +1,94 @@+import "server-only";+import { AsyncLocalStorage } from "node:async_hooks";+import type { Actor } from "../identity/principal";++/**+ * Who is acting, wherever the code runs (docs/research/accounts-8.md §7.1, §7.11). A request scope rides on+ * AsyncLocalStorage: route handlers open one through handler() (src/server/access/route.ts), runners open one per row+ * with runAs(row owner), and housekeeping runs asSystem. Server modules ask currentActor(), which throws when nothing+ * opened a scope: code that acts for nobody is a bug, never a silent "the owner".+ *+ * This module imports nothing that touches the database, so the test setup (tests/setup/actor.ts) can load it before+ * a test file has chosen its data folder.+ */++export type { Actor };++/** What a request (or a runner's turn) knows about who is acting and from where. */+export interface RequestScope {+ /** Null on a public route answered for nobody (a share file, the sign-in form). */+ actor: Actor | null;+ ip?: string | null;+ userAgent?: string | null;+ method?: string;+ path?: string;+}++declare global {+ var __fuobeAccessScope: AsyncLocalStorage<RequestScope> | undefined;+}++/** One store per process, shared by every bundle that loads this module (instrumentation and route handlers). */+const store = (): AsyncLocalStorage<RequestScope> => (globalThis.__fuobeAccessScope ??= new AsyncLocalStorage<RequestScope>());++/** The local owner: "Just me on this computer", and the person every test acts as unless it says otherwise. */+export const LOCAL_OWNER: Actor = Object.freeze({ userId: "u_owner", role: "owner", via: "local", scopes: ["full"] }) as Actor;++/** The server itself: housekeeping, sweeps and boot work that belong to no one. */+export const SYSTEM: Actor = Object.freeze({ userId: "system", role: "system", via: "system", scopes: ["full"] }) as Actor;++export class NoActorError extends Error {+ constructor() {+ super("No one is acting here: wrap this in handler(), runAs() or asSystem()");+ this.name = "NoActorError";+ }+}++/** The scope this code runs in, if any. */+export function requestScope(): RequestScope | undefined {+ return store().getStore();+}++/** Who is acting, or null (no scope, or a public route answered for nobody). */+export function maybeActor(): Actor | null {+ return store().getStore()?.actor ?? null;+}++/** Who is acting. Throws when no one is: every route, runner and sweep opens a scope first. */+export function currentActor(): Actor {+ const actor = maybeActor();+ if (!actor) throw new NoActorError();+ return actor;+}++/** Run `fn` inside a scope (handler() opens one per request). */+export function withScope<T>(scope: RequestScope, fn: () => T): T {+ return store().run(scope, fn);+}++/**+ * Run `fn` as `actor`: a runner working on a row its owner started, an after() continuation, Assist acting for the+ * chat's author. Timers and promises started inside keep the actor (AsyncLocalStorage follows them).+ */+export function runAs<T>(actor: Actor, fn: () => T): T {+ return store().run({ actor }, fn);+}++/** Run `fn` as the server itself: timers that sweep everyone's rows start here, then act per row with runAs. */+export function asSystem<T>(fn: () => T): T {+ return store().run({ actor: SYSTEM }, fn);+}++/**+ * The actor now, as a function that runs later work as them: `const resume = captureActor(); after(() => resume(work))`.+ * Explicit, so a continuation never depends on where the work happens to be scheduled from.+ */+export function captureActor(): <T>(fn: () => T) => T {+ const actor = currentActor();+ return (fn) => runAs(actor, fn);+}++/** For the test harness only: make the rest of this synchronous run (and what it starts) act as `actor`. */+export function enterAs(actor: Actor | null): void {+ store().enterWith({ actor });+}diff --git a/src/server/access/audit.ts b/src/server/access/audit.tsnew file mode 100644index 00000000..3f3ecaa8--- /dev/null+++ b/src/server/access/audit.ts@@ -0,0 +1,84 @@+import "server-only";+import { appendAudit, verifyAuditChain, type AuditChainCheck } from "../identity/audit-log";+import { requestScope } from "./actor";++/**+ * The audit log as the rest of Fuobe writes it (docs/research/accounts-8.md §7.14): `audit(action, target, meta)`+ * takes who acted, from which address and with which browser from the request scope, and appends a row to the+ * hash-chained, append-only `audit_log` (src/server/identity/audit-log.ts). Core events: auth.*, token.*, people.*,+ * team.*, install.*, keys.* (setting names and masked prefixes only), limits.*, content.share|move|grant, `denied`+ * (every 403 a route answers) and `denied.hidden` (404s for records the actor may not see, at most one a minute per+ * person and route).+ *+ * Secrets never reach the log: meta fields named like one (password, secret, token, apiKey…) are replaced before the+ * row is written, whatever the caller passed.+ */++export interface AuditTarget {+ kind: string;+ id?: string | null;+}++const SECRET_NAME = /(pass(word)?|secret|token|api_?key|private_?key|authorization|cookie)$/i;+/** Names that look like a secret's but only describe one. */+const DESCRIBES = /(prefix|id|name|kind|count|at|tokens)$/i;++function redact(meta: Record<string, unknown>): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(meta)) {+ if (SECRET_NAME.test(k) && !DESCRIBES.test(k) && typeof v === "string" && v) out[k] = "[redacted]";+ else if (v && typeof v === "object" && !Array.isArray(v)) out[k] = redact(v as Record<string, unknown>);+ else out[k] = v;+ }+ return out;+}++/** Append an entry for whoever is acting now (the request's person, a runner's row owner, or the server). */+export function audit(action: string, target?: AuditTarget | null, meta: Record<string, unknown> = {}): void {+ const scope = requestScope();+ const actor = scope?.actor ?? null;+ appendAudit({+ action,+ actorId: actor?.userId ?? null,+ via: actor?.via ?? null,+ targetKind: target?.kind ?? null,+ targetId: target?.id ?? null,+ meta: redact({+ ...(actor?.impersonatorId && { impersonator: actor.impersonatorId }),+ ...(actor?.tokenId && { tokenId: actor.tokenId }),+ ...meta,+ }),+ ip: scope?.ip ?? null,+ userAgent: scope?.userAgent ?? null,+ });+}++/** A 403: what was refused and why (a permission, a token's scope, a code like REAUTH). */+export function auditDenied(reason: string, meta: Record<string, unknown> = {}): void {+ const scope = requestScope();+ audit("denied", null, { method: scope?.method, path: scope?.path, reason, ...meta });+}++declare global {+ var __fuobeHiddenDenials: Map<string, number> | undefined;+}++const HIDDEN_EVERY_MS = 60_000;++/**+ * A 404 for a record that exists but isn't the actor's to see. Logged at most once a minute per person and route, so+ * probing ids can't flood the log (the scoping package calls it through NotFoundError({ hidden: true })).+ */+export function auditHidden(target?: AuditTarget | null): void {+ const scope = requestScope();+ const key = `${scope?.actor?.userId ?? "-"} ${scope?.method ?? ""} ${scope?.path ?? ""}`;+ const seen = (globalThis.__fuobeHiddenDenials ??= new Map());+ const now = Date.now();+ const last = seen.get(key);+ if (last !== undefined && now - last < HIDDEN_EVERY_MS) return;+ if (seen.size > 5000) for (const [k, t] of seen) if (now - t >= HIDDEN_EVERY_MS) seen.delete(k);+ seen.set(key, now);+ audit("denied.hidden", target, { method: scope?.method, path: scope?.path });+}++export { verifyAuditChain, type AuditChainCheck };diff --git a/src/server/access/errors.ts b/src/server/access/errors.tsnew file mode 100644index 00000000..587b0736--- /dev/null+++ b/src/server/access/errors.ts@@ -0,0 +1,57 @@+import "server-only";++/**+ * The refusals a route handler answers for (docs/research/accounts-8.md §7.1, §7.4, §7.12): server code throws one and+ * handler() turns it into the JSON answer, `{ error, code? }` with its status. Every 403 is audited as `denied`; a+ * hidden record (a 404 for something that exists but isn't the actor's to see) as `denied.hidden`, at most once a+ * minute per person and route.+ */++export class AccessError extends Error {+ constructor(+ message: string,+ readonly status: number,+ readonly code?: string,+ ) {+ super(message);+ this.name = new.target.name;+ }+}++/** 404: no such thing — or one the actor may not know exists (`hidden`, which is audited). */+export class NotFoundError extends AccessError {+ constructor(+ message = "Not found",+ readonly hidden = false,+ ) {+ super(message, 404);+ }+}++/** 403: the actor is known and may not do this. */+export class ForbiddenError extends AccessError {+ constructor(message = "You don't have access to this.", code?: string) {+ super(message, 403, code);+ }+}++/** 401: nobody (or an invalid token) asking for something that needs a person. */+export class UnauthenticatedError extends AccessError {+ constructor(message = "Sign in, or send an API token as Authorization: Bearer fuobe_…", code?: string) {+ super(message, 401, code);+ }+}++/** 402: a limit or a credit balance stops this run (the meter and plans packages throw it with their line). */+export class PaymentRequiredError extends AccessError {+ constructor(message = "This would go over your limit.", code = "LIMIT_REACHED") {+ super(message, 402, code);+ }+}++/** 403 REAUTH: a sensitive action needs the session confirmed in the last 10 minutes ("Confirm it's you", §7.2). */+export class ReauthRequiredError extends AccessError {+ constructor(message = "Confirm it's you to continue.") {+ super(message, 403, "REAUTH");+ }+}diff --git a/src/server/access/gates.ts b/src/server/access/gates.tsnew file mode 100644index 00000000..d036df4c--- /dev/null+++ b/src/server/access/gates.ts@@ -0,0 +1,40 @@+import "server-only";+import type { Actor } from "./actor";+import { ForbiddenError } from "./errors";++/**+ * Gates for actions that cost nothing but still have limits (docs/research/accounts-8.md §7.12): creating an API+ * token, a share link, an upload, a team, adding one's own keys. The core registers no checks, so every gate is open+ * (a no-op); the entitlements and plans packages register theirs ("Your plan doesn't include share links."). A check+ * returns a refusal or null.+ */++export type GateKind = "token.create" | "share.create" | "upload" | "team.create" | "keys.own" | (string & {});++export interface GateRefusal {+ code: string;+ message: string;+}++type GateCheck = (actor: Actor) => GateRefusal | null;++const CHECKS = new Map<string, GateCheck[]>();++export function registerGate(kind: GateKind, check: GateCheck): void {+ CHECKS.set(kind, [...(CHECKS.get(kind) ?? []), check]);+}++/** The first refusal for this action, or null when it may go ahead. */+export function gateRefusal(kind: GateKind, actor: Actor): GateRefusal | null {+ for (const check of CHECKS.get(kind) ?? []) {+ const r = check(actor);+ if (r) return r;+ }+ return null;+}++/** Refuse (a 403 the route handler answers and audits) when a check says no. */+export function gate(kind: GateKind, actor: Actor): void {+ const r = gateRefusal(kind, actor);+ if (r) throw new ForbiddenError(r.message, r.code);+}diff --git a/src/server/access/permissions.ts b/src/server/access/permissions.tsnew file mode 100644index 00000000..9182da0e--- /dev/null+++ b/src/server/access/permissions.ts@@ -0,0 +1,204 @@+import "server-only";+import { db } from "../db";+import { runAs, type Actor } from "./actor";++/**+ * Roles and permissions (docs/research/accounts-8.md §7.3). Both are registries: the core registers the install roles+ * owner, admin and member and the core permissions; later packages add theirs (the audit viewer adds `auditor` and+ * `audit.view` holders, the Platform admin adds `billing`, `moderator` and `support` with `billing.*` and+ * `moderation.*`). Routes declare the permission they need (`handler({ access: "perm:install.settings" })`) and never+ * test a role name themselves.+ *+ * Team roles (owner, admin, member shown as Editor, viewer) are answered by effectiveTeamRole() alone, so the clamps+ * that come later (view-only seats, view-as) apply everywhere at once.+ */++// ---------------------------------------------------------------------------+// Permissions++const PERMISSIONS = new Set<string>([+ "install.settings",+ "install.mode",+ "people.view",+ "people.manage",+ "people.roles",+ "usage.view_all",+ "limits.manage",+ "keys.install",+ "teams.create",+ "teams.manage_all",+ "audit.view",+ "data.manage",+ "gpu.manage",+ "approvals.decide",+ "support.view_as",+ "credits.adjust",+]);++/** Add a permission (a package's own: `billing.refund`, `moderation.review`…). */+export function registerPermission(name: string): void {+ PERMISSIONS.add(name);+}++export const permissionExists = (name: string): boolean => PERMISSIONS.has(name);++export function permissions(): string[] {+ return [...PERMISSIONS];+}++// ---------------------------------------------------------------------------+// Install roles++export interface RoleDef {+ /** Shown in people lists and pickers. */+ label: string;+ /** Higher outranks lower: who may act on whom (§7.3 target matrix) compares ranks. */+ rank: number;+ /** Permissions held: exact names, a family (`billing.*`) or everything (`*`). */+ grants: string[];+}++const ROLES = new Map<string, RoleDef>([+ ["owner", { label: "Owner", rank: 100, grants: ["*"] }],+ [+ "admin",+ {+ label: "Admin",+ rank: 50,+ // Everything an install needs run day to day; the mode, roles, view-as and credit adjustments stay with the owner.+ grants: [+ "install.settings",+ "people.view",+ "people.manage",+ "usage.view_all",+ "limits.manage",+ "keys.install",+ "teams.create",+ "teams.manage_all",+ "audit.view",+ "data.manage",+ "gpu.manage",+ "approvals.decide",+ ],+ },+ ],+ // Whether members may create teams is an install setting (teams.create), refined by the teams package.+ ["member", { label: "Member", rank: 10, grants: [] }],+]);++/** Add or replace an install role (`auditor`, `billing`, `moderator`, `support`). `owner` is fixed. */+export function registerRole(name: string, def: RoleDef): void {+ if (name === "owner") throw new Error("The owner role is fixed");+ ROLES.set(name, def);+}++export const roleExists = (name: string): boolean => ROLES.has(name);+export const roleDef = (name: string): RoleDef | undefined => ROLES.get(name);++export function roles(): { name: string; def: RoleDef }[] {+ return [...ROLES].map(([name, def]) => ({ name, def })).sort((a, b) => b.def.rank - a.def.rank);+}++const grantCovers = (grant: string, permission: string) =>+ grant === "*" || grant === permission || (grant.endsWith(".*") && permission.startsWith(grant.slice(0, -1)));++/** Whether an install role holds a permission. Unknown roles hold nothing. */+export function roleCan(role: string, permission: string): boolean {+ return (ROLES.get(role)?.grants ?? []).some((g) => grantCovers(g, permission));+}++/**+ * Whether the actor may do something that needs `permission`. The server itself (asSystem) may; a view-as session+ * may not (it is read-only, §9.5 E5b); a token needs the admin or full scope for any install permission.+ */+export function can(actor: Actor | null | undefined, permission: string): boolean {+ if (!actor) return false;+ if (actor.via === "system") return true;+ if (actor.impersonatorId) return false;+ if (actor.via === "token" && !actor.scopes.some((s) => s === "full" || s === "admin")) return false;+ return roleCan(actor.role, permission);+}++// ---------------------------------------------------------------------------+// Team roles++export type TeamRole = "owner" | "admin" | "member" | "viewer";++/** Strongest first. `member` is shown as "Editor". */+export const TEAM_ROLES: readonly TeamRole[] = ["owner", "admin", "member", "viewer"];+export const TEAM_ROLE_LABEL: Record<TeamRole, string> = { owner: "Owner", admin: "Admin", member: "Editor", viewer: "Viewer" };++const teamRank = (r: TeamRole) => TEAM_ROLES.length - TEAM_ROLES.indexOf(r);++/** Whether `role` is at least `min` (an Editor action needs "member"). */+export function teamRoleAtLeast(role: TeamRole | null | undefined, min: TeamRole): boolean {+ return !!role && teamRank(role) >= teamRank(min);+}++/**+ * Clamps applied after the stored membership, in order: each may lower the role (a view-only seat is a Viewer,+ * §9.5 E6), never raise it. Packages register theirs.+ */+export type TeamRoleClamp = (actor: Actor, workspaceId: string, role: TeamRole) => TeamRole;+const CLAMPS: TeamRoleClamp[] = [+ // View-as is read-only (§9.5 E5b): whoever is looking can't change anything.+ (actor, _w, role) => (actor.impersonatorId ? "viewer" : role),+];++export function registerTeamRoleClamp(clamp: TeamRoleClamp): void {+ CLAMPS.push(clamp);+}++/**+ * The actor's role in a workspace (their personal one, a team, or the install catalog), or null when they aren't a+ * member. The only function that answers a team role.+ */+export function effectiveTeamRole(actor: Actor, workspaceId: string): TeamRole | null {+ if (actor.via === "system") return "owner";+ const row = db().prepare("SELECT role FROM workspace_members WHERE workspace_id = ? AND user_id = ?").get(workspaceId, actor.userId) as { role: string } | undefined;+ if (!row || !(TEAM_ROLES as readonly string[]).includes(row.role)) return null;+ let role = row.role as TeamRole;+ for (const clamp of CLAMPS) {+ const next = clamp(actor, workspaceId, role);+ // A clamp only ever lowers.+ if (teamRank(next) < teamRank(role)) role = next;+ }+ return role;+}++// ---------------------------------------------------------------------------+// Acting for a row's owner++/** The words a runner fails a row with when the person who started it was turned off (§7.11). */+export const ACCOUNT_OFF_MESSAGE = "Paused: the account that started this is off.";++export class AccountOffError extends Error {+ constructor() {+ super(ACCOUNT_OFF_MESSAGE);+ this.name = "AccountOffError";+ }+}++/** The person every row belongs to until rows record who made them (the scoping package adds created_by). */+export const INSTALL_OWNER_ID = "u_owner";++/** Who started a stored row: its created_by once rows have one, else the install owner (everything is theirs today). */+export function rowOwner(row: object): string {+ return (row as { created_by?: string | null }).created_by || INSTALL_OWNER_ID;+}++/**+ * The actor a runner works as for a row started by `userId` (the install owner when the row names nobody yet). Throws+ * AccountOffError when that person is pending, turned off, deleted or dormant.+ */+export function ownerActor(userId?: string | null): Actor {+ const id = userId || INSTALL_OWNER_ID;+ const p = db().prepare("SELECT id, role, status, dormant FROM users WHERE id = ?").get(id) as { id: string; role: string; status: string; dormant: number } | undefined;+ if (!p || p.status !== "active" || p.dormant) throw new AccountOffError();+ return { userId: p.id, role: p.role, via: "runner", scopes: ["full"] };+}++/** Run `fn` as the row's owner (see ownerActor). */+export function runAsOwner<T>(userId: string | null | undefined, fn: () => T): T {+ return runAs(ownerActor(userId), fn);+}diff --git a/src/server/access/route.ts b/src/server/access/route.tsnew file mode 100644index 00000000..7893a261--- /dev/null+++ b/src/server/access/route.ts@@ -0,0 +1,177 @@+import "server-only";+import { CLIENT_IP_HEADER, type Principal, resolvePrincipal } from "../identity/principal";+import { refusal } from "../identity/refusals";+import { withScope, type Actor } from "./actor";+import { auditDenied, auditHidden } from "./audit";+import { AccessError, ForbiddenError, NotFoundError, UnauthenticatedError } from "./errors";+import { can, permissionExists } from "./permissions";++/**+ * Every route handler goes through handler() (docs/research/accounts-8.md §7.1, §7.3, §7.18): it resolves who is+ * asking (the principal: a token, a session, or Just me on this computer), checks what the route declares, and runs+ * the route inside a request scope, so server code can ask currentActor() and audit() knows who acted. Next 16 rule:+ * the proxy is optimistic; this is where authorization is checked again, for every request.+ *+ * export const POST = handler({ access: "perm:install.settings" }, async (request) => { … });+ *+ * Access kinds:+ * - "signed-in" (the default): any person — a session, a token, or the local owner.+ * - "browser": a session or the local owner, never an API token (tokens are managed from a browser, §7.10).+ * - "perm:<name>": a person whose install role holds that permission (src/server/access/permissions.ts).+ * - "public": anyone; the route answers for nobody when no one is signed in (sign-in, share files, the identity+ * router). A known person is still the actor.+ *+ * Token scopes: a bearer token may call a route only when one of its scopes is listed (Full always may). By default+ * reads (GET, HEAD) take any scope, writes take Generate or Admin, and permission routes take Admin.+ *+ * Refusals thrown inside (src/server/access/errors.ts) become their answers: 404, 403, 401, 402 and 403 REAUTH. Every+ * 403 is audited as `denied`, including one the route answers itself.+ */++export type Access = "public" | "signed-in" | "browser" | `perm:${string}`;+export type TokenScope = "full" | "read" | "generate" | "admin";++export interface HandlerOptions {+ access?: Access;+ /** The token scopes allowed besides Full (see above for the defaults). */+ scopes?: TokenScope[];+}++// ---------------------------------------------------------------------------+// Registries++/**+ * Restricted session kinds (§7.1): a session that may only finish one step — enrolling two-step (`enroll-2fa`),+ * proving it (`verify-2fa`), looking at someone's library (`view-as`), restoring a deleted account+ * (`restore-account`), accepting new terms (`accept-terms`). Each kind's packages register the paths it may reach;+ * anywhere else the session counts as signed out.+ */+const RESTRICTED_KINDS = new Map<string, (pathname: string, method: string) => boolean>();++export function registerRestrictedKind(kind: string, allows: (pathname: string, method: string) => boolean): void {+ RESTRICTED_KINDS.set(kind, allows);+}++export function restrictedAllows(kind: string, pathname: string, method: string): boolean {+ return RESTRICTED_KINDS.get(kind)?.(pathname, method) ?? false;+}++/**+ * The substituteActor seam (§9.5 E5b view-as): given the real actor and the request, a registered substitution+ * returns who the request acts as, or null to leave it. The first that answers wins, and the real person is kept as+ * `impersonatorId` (audit entries name them; permissions and team roles treat the request as read-only). None in the+ * core.+ */+type Substitute = (actor: Actor, request: Request) => Actor | null;+const SUBSTITUTES: Substitute[] = [];++export function registerActorSubstitute(fn: Substitute): void {+ SUBSTITUTES.push(fn);+}++export function substituteActor(actor: Actor, request: Request): Actor {+ for (const fn of SUBSTITUTES) {+ const next = fn(actor, request);+ if (next) return { ...next, impersonatorId: next.impersonatorId ?? actor.userId };+ }+ return actor;+}++// ---------------------------------------------------------------------------+// The wrapper++/** Every route file's handlers, by file, for the route sweep (tests/route-sweep.test.ts). */+const WRAPPED = new WeakSet<object>();+export const isWrapped = (fn: unknown): boolean => typeof fn === "function" && WRAPPED.has(fn);++const READS = new Set(["GET", "HEAD", "OPTIONS"]);++function allowedScopes(opts: HandlerOptions, method: string): TokenScope[] {+ if (opts.scopes) return opts.scopes;+ if (opts.access?.startsWith("perm:")) return ["admin"];+ return READS.has(method) ? ["read", "generate", "admin"] : ["generate", "admin"];+}++const json = (status: number, error: string, code?: string, headers?: HeadersInit) => Response.json({ error, ...(code && { code }) }, { status, headers });++/** Nobody (or a refused person) asking for a route that needs someone: the same answers the proxy gives. */+function signedOut(principal: Principal): Response {+ if (principal.code && principal.code !== "INVALID_TOKEN") {+ const r = refusal(principal.code);+ return json(r.status, r.message, r.code);+ }+ const error = principal.code === "INVALID_TOKEN" ? "That API token isn't valid. Create a new one in Settings → Security." : new UnauthenticatedError().message;+ return json(401, error, undefined, { "WWW-Authenticate": 'Bearer realm="fuobe"' });+}++/** Why this actor may not call this route, or null. */+function refusedFor(actor: Actor, opts: HandlerOptions, method: string): ForbiddenError | null {+ const access = opts.access ?? "signed-in";+ if (actor.via === "token" && !actor.scopes.includes("full") && !actor.scopes.some((s) => (allowedScopes(opts, method) as string[]).includes(s))) {+ return new ForbiddenError("This API token's scope doesn't allow that.", "TOKEN_SCOPE");+ }+ if (access === "browser" && actor.via !== "session" && actor.via !== "local") {+ return new ForbiddenError("Do this from a signed-in browser: an API token can't.", "BROWSER_ONLY");+ }+ if (access.startsWith("perm:")) {+ const permission = access.slice(5);+ if (!permissionExists(permission)) throw new Error(`Unknown permission ${permission}`);+ if (!can(actor, permission)) return new ForbiddenError("You don't have access to this. Ask an admin.", "FORBIDDEN");+ }+ return null;+}++/** Turn a thrown refusal into its answer (others are rethrown: a 500, as before). */+function answer(e: unknown): Response {+ if (!(e instanceof AccessError)) throw e;+ if (e instanceof NotFoundError && e.hidden) auditHidden();+ if (e.status === 403) auditDenied(e.code ?? "forbidden", { message: e.message });+ return json(e.status, e.message, e.code);+}++/**+ * Wrap a route handler. The request scope it opens carries the actor (null on a public route answered for nobody), the+ * client's address (only when a trusted proxy reported it) and user agent, the method and the path.+ */+export function handler<Req extends Request = Request, C = unknown>(+ opts: HandlerOptions,+ fn: (request: Req, ctx: C) => Response | Promise<Response>,+): (request: Req, ctx?: C) => Promise<Response> {+ const access = opts.access ?? "signed-in";+ if (access.startsWith("perm:") && !permissionExists(access.slice(5))) throw new Error(`Unknown permission ${access.slice(5)}`);+ // Next always passes the context; a route without params (or a test calling one) may leave it out.+ const wrapped = async (request: Req, ctx?: C): Promise<Response> => {+ const url = new URL(request.url);+ const method = request.method.toUpperCase();+ const principal = await resolvePrincipal(request);+ let actor = principal.actor;+ // A restricted session (finishing two-step, accepting terms…) outside its own routes is signed out.+ if (actor?.restricted && !restrictedAllows(actor.restricted, url.pathname, method)) actor = null;+ if (actor) actor = substituteActor(actor, request);+ const scope = {+ actor,+ ip: request.headers.get(CLIENT_IP_HEADER),+ userAgent: request.headers.get("user-agent"),+ method,+ path: url.pathname,+ };+ return withScope(scope, async () => {+ if (!actor && access !== "public") return signedOut(principal);+ if (actor) {+ const refused = refusedFor(actor, opts, method);+ if (refused) return answer(refused);+ }+ let res: Response;+ try {+ res = await fn(request, ctx as C);+ } catch (e) {+ return answer(e);+ }+ // A 403 the route answered itself (a wrong current password, MCP's Origin check) is a denial too.+ if (res.status === 403) auditDenied("route");+ return res;+ });+ };+ WRAPPED.add(wrapped);+ return wrapped;+}diff --git a/src/server/db.ts b/src/server/db.tsindex 6f90bf00..ec0dd919 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -714,6 +714,11 @@ const MIGRATIONS: string[] = [create index "auth_session_userId_idx" on "auth_session" ("userId");create index "auth_account_userId_idx" on "auth_account" ("userId");create index "auth_verification_identifier_idx" on "auth_verification" ("identifier");`,+ // originals (o/acc-2): the audit log refuses DELETE as it already refuses UPDATE (docs/research/accounts-8.md §7.14),+ // so a row can only be added. Only the retention purge (acc-34) removes rows: it lifts this trigger inside its own+ // transaction and writes an entry of its own.+ `CREATE TRIGGER IF NOT EXISTS audit_log_no_delete BEFORE DELETE ON audit_log+ BEGIN SELECT RAISE(ABORT, 'audit_log is append-only'); END;`,];/** The index of the migration whose SQL contains `fragment` (-1 when none does): tests and the bootstrap name migrations by what they do. */diff --git a/src/server/identity/audit-log.ts b/src/server/identity/audit-log.tsindex 98622d9f..955bcdbe 100644--- a/src/server/identity/audit-log.ts+++ b/src/server/identity/audit-log.ts@@ -5,8 +5,9 @@ import { db } from "../db";/*** The append-only audit log's storage (docs/research/accounts-8.md §7.14): each row carries the hash of the row* before it, so a changed or removed row breaks the chain from there on. This is the bare writer the identity core- * needs (imports, sign-ins, admin operations); the actor-aware `audit()` that reads the request scope arrives with- * acc-2 and writes through it. Never put a secret in `meta` (a password, a token, a key): names and prefixes only.+ * needs (imports, sign-ins, admin operations); the actor-aware `audit()` (src/server/access/audit.ts) reads the+ * request scope and writes through it. The table refuses UPDATE and DELETE (triggers in db.ts). Never put a secret+ * in `meta` (a password, a token, a key): names and prefixes only.*/export interface AuditEntry {@@ -69,12 +70,34 @@ export function recentAudit(limit = 50): Row[] {return db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT ?").all(limit) as Row[];}-/** Whether every row still hashes to what the next one remembers: false from the first changed row on. */-export function auditChainIntact(): boolean {+export interface AuditChainCheck {+ ok: boolean;+ /** Rows checked. */+ rows: number;+ /** The time of the last row that verified ("Records verified up to {time}"); null when none did. */+ verifiedUpTo: number | null;+ /** The first row that doesn't match what the row before it remembers ("The record changed after {time}"). */+ brokenAt?: { seq: number; at: number };+}++/**+ * Walk the chain from the first row: each row must remember the hash of the row before it and hash to its own. A row+ * changed in place, removed from the middle or inserted out of order breaks it from there on.+ */+export function verifyAuditChain(): AuditChainCheck {let prev = "";+ let rows = 0;+ let verifiedUpTo: number | null = null;for (const r of db().prepare("SELECT * FROM audit_log ORDER BY seq").iterate() as Iterable<Row>) {- if (r.prev_hash !== prev || r.hash !== rowHash(prev, r)) return false;+ if (r.prev_hash !== prev || r.hash !== rowHash(prev, r)) return { ok: false, rows, verifiedUpTo, brokenAt: { seq: r.seq, at: r.at } };prev = r.hash;+ rows++;+ verifiedUpTo = r.at;}- return true;+ return { ok: true, rows, verifiedUpTo };+}++/** Whether every row still hashes to what the next one remembers: false from the first changed row on. */+export function auditChainIntact(): boolean {+ return verifyAuditChain().ok;}diff --git a/src/server/identity/principal.ts b/src/server/identity/principal.tsindex 2557a5ad..23155b7c 100644--- a/src/server/identity/principal.ts+++ b/src/server/identity/principal.ts@@ -2,6 +2,7 @@ import "server-only";import { hostAllowed } from "../auth";import { db } from "../db";import { installMode, signInOn } from "../mode";+import { LOCAL_OWNER } from "../access/actor";import { ensurePendingPerson, getAuth, sessionCookieName } from "./auth";import { tokenFromHeader } from "./tokens";@@ -15,8 +16,8 @@ import { tokenFromHeader } from "./tokens";* 3. Just me (Personal, sign-in off, a local address) → the owner, via `local`.* 4. Otherwise nobody.*- * The proxy uses it optimistically; route handlers that need a person ask again (acc-2 puts an actor on every- * route).+ * The proxy uses it optimistically; every route handler asks again through handler() (src/server/access/route.ts),+ * which also holds the restricted session kinds' registry and the actor-substitution seam.*/export type ActorVia = "session" | "token" | "local" | "system" | "runner" | "scim";@@ -42,11 +43,8 @@ export interface Principal {needsRefresh?: boolean;}-/**- * Restricted session kinds and the routes each may reach (packages add theirs: two-step enrolment, view-as…). A- * restricted actor outside its routes is treated as signed out.- */-export const RESTRICTED_KINDS = new Map<string, (pathname: string) => boolean>();+/** The header Better Auth and the audit log read the client's address from; only the proxy writes it. */+export const CLIENT_IP_HEADER = "x-fuobe-client-ip";interface PersonRow {id: string;@@ -76,8 +74,6 @@ export function hasSessionCookie(request: Request): boolean {return (request.headers.get("cookie") ?? "").split(";").some((c) => c.trim().startsWith(`${name}=`));}-const LOCAL: Actor = { userId: "u_owner", role: "owner", via: "local", scopes: ["full"] };-async function resolve(request: Request): Promise<Principal> {const local = justMe(request);const bearer = tokenFromHeader(request.headers.get("authorization"));@@ -104,7 +100,7 @@ async function resolve(request: Request): Promise<Principal> {};}}- if (local) return { actor: LOCAL };+ if (local) return { actor: LOCAL_OWNER };return { actor: null };}@@ -119,15 +115,6 @@ export function resolvePrincipal(request: Request): Promise<Principal> {return p;}-/** Act as someone else for this request (view-as, §9.5 E5b). The real actor is kept as the impersonator. */-export function substituteActor(actor: Actor, request: Request): void {- const real = memo.get(request);- memo.set(- request,- (real ?? Promise.resolve({ actor: null } as Principal)).then((r) => ({ actor: { ...actor, impersonatorId: r.actor?.userId ?? actor.impersonatorId } })),- );-}-/*** Refresh a session that is due (once a day), on a POST: Better Auth extends it and sends the cookie again. Returns* the Set-Cookie headers to add to the response (none when nothing was due or it failed).