Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Accounts 2: test harness, route sweep and access tests

Claude47be2516b259
diff --git a/tests/access-roles.test.ts b/tests/access-roles.test.ts
new file mode 100644
index 00000000..a58b4221
--- /dev/null
+++ b/tests/access-roles.test.ts
@@ -0,0 +1,314 @@
+/**
+ * Who may call what (docs/research/accounts-8.md §7.1, §7.3): handler() resolves an actor for every route, the four
+ * install-config routes need install.settings (the Personal owner and Just me on this computer pass, a member is
+ * refused), token scopes narrow what a token may call, typed refusals become 404 / 403 / 401 / 402 / 403 REAUTH,
+ * every 403 is audited, restricted sessions only reach their own routes, the substituteActor seam keeps the real
+ * person, and the role, permission and team-role registries answer as the plan says.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+// Real scrypt hashes (N=2^15) for the password case: slow under a parallel run.
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-access-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES", "FUOBE_SITE_URL"]) delete process.env[k];
+
+const { db } = await import("@/server/db");
+const { bootstrapIdentity } = await import("@/server/identity/bootstrap");
+const { handler, registerActorSubstitute, registerRestrictedKind, restrictedAllows } = await import("@/server/access/route");
+const { currentActor, maybeActor, LOCAL_OWNER, runAs, SYSTEM } = await import("@/server/access/actor");
+const errors = await import("@/server/access/errors");
+const perms = await import("@/server/access/permissions");
+const { gate, gateRefusal, registerGate } = await import("@/server/access/gates");
+const { seedPerson, seedTeam, tokenFor, request, actor, asNobody } = await import("./helpers/actors");
+const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");
+const settingsRoute = await import("@/app/api/settings/route");
+const modelsRoute = await import("@/app/api/settings/models/route");
+const providersTest = await import("@/app/api/providers/test/route");
+const lorasRoute = await import("@/app/api/loras/route");
+const tokensRoute = await import("@/app/api/auth/tokens/route");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+await bootstrapIdentity();
+
+interface AuditRow {
+ seq: number;
+ action: string;
+ actor_id: string | null;
+ actor_via: string | null;
+ meta_json: string;
+}
+const lastAudit = () => db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT 1").get() as AuditRow;
+const auditCount = (action: string) => (db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = ?").get(action) as { n: number }).n;
+
+const member = seedPerson({ role: "member" });
+const admin = seedPerson({ role: "admin" });
+
+/** The four install-config calls, each with a body their handler answers 400 to (nothing changes, nothing is fetched). */
+const CONFIG: [string, (o: { bearer?: string; cookie?: string }) => Promise<Response>][] = [
+ ["PUT /api/settings", (o) => settingsRoute.PUT(request("/api/settings", { method: "PUT", body: { nope: 1 }, ...o }))],
+ ["PUT /api/settings/models", (o) => modelsRoute.PUT(request("/api/settings/models", { method: "PUT", body: {}, ...o }))],
+ ["POST /api/providers/test", (o) => providersTest.POST(request("/api/providers/test", { body: { provider: "nope" }, ...o }))],
+ ["POST /api/loras", (o) => lorasRoute.POST(request("/api/loras", { body: {}, ...o }))],
+];
+
+describe("install-config routes need install.settings", () => {
+ it("lets Just me on this computer through", async () => {
+ for (const [name, call] of CONFIG) expect([200, 400], name).toContain((await call({})).status);
+ });
+
+ it("refuses a member with 403, audited as denied with the route and the reason", async () => {
+ const token = tokenFor(member);
+ for (const [name, call] of CONFIG) {
+ const before = auditCount("denied");
+ const res = await call({ bearer: token });
+ expect(res.status, name).toBe(403);
+ expect(await res.json()).toMatchObject({ code: "FORBIDDEN" });
+ expect(auditCount("denied"), name).toBe(before + 1);
+ const row = lastAudit();
+ expect(row).toMatchObject({ action: "denied", actor_id: member, actor_via: "token" });
+ const [method, p] = name.split(" ");
+ expect(JSON.parse(row.meta_json)).toMatchObject({ method, path: p, reason: "FORBIDDEN" });
+ }
+ });
+
+ it("lets an admin and the owner's Full or Admin tokens through, but not a Generate or Read token", async () => {
+ for (const bearer of [tokenFor(admin), tokenFor("u_owner"), tokenFor("u_owner", ["admin"])]) {
+ for (const [name, call] of CONFIG) expect([200, 400], name).toContain((await call({ bearer })).status);
+ }
+ for (const scopes of [["generate"], ["read"]]) {
+ const res = await settingsRoute.PUT(request("/api/settings", { method: "PUT", body: {}, bearer: tokenFor("u_owner", scopes) }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: "TOKEN_SCOPE" });
+ }
+ });
+
+ it("lets the Personal owner through when signed in, and nobody without a session or token", async () => {
+ await setOwnerPassword("correct horse battery");
+ try {
+ const cookie = await ownerCookie("correct horse battery");
+ for (const [name, call] of CONFIG) expect([200, 400], name).toContain((await call({ cookie })).status);
+ for (const [name, call] of CONFIG) expect((await call({})).status, name).toBe(401);
+ expect((await settingsRoute.PUT(request("/api/settings", { method: "PUT", body: {}, bearer: "fuobe_wrong" }))).status).toBe(401);
+ } finally {
+ await setOwnerPassword(null);
+ }
+ });
+
+ it("keeps reads open to every signed-in person", async () => {
+ expect((await settingsRoute.GET(request("/api/settings", { bearer: tokenFor(member, ["read"]) }))).status).toBe(200);
+ });
+});
+
+describe("token scopes and browser-only routes", () => {
+ it("lets a Read token read but not write", async () => {
+ const read = tokenFor("u_owner", ["read"]);
+ const echo = handler({}, () => Response.json({ ok: true }));
+ expect((await echo(request("/x", { bearer: read }))).status).toBe(200);
+ const res = await echo(request("/x", { method: "POST", body: {}, bearer: read }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: "TOKEN_SCOPE" });
+ });
+
+ it("keeps API tokens out of token management", async () => {
+ const res = await tokensRoute.GET(request("/api/auth/tokens", { bearer: tokenFor("u_owner") }));
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ code: "BROWSER_ONLY" });
+ expect((await tokensRoute.GET(request("/api/auth/tokens"))).status).toBe(200);
+ });
+});
+
+describe("handler()", () => {
+ it("runs the route as the resolved actor, with the address and browser in the scope", async () => {
+ let seen: unknown;
+ const who = handler({}, () => {
+ seen = currentActor();
+ return Response.json({});
+ });
+ await runAs(SYSTEM, () => who(request("/x")));
+ expect(seen).toEqual(LOCAL_OWNER);
+ await who(request("/x", { bearer: tokenFor(member) }));
+ expect(seen).toMatchObject({ userId: member, role: "member", via: "token" });
+ });
+
+ it("answers a public route for nobody, and every other route 401", async () => {
+ await setOwnerPassword("correct horse battery");
+ try {
+ let seen: unknown = "unset";
+ const open = handler({ access: "public" }, () => {
+ seen = maybeActor();
+ return Response.json({});
+ });
+ expect((await open(request("/x"))).status).toBe(200);
+ expect(seen).toBeNull();
+ const closed = handler({}, () => Response.json({}));
+ const res = await closed(request("/x"));
+ expect(res.status).toBe(401);
+ expect(res.headers.get("www-authenticate")).toMatch(/Bearer/);
+ } finally {
+ await setOwnerPassword(null);
+ }
+ });
+
+ it("maps typed refusals to 404, 403, 401, 402 and 403 REAUTH, auditing each 403", async () => {
+ const cases: [Error, number, string | undefined][] = [
+ [new errors.NotFoundError(), 404, undefined],
+ [new errors.ForbiddenError("No.", "NOPE"), 403, "NOPE"],
+ [new errors.UnauthenticatedError(), 401, undefined],
+ [new errors.PaymentRequiredError(), 402, "LIMIT_REACHED"],
+ [new errors.ReauthRequiredError(), 403, "REAUTH"],
+ ];
+ for (const [e, status, code] of cases) {
+ const before = auditCount("denied");
+ const res = await handler({}, () => {
+ throw e;
+ })(request("/refuse", { method: "POST", body: {} }));
+ expect(res.status, e.name).toBe(status);
+ const body = (await res.json()) as { error: string; code?: string };
+ expect(body.error).toBe(e.message);
+ expect(body.code).toBe(code);
+ expect(auditCount("denied"), e.name).toBe(before + (status === 403 ? 1 : 0));
+ if (status === 403) expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ reason: code, path: "/refuse", method: "POST" });
+ }
+ });
+
+ it("audits a 403 the route answers itself, and lets other errors through as before", async () => {
+ const before = auditCount("denied");
+ expect((await handler({}, () => Response.json({ error: "no" }, { status: 403 }))(request("/self"))).status).toBe(403);
+ expect(auditCount("denied")).toBe(before + 1);
+ await expect(
+ handler({}, () => {
+ throw new Error("boom");
+ })(request("/boom")),
+ ).rejects.toThrow("boom");
+ });
+
+ it("audits a hidden record's 404 at most once a minute per person and route", async () => {
+ const hidden = handler({}, () => {
+ throw new errors.NotFoundError("Not found", true);
+ });
+ const before = auditCount("denied.hidden");
+ for (let i = 0; i < 3; i++) expect((await hidden(request("/hidden/1"))).status).toBe(404);
+ expect(auditCount("denied.hidden")).toBe(before + 1);
+ await hidden(request("/hidden/1", { bearer: tokenFor(member) }));
+ expect(auditCount("denied.hidden")).toBe(before + 2);
+ });
+
+ it("refuses an unknown permission when the route is declared", () => {
+ expect(() => handler({ access: "perm:nope.nothing" }, () => new Response())).toThrow(/Unknown permission/);
+ });
+
+ it("treats a restricted session outside its kind's routes as signed out", () => {
+ registerRestrictedKind("accept-terms", (p) => p.startsWith("/api/terms"));
+ expect(restrictedAllows("accept-terms", "/api/terms/accept", "POST")).toBe(true);
+ expect(restrictedAllows("accept-terms", "/api/settings", "PUT")).toBe(false);
+ expect(restrictedAllows("enroll-2fa", "/api/terms/accept", "POST")).toBe(false);
+ });
+
+ it("acts as a substituted person (view-as), keeping the real one and making it read-only", async () => {
+ const viewed = seedPerson({ role: "member" });
+ registerActorSubstitute((a, req) => (req.headers.get("x-test-view-as") === viewed ? { ...a, userId: viewed, role: "member" } : null));
+ let seen: ReturnType<typeof currentActor> | undefined;
+ const who = handler({}, () => {
+ seen = currentActor();
+ return Response.json({});
+ });
+ await who(request("/x", { headers: { "x-test-view-as": viewed } }));
+ expect(seen).toMatchObject({ userId: viewed, impersonatorId: "u_owner" });
+ expect(perms.can(seen, "install.settings")).toBe(false);
+ const res = await settingsRoute.PUT(request("/api/settings", { method: "PUT", body: {}, headers: { "x-test-view-as": viewed } }));
+ expect(res.status).toBe(403);
+ expect(JSON.parse(lastAudit().meta_json)).toMatchObject({ impersonator: "u_owner" });
+ });
+});
+
+describe("roles and permissions", () => {
+ it("gives the owner everything, an admin the day-to-day permissions, a member none", () => {
+ for (const p of perms.permissions()) expect(perms.roleCan("owner", p), p).toBe(true);
+ expect(perms.roleCan("admin", "install.settings")).toBe(true);
+ for (const p of ["install.mode", "people.roles", "support.view_as", "credits.adjust"]) expect(perms.roleCan("admin", p), p).toBe(false);
+ for (const p of perms.permissions()) expect(perms.roleCan("member", p), p).toBe(false);
+ expect(perms.roleCan("nobody", "install.settings")).toBe(false);
+ });
+
+ it("lets packages register roles and permissions (a family grant covers its names), but never replace the owner", () => {
+ perms.registerPermission("billing.refund");
+ perms.registerRole("billing", { label: "Billing", rank: 40, grants: ["billing.*"] });
+ expect(perms.permissionExists("billing.refund")).toBe(true);
+ expect(perms.roleCan("billing", "billing.refund")).toBe(true);
+ expect(perms.roleCan("billing", "install.settings")).toBe(false);
+ expect(perms.roles().map((r) => r.name)).toEqual(["owner", "admin", "billing", "member"]);
+ expect(() => perms.registerRole("owner", { label: "Owner", rank: 1, grants: [] })).toThrow();
+ });
+
+ it("answers can() for the server, tokens and nobody", () => {
+ expect(perms.can(SYSTEM, "install.mode")).toBe(true);
+ expect(perms.can(null, "install.settings")).toBe(false);
+ expect(perms.can(LOCAL_OWNER, "install.settings")).toBe(true);
+ expect(perms.can(actor("u_owner", "owner", { via: "token", scopes: ["generate"] }), "install.settings")).toBe(false);
+ expect(perms.can(actor(admin, "admin", { via: "token", scopes: ["admin"] }), "install.settings")).toBe(true);
+ });
+
+ it("answers team roles through effectiveTeamRole only, with clamps that only lower", () => {
+ const viewer = seedPerson();
+ const team = seedTeam("Studio A", { [admin]: "admin", [member]: "member", [viewer]: "viewer" });
+ const as = (id: string, o = {}) => actor(id, "member", o);
+ expect(perms.effectiveTeamRole(as(admin), team)).toBe("admin");
+ expect(perms.effectiveTeamRole(as(member), team)).toBe("member");
+ expect(perms.effectiveTeamRole(as(viewer), team)).toBe("viewer");
+ expect(perms.effectiveTeamRole(as("u_owner"), team)).toBeNull();
+ expect(perms.effectiveTeamRole(LOCAL_OWNER, "w_owner")).toBe("owner");
+ expect(perms.effectiveTeamRole(SYSTEM, team)).toBe("owner");
+ // View-as is read-only.
+ expect(perms.effectiveTeamRole(as(admin, { impersonatorId: "u_owner" }), team)).toBe("viewer");
+ // A view-only seat is a Viewer; a clamp that tries to raise is ignored.
+ perms.registerTeamRoleClamp((a, _w, role) => (a.userId === member ? "viewer" : role));
+ perms.registerTeamRoleClamp((a, _w, role) => (a.userId === viewer ? "owner" : role));
+ expect(perms.effectiveTeamRole(as(member), team)).toBe("viewer");
+ expect(perms.effectiveTeamRole(as(viewer), team)).toBe("viewer");
+ expect(perms.teamRoleAtLeast("admin", "member")).toBe(true);
+ expect(perms.teamRoleAtLeast("viewer", "member")).toBe(false);
+ expect(perms.TEAM_ROLE_LABEL.member).toBe("Editor");
+ });
+});
+
+describe("gates", () => {
+ it("are open in the core, and refuse with a 403 once a package registers a check", () => {
+ expect(gateRefusal("share.create", LOCAL_OWNER)).toBeNull();
+ expect(() => gate("share.create", LOCAL_OWNER)).not.toThrow();
+ registerGate("share.create", (a) => (a.role === "member" ? { code: "PLAN", message: "Your plan doesn't include share links." } : null));
+ expect(() => gate("share.create", actor(member))).toThrow(errors.ForbiddenError);
+ expect(gateRefusal("share.create", LOCAL_OWNER)).toBeNull();
+ });
+});
+
+describe("the test harness", () => {
+ let inBeforeAll: string | undefined;
+ beforeAll(() => {
+ inBeforeAll = maybeActor()?.userId;
+ });
+
+ it("runs every test as the local owner, from beforeAll on", async () => {
+ expect(inBeforeAll).toBe("u_owner");
+ await new Promise((r) => setTimeout(r, 1));
+ expect(currentActor()).toEqual(LOCAL_OWNER);
+ });
+
+ it("acts as nobody after asNobody(): currentActor() throws", async () => {
+ asNobody();
+ await Promise.resolve();
+ expect(maybeActor()).toBeNull();
+ expect(() => currentActor()).toThrow(/No one is acting/);
+ });
+
+ it("is the local owner again in the next test", () => {
+ expect(currentActor().userId).toBe("u_owner");
+ });
+});
diff --git a/tests/audit-log.test.ts b/tests/audit-log.test.ts
new file mode 100644
index 00000000..a3300d1f
--- /dev/null
+++ b/tests/audit-log.test.ts
@@ -0,0 +1,144 @@
+/**
+ * The audit log (docs/research/accounts-8.md §7.14): audit() takes who acted, from where and with which browser from
+ * the request scope, never records a secret, and appends to a hash-chained table that refuses UPDATE and DELETE.
+ * verifyAuditChain() answers "Records verified up to {time}" or "The record changed after {time}".
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-audit-"));
+process.env.FUOBE_DATA_DIR = dir;
+const { db } = await import("@/server/db");
+const { audit, auditDenied, verifyAuditChain } = await import("@/server/access/audit");
+const { withScope, runAs, asSystem, LOCAL_OWNER } = await import("@/server/access/actor");
+const { appendAudit } = await import("@/server/identity/audit-log");
+const { actor, asNobody } = await import("./helpers/actors");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+interface Row {
+ seq: number;
+ at: number;
+ actor_id: string | null;
+ actor_via: string | null;
+ action: string;
+ target_kind: string | null;
+ target_id: string | null;
+ meta_json: string;
+ ip: string | null;
+ user_agent: string | null;
+}
+const last = () => db().prepare("SELECT * FROM audit_log ORDER BY seq DESC LIMIT 1").get() as Row;
+
+describe("audit()", () => {
+ it("records the acting person, their address and browser from the request scope", () => {
+ const person = actor("u_alex", "member", { via: "token", tokenId: "t1" });
+ withScope({ actor: person, ip: "203.0.113.7", userAgent: "curl/8", method: "PUT", path: "/api/settings" }, () =>
+ audit("install.setting_changed", { kind: "setting", id: "engine.mode" }, { from: "both", to: "open" }),
+ );
+ const row = last();
+ expect(row).toMatchObject({ action: "install.setting_changed", actor_id: "u_alex", actor_via: "token", target_kind: "setting", target_id: "engine.mode", ip: "203.0.113.7", user_agent: "curl/8" });
+ expect(JSON.parse(row.meta_json)).toEqual({ tokenId: "t1", from: "both", to: "open" });
+ });
+
+ it("names the runner's row owner, the server, and the real person behind a view-as", () => {
+ runAs({ ...LOCAL_OWNER, via: "runner" }, () => audit("generation.settled"));
+ expect(last()).toMatchObject({ actor_id: "u_owner", actor_via: "runner", ip: null });
+ asSystem(() => audit("housekeeping.swept"));
+ expect(last()).toMatchObject({ actor_id: "system", actor_via: "system" });
+ runAs(actor("u_alex", "member", { impersonatorId: "u_owner" }), () => audit("content.viewed"));
+ expect(JSON.parse(last().meta_json)).toEqual({ impersonator: "u_owner" });
+ });
+
+ it("records nobody when no one is acting (a public route answered for nobody)", () => {
+ asNobody();
+ audit("auth.sign_in_failed", null, { reason: "wrong password" });
+ expect(last()).toMatchObject({ actor_id: null, actor_via: null });
+ });
+
+ it("never writes a secret, whatever the caller passed", () => {
+ audit("keys.changed", null, {
+ setting: "fal.key",
+ apiKey: "sk-live-123",
+ password: "hunter2",
+ nested: { client_secret: "abc", authorization: "Bearer x", tokenPrefix: "fuobe_abcd" },
+ tokenId: "keep-me",
+ prefix: "sk-li…",
+ });
+ const meta = JSON.parse(last().meta_json);
+ expect(meta).toEqual({
+ setting: "fal.key",
+ apiKey: "[redacted]",
+ password: "[redacted]",
+ nested: { client_secret: "[redacted]", authorization: "[redacted]", tokenPrefix: "fuobe_abcd" },
+ tokenId: "keep-me",
+ prefix: "sk-li…",
+ });
+ expect(last().meta_json).not.toMatch(/sk-live|hunter2|Bearer x/);
+ });
+
+ it("records a denial with the route and the reason", () => {
+ withScope({ actor: actor("u_alex"), method: "POST", path: "/api/loras" }, () => auditDenied("FORBIDDEN"));
+ expect(last().action).toBe("denied");
+ expect(JSON.parse(last().meta_json)).toEqual({ method: "POST", path: "/api/loras", reason: "FORBIDDEN" });
+ });
+});
+
+describe("the append-only, hash-chained table", () => {
+ it("refuses UPDATE and DELETE", () => {
+ const { seq } = last();
+ expect(() => db().prepare("UPDATE audit_log SET action = 'x' WHERE seq = ?").run(seq)).toThrow(/append-only/);
+ expect(() => db().prepare("DELETE FROM audit_log WHERE seq = ?").run(seq)).toThrow(/append-only/);
+ expect(() => db().exec("DELETE FROM audit_log")).toThrow(/append-only/);
+ expect(last().seq).toBe(seq);
+ });
+
+ it("verifies up to the last row", () => {
+ for (let i = 0; i < 5; i++) audit("test.entry", { kind: "n", id: String(i) });
+ const check = verifyAuditChain();
+ const rows = (db().prepare("SELECT COUNT(*) AS n FROM audit_log").get() as { n: number }).n;
+ expect(check).toEqual({ ok: true, rows, verifiedUpTo: last().at });
+ });
+
+ it("chains each row to the one before it (prev_hash is the previous row's hash)", () => {
+ const rows = db().prepare("SELECT prev_hash, hash FROM audit_log ORDER BY seq").all() as { prev_hash: string; hash: string }[];
+ expect(rows[0].prev_hash).toBe("");
+ for (let i = 1; i < rows.length; i++) expect(rows[i].prev_hash).toBe(rows[i - 1].hash);
+ });
+
+ it("keeps the bare writer and audit() on one chain", () => {
+ appendAudit({ action: "auth.sign_in", actorId: "u_owner", via: "session" });
+ audit("token.created", { kind: "token", id: "t2" });
+ const [a, b] = (db().prepare("SELECT prev_hash, hash FROM audit_log ORDER BY seq DESC LIMIT 2").all() as { prev_hash: string; hash: string }[]).reverse();
+ expect(b.prev_hash).toBe(a.hash);
+ expect(verifyAuditChain().ok).toBe(true);
+ });
+
+ // Someone with the database file can lift a trigger; the chain still tells.
+ const behindTheTriggers = (trigger: "audit_log_append_only" | "audit_log_no_delete", sql: string, seq: number) => {
+ const create = (db().prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?").get(trigger) as { sql: string }).sql;
+ db().exec(`DROP TRIGGER ${trigger}`);
+ try {
+ db().prepare(sql).run(seq);
+ } finally {
+ db().exec(create);
+ }
+ };
+
+ it("finds a row changed behind the triggers' back, and says from when", () => {
+ const rows = db().prepare("SELECT seq, at FROM audit_log ORDER BY seq").all() as { seq: number; at: number }[];
+ behindTheTriggers("audit_log_append_only", `UPDATE audit_log SET meta_json = '{"to":"edited"}' WHERE seq = ?`, rows[3].seq);
+ const check = verifyAuditChain();
+ expect(check).toEqual({ ok: false, rows: 3, verifiedUpTo: rows[2].at, brokenAt: { seq: rows[3].seq, at: rows[3].at } });
+ });
+
+ it("finds a row removed from the middle (earlier than the change, so that is where it breaks now)", () => {
+ const rows = db().prepare("SELECT seq, at FROM audit_log ORDER BY seq").all() as { seq: number; at: number }[];
+ behindTheTriggers("audit_log_no_delete", "DELETE FROM audit_log WHERE seq = ?", rows[1].seq);
+ const check = verifyAuditChain();
+ expect(check).toEqual({ ok: false, rows: 1, verifiedUpTo: rows[0].at, brokenAt: { seq: rows[2].seq, at: rows[2].at } });
+ // The triggers are back.
+ expect(() => db().prepare("DELETE FROM audit_log WHERE seq = ?").run(rows[0].seq)).toThrow(/append-only/);
+ });
+});
diff --git a/tests/helpers/actors.ts b/tests/helpers/actors.ts
new file mode 100644
index 00000000..47af6bf7
--- /dev/null
+++ b/tests/helpers/actors.ts
@@ -0,0 +1,100 @@
+/**
+ * People, teams and requests for tests (docs/research/accounts-8.md §13). Every test acts as the local owner, "Just me
+ * on this computer" (tests/setup/actor.ts); these helpers seed other people, roles and teams, act as nobody or as
+ * someone else, and build the requests a browser or a CLI would send: from this computer, with a bearer token, or
+ * with a session cookie (tests/helpers/identity.ts signs the owner in). Each test file sets FUOBE_DATA_DIR before
+ * importing Fuobe.
+ */
+import crypto from "node:crypto";
+import { enterAs, LOCAL_OWNER, maybeActor, runAs, SYSTEM, type Actor } from "@/server/access/actor";
+import type { TeamRole } from "@/server/access/permissions";
+import { db } from "@/server/db";
+import { createToken } from "@/server/identity/tokens";
+
+export { LOCAL_OWNER, maybeActor, runAs, SYSTEM };
+
+/** The rest of this test runs as nobody: server code that asks who is acting throws. */
+export function asNobody(): void {
+ enterAs(null);
+}
+
+/** The rest of this test runs as `actor` (the local owner by default). */
+export function actAs(actor: Actor = LOCAL_OWNER): void {
+ enterAs(actor);
+}
+
+/** An actor as handler() would resolve it (a session by default). */
+export function actor(userId: string, role = "member", o: Partial<Actor> = {}): Actor {
+ return { userId, role, via: "session", scopes: ["full"], ...o };
+}
+
+export interface SeedPerson {
+ id?: string;
+ role?: string;
+ status?: "active" | "pending" | "disabled" | "deleted";
+ dormant?: boolean;
+}
+
+/** A person (a `users` row) with a personal workspace they own. Returns their id. */
+export function seedPerson(p: SeedPerson = {}): string {
+ const id = p.id ?? `u_${crypto.randomBytes(6).toString("hex")}`;
+ const ws = `w_${id.slice(2)}`;
+ const now = Date.now();
+ db()
+ .prepare(
+ `INSERT INTO users (id, role, status, dormant, personal_workspace_id, source, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, 'admin', ?, ?)`,
+ )
+ .run(id, p.role ?? "member", p.status ?? "active", p.dormant ? 1 : 0, ws, now, now);
+ db().prepare("INSERT INTO workspaces (id, kind, name, slug, created_by, created_at, updated_at) VALUES (?, 'personal', 'Personal', ?, ?, ?, ?)").run(ws, ws, id, now, now);
+ db().prepare("INSERT INTO workspace_members (workspace_id, user_id, role, source, created_at) VALUES (?, ?, 'owner', 'manual', ?)").run(ws, id, now);
+ return id;
+}
+
+/** Change a seeded person (turn them off, make them dormant, change their role). */
+export function updatePerson(id: string, p: Omit<SeedPerson, "id">): void {
+ if (p.role) db().prepare("UPDATE users SET role = ? WHERE id = ?").run(p.role, id);
+ if (p.status) db().prepare("UPDATE users SET status = ? WHERE id = ?").run(p.status, id);
+ if (p.dormant !== undefined) db().prepare("UPDATE users SET dormant = ? WHERE id = ?").run(p.dormant ? 1 : 0, id);
+}
+
+/** A team workspace with these members and roles. Returns its id. */
+export function seedTeam(name: string, members: Record<string, TeamRole>): string {
+ const id = `w_${crypto.randomBytes(6).toString("hex")}`;
+ const now = Date.now();
+ db().prepare("INSERT INTO workspaces (id, kind, name, slug, created_at, updated_at) VALUES (?, 'team', ?, ?, ?, ?)").run(id, name, id, now, now);
+ for (const [userId, role] of Object.entries(members)) {
+ db().prepare("INSERT INTO workspace_members (workspace_id, user_id, role, source, created_at) VALUES (?, ?, ?, 'manual', ?)").run(id, userId, role, now);
+ }
+ return id;
+}
+
+/** A live API token for a person, with these scopes (Full by default). Returns the token itself. */
+export function tokenFor(userId: string, scopes: string[] = ["full"]): string {
+ const { token, info } = createToken(userId, "Test");
+ db().prepare("UPDATE api_tokens SET scopes = ? WHERE id = ?").run(scopes.join(","), info.id);
+ return token;
+}
+
+export interface RequestOptions {
+ method?: string;
+ body?: unknown;
+ headers?: Record<string, string>;
+ /** Sent as Authorization: Bearer … */
+ bearer?: string;
+ /** Sent as the Cookie header (tests/helpers/identity.ts ownerCookie). */
+ cookie?: string;
+ /** The address the request arrives at (localhost: Just me on this computer when sign-in is off). */
+ origin?: string;
+}
+
+/** A request the way a browser or the CLI sends it to `path`. */
+export function request(path: string, o: RequestOptions = {}): Request {
+ const origin = o.origin ?? "http://localhost:3000";
+ const headers: Record<string, string> = { host: new URL(origin).host, ...o.headers };
+ if (o.bearer) headers.authorization = `Bearer ${o.bearer}`;
+ if (o.cookie) headers.cookie = o.cookie;
+ const method = o.method ?? (o.body === undefined ? "GET" : "POST");
+ if (o.body !== undefined) headers["content-type"] ??= "application/json";
+ return new Request(new URL(path, origin), { method, headers, ...(o.body !== undefined && { body: typeof o.body === "string" ? o.body : JSON.stringify(o.body) }) });
+}
diff --git a/tests/mcp-actor.test.ts b/tests/mcp-actor.test.ts
new file mode 100644
index 00000000..7baa792d
--- /dev/null
+++ b/tests/mcp-actor.test.ts
@@ -0,0 +1,88 @@
+/**
+ * MCP receives the actor (docs/research/accounts-8.md §7.10, acc-2): /api/mcp resolves the token's (or session's)
+ * person through handler() and hands it to handleMcp(body, actor), and every tool the message runs acts for that
+ * person — in its ToolContext and as the scope's actor. The route's Origin check still refuses other sites (and the
+ * refusal is audited).
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+import type { ToolContext } from "@/server/assist/define";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-mcp-actor-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+/** What each tool call saw: the context's actor and the scope's. */
+const calls: { name: string; ctxActor: unknown; scopeActor: unknown }[] = [];
+vi.mock("@/server/assist/tools", async (importOriginal) => {
+ const real = await importOriginal<typeof import("@/server/assist/tools")>();
+ const { maybeActor } = await import("@/server/access/actor");
+ return {
+ ...real,
+ executeTool: async (name: string, input: unknown, ctx: ToolContext) => {
+ calls.push({ name, ctxActor: ctx.actor, scopeActor: maybeActor() });
+ return real.executeTool(name, input, ctx);
+ },
+ };
+});
+
+const { handleMcp } = await import("@/server/mcp");
+const route = await import("@/app/api/mcp/route");
+const { db } = await import("@/server/db");
+const { runAs, SYSTEM, LOCAL_OWNER } = await import("@/server/access/actor");
+const { seedPerson, tokenFor, request, actor, asNobody } = await import("./helpers/actors");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const call = (name: string, args: unknown = {}) => ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
+
+describe("handleMcp(body, actor)", () => {
+ it("runs each tool for the actor it is given, whoever is acting around it", async () => {
+ const alex = actor(seedPerson(), "member", { via: "token", tokenId: "t1" });
+ calls.length = 0;
+ const res = await runAs(SYSTEM, () => handleMcp(call("search_models", { query: "video" }), alex));
+ expect(res).toMatchObject({ result: {} });
+ expect(calls).toEqual([{ name: "search_models", ctxActor: alex, scopeActor: alex }]);
+ });
+
+ it("acts for whoever the scope says when no actor is passed, and refuses to act for nobody", async () => {
+ calls.length = 0;
+ await handleMcp(call("list_elements"));
+ expect(calls[0]).toMatchObject({ ctxActor: LOCAL_OWNER, scopeActor: LOCAL_OWNER });
+ asNobody();
+ await expect(handleMcp(call("list_elements"))).rejects.toThrow(/No one is acting/);
+ });
+});
+
+describe("POST /api/mcp", () => {
+ const post = (body: unknown, o: { bearer?: string; headers?: Record<string, string> } = {}) => route.POST(request("/api/mcp", { body, ...o }));
+
+ it("hands the bearer token's person to the tools", async () => {
+ const member = seedPerson();
+ calls.length = 0;
+ const res = await post(call("search_models", { query: "image" }), { bearer: tokenFor(member) });
+ expect(res.status).toBe(200);
+ expect(calls[0].ctxActor).toMatchObject({ userId: member, role: "member", via: "token" });
+ expect(calls[0].scopeActor).toEqual(calls[0].ctxActor);
+ });
+
+ it("hands Just me on this computer the local owner", async () => {
+ calls.length = 0;
+ expect((await post(call("list_elements"))).status).toBe(200);
+ expect(calls[0].ctxActor).toEqual(LOCAL_OWNER);
+ });
+
+ it("keeps the Origin check, and audits the refusal", async () => {
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n;
+ const res = await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { headers: { origin: "https://evil.example" } });
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ error: { code: -32000, message: "Origin not allowed" } });
+ expect((db().prepare("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'denied'").get() as { n: number }).n).toBe(before + 1);
+ expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { headers: { origin: "http://localhost:3000" } })).status).toBe(200);
+ });
+
+ it("ignores an invalid token in Just me on this computer, as the proxy does", async () => {
+ expect((await post({ jsonrpc: "2.0", id: 1, method: "ping" }, { bearer: "fuobe_wrong" })).status).toBe(200);
+ });
+});
diff --git a/tests/route-sweep.test.ts b/tests/route-sweep.test.ts
new file mode 100644
index 00000000..e68eed6f
--- /dev/null
+++ b/tests/route-sweep.test.ts
@@ -0,0 +1,92 @@
+/**
+ * The route sweep (docs/research/accounts-8.md §13): every route handler under src/app goes through handler()
+ * (src/server/access/route.ts), so each request resolves who is asking and checks what the route declares. A new
+ * route.ts that exports a bare function fails here, by file and method.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+// Importing every route module once is slow under a parallel run.
+vi.setConfig({ testTimeout: 180_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-route-sweep-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const { isWrapped } = await import("@/server/access/route");
+
+const ROOT = path.resolve(__dirname, "..");
+const METHODS = ["GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"];
+
+function routeFiles(d = path.join(ROOT, "src/app")): string[] {
+ return fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) return routeFiles(p);
+ return /^route\.(ts|tsx|js|mjs)$/.test(e.name) ? [p] : [];
+ });
+}
+
+const FILES = routeFiles();
+const rel = (f: string) => path.relative(ROOT, f);
+
+describe("every route goes through handler()", () => {
+ it("finds the routes (192 at 545ebb5; more since)", () => {
+ expect(FILES.length).toBeGreaterThanOrEqual(192);
+ });
+
+ it("exports no bare handler: each method is `export const X = handler(…)` or a const made by handler()", () => {
+ const bad: string[] = [];
+ for (const f of FILES) {
+ const src = fs.readFileSync(f, "utf8");
+ const name = rel(f);
+ for (const m of src.matchAll(/export\s+(?:async\s+)?function\s+(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\b/g)) bad.push(`${name}: function ${m[1]}`);
+ for (const m of src.matchAll(/export\s*\{([^}]*)\}/g)) {
+ for (const part of m[1].split(",")) {
+ const exported = part.trim().split(/\s+as\s+/).pop()?.trim();
+ if (exported && METHODS.includes(exported)) bad.push(`${name}: export { … as ${exported} }`);
+ }
+ }
+ for (const m of src.matchAll(/export\s+const\s+(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\s*=\s*([^;\n]*)/g)) {
+ const rhs = m[2].trim();
+ if (rhs.startsWith("handler(")) continue;
+ const alias = /^([A-Za-z_$][\w$]*)\s*;?$/.exec(rhs)?.[1];
+ if (alias && new RegExp(`const\\s+${alias}\\s*=\\s*handler\\(`).test(src)) continue;
+ bad.push(`${name}: ${m[1]} = ${rhs.slice(0, 40)}`);
+ }
+ }
+ expect(bad).toEqual([]);
+ });
+
+ it("every exported method of every route module is a handler() wrapper", async () => {
+ const bad: string[] = [];
+ for (const f of FILES) {
+ const mod = (await import(f)) as Record<string, unknown>;
+ const methods = METHODS.filter((m) => m in mod);
+ if (!methods.length) bad.push(`${rel(f)}: exports no method`);
+ for (const m of methods) if (!isWrapped(mod[m])) bad.push(`${rel(f)}: ${m}`);
+ }
+ expect(bad).toEqual([]);
+ });
+
+ it("names the four install-config routes as needing install.settings", () => {
+ const needs = (file: string, method: string) =>
+ new RegExp(`export\\s+const\\s+${method}\\s*=\\s*handler\\(\\{\\s*access:\\s*"perm:install\\.settings"`).test(fs.readFileSync(path.join(ROOT, file), "utf8"));
+ expect(needs("src/app/api/settings/route.ts", "PUT")).toBe(true);
+ expect(needs("src/app/api/settings/models/route.ts", "PUT")).toBe(true);
+ expect(needs("src/app/api/providers/test/route.ts", "POST")).toBe(true);
+ expect(needs("src/app/api/loras/route.ts", "POST")).toBe(true);
+ });
+
+ it("keeps the public routes few: sign-in, sign-out, Better Auth's router and share files", () => {
+ const open = FILES.filter((f) => /access:\s*"public"/.test(fs.readFileSync(f, "utf8"))).map(rel).sort();
+ expect(open).toEqual([
+ "src/app/api/auth/login/route.ts",
+ "src/app/api/auth/logout/route.ts",
+ "src/app/api/identity/[...all]/route.ts",
+ "src/app/s/[token]/f/[...path]/route.ts",
+ ]);
+ });
+});
diff --git a/tests/runners-actor.test.ts b/tests/runners-actor.test.ts
new file mode 100644
index 00000000..fd29edcd
--- /dev/null
+++ b/tests/runners-actor.test.ts
@@ -0,0 +1,163 @@
+/**
+ * Runners carry an actor (docs/research/accounts-8.md §7.11): background work runs as the person who started the
+ * row (runAs(row owner), via "runner"), never as whoever's request happened to start a timer, and a row whose owner
+ * was turned off fails with "Paused: the account that started this is off." Timers themselves belong to the server
+ * (asSystem).
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type Anthropic from "@anthropic-ai/sdk";
+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-runners-actor-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+// No real sweeps in this process: each test drives the runner's ticks itself.
+const stubTimer = setInterval(() => {}, 60_000);
+clearInterval(stubTimer);
+globalThis.__fuobeScheduleRunner = { tick: () => {}, timer: stubTimer };
+
+const { db } = await import("@/server/db");
+const gens = await import("@/server/generations");
+const { PROVIDERS } = await import("@/server/providers");
+const perms = await import("@/server/access/permissions");
+const { maybeActor, currentActor, runAs, asSystem, SYSTEM } = await import("@/server/access/actor");
+const sched = await import("@/server/assist/schedules");
+const agent = await import("@/server/assist/agent");
+const { setSetting } = await import("@/server/settings");
+const { seedPerson, updatePerson, actor } = await import("./helpers/actors");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+afterEach(() => {
+ updatePerson("u_owner", { status: "active", dormant: false });
+ vi.restoreAllMocks();
+});
+
+const who = () => {
+ const a = maybeActor();
+ return a && { userId: a.userId, via: a.via };
+};
+
+let rows = 0;
+function storedRow(r: { status: string; externalId?: string; dependsOn?: string; outputs?: object[] }): string {
+ const id = `row-${++rows}`;
+ const now = Date.now();
+ db()
+ .prepare(
+ `INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, external_id, depends_on, created_at, updated_at)
+ VALUES (?, 'image', 'nano-banana-pro', 'cloud', 'mock', 'generate', 'image', ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(id, r.status, JSON.stringify({ modelId: "nano-banana-pro", prompt: "a lighthouse" }), JSON.stringify(r.outputs ?? []), r.externalId ?? null, r.dependsOn ?? null, now, now);
+ return id;
+}
+
+describe("acting for a row's owner", () => {
+ it("reads the owner from created_by once rows have it, else the install owner", () => {
+ expect(perms.rowOwner({})).toBe("u_owner");
+ expect(perms.rowOwner({ created_by: null })).toBe("u_owner");
+ expect(perms.rowOwner({ created_by: "u_alex" })).toBe("u_alex");
+ });
+
+ it("acts as that person, via the runner", () => {
+ const alex = seedPerson({ role: "admin" });
+ expect(perms.ownerActor(alex)).toEqual({ userId: alex, role: "admin", via: "runner", scopes: ["full"] });
+ expect(perms.runAsOwner(alex, () => currentActor().userId)).toBe(alex);
+ expect(perms.runAsOwner(null, () => who())).toEqual({ userId: "u_owner", via: "runner" });
+ });
+
+ it("refuses for a person who is pending, off, deleted, dormant or unknown", () => {
+ for (const p of [{ status: "pending" as const }, { status: "disabled" as const }, { status: "deleted" as const }, { dormant: true }]) {
+ const id = seedPerson(p);
+ expect(() => perms.ownerActor(id)).toThrow(perms.AccountOffError);
+ }
+ expect(() => perms.ownerActor("u_nobody")).toThrow("Paused: the account that started this is off.");
+ });
+});
+
+describe("the generations runner", () => {
+ async function tickUntil(done: () => boolean) {
+ gens.ensureRunner();
+ for (let i = 0; i < 50 && !done(); i++) {
+ await globalThis.__fuobeRunner!.tick();
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ }
+
+ it("polls a running job as the person who started it, whoever's request started the runner", async () => {
+ const seen: unknown[] = [];
+ vi.spyOn(PROVIDERS.mock, "poll").mockImplementation(async () => {
+ seen.push(who());
+ return { state: "running", progress: 0.5 };
+ });
+ const id = storedRow({ status: "running", externalId: "mock-1" });
+ // A member's request is what first starts the runner; the timers it sets up still belong to the server.
+ runAs(actor(seedPerson(), "member"), () => gens.ensureRunner());
+ await asSystem(() => tickUntil(() => seen.length > 0));
+ expect(seen[0]).toEqual({ userId: "u_owner", via: "runner" });
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(id);
+ });
+
+ it("fails a running job whose owner was turned off, with the words the plan gives", async () => {
+ vi.spyOn(PROVIDERS.mock, "poll").mockResolvedValue({ state: "running" });
+ const id = storedRow({ status: "running", externalId: "mock-2" });
+ updatePerson("u_owner", { status: "disabled" });
+ await tickUntil(() => gens.getGeneration(id)?.status === "failed");
+ expect(gens.getGeneration(id)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });
+ });
+
+ it("fails a waiting step of a chain whose owner went dormant, and plans the next one as the owner", async () => {
+ const parent = storedRow({ status: "succeeded", outputs: [{ url: "/api/files/x.png", kind: "image" }] });
+ const child = storedRow({ status: "queued", dependsOn: parent });
+ updatePerson("u_owner", { dormant: true });
+ await tickUntil(() => gens.getGeneration(child)?.status === "failed");
+ expect(gens.getGeneration(child)).toMatchObject({ status: "failed", error: "Paused: the account that started this is off." });
+ });
+});
+
+describe("Assist", () => {
+ type Block = Anthropic.Beta.BetaContentBlock;
+ const done = (seen: unknown[]): import("@/server/assist/agent").ModelCall =>
+ async () => {
+ seen.push(who());
+ return { content: [{ type: "text", text: "Done.", citations: null } as Block], stop_reason: "end_turn", stop_details: null } as unknown as Anthropic.Beta.BetaMessage;
+ };
+
+ it("carries a chat on as its author, whoever's request or schedule carried it", async () => {
+ setSetting("anthropicKey", "sk-ant-test");
+ const t = agent.createThread({ engine: "cloud", agent: "claude", title: "Ad" });
+ agent.addMessage(t.id, "Make an ad");
+ const seen: unknown[] = [];
+ await runAs(SYSTEM, () => agent.run(t.id, done(seen)));
+ expect(seen[0]).toEqual({ userId: "u_owner", via: "runner" });
+ });
+
+ it("runs a scheduled task as the person who owns it, from the server's sweep", async () => {
+ const T = (s: string) => Date.parse(s);
+ const s = sched.createSchedule(
+ { title: "Daily ad", prompt: "Make today's ad", tz: "UTC", engine: "cloud", approval: "ask", rule: { kind: "daily", time: "09:00" } },
+ T("2026-10-27T08:00:00Z"),
+ );
+ const seen: unknown[] = [];
+ const started = await asSystem(() => sched.sweepSchedules(T("2026-10-27T09:00:30Z"), { model: done(seen) }));
+ expect(started).toHaveLength(1);
+ await vi.waitFor(() => expect(seen.length).toBeGreaterThan(0));
+ expect(seen[0]).toEqual({ userId: "u_owner", via: "runner" });
+ sched.deleteSchedule(s.id);
+ });
+
+ it("records a failed run when the task's owner is off, and starts no chat", async () => {
+ const T = (s: string) => Date.parse(s);
+ const s = sched.createSchedule(
+ { title: "Weekly", prompt: "Make the weekly ad", tz: "UTC", engine: "cloud", approval: "ask", rule: { kind: "daily", time: "10:00" } },
+ T("2026-10-28T08:00:00Z"),
+ );
+ updatePerson("u_owner", { status: "disabled" });
+ const seen: unknown[] = [];
+ expect(await asSystem(() => sched.sweepSchedules(T("2026-10-28T10:00:30Z"), { model: done(seen) }))).toEqual([]);
+ expect(seen).toEqual([]);
+ expect(sched.getSchedule(s.id)?.last).toMatchObject({ status: "failed", text: "Paused: the account that started this is off." });
+ });
+});
diff --git a/tests/setup/actor.ts b/tests/setup/actor.ts
new file mode 100644
index 00000000..5eae0776
--- /dev/null
+++ b/tests/setup/actor.ts
@@ -0,0 +1,11 @@
+import { beforeAll, beforeEach } from "vitest";
+import { enterAs, LOCAL_OWNER } from "@/server/access/actor";
+
+/**
+ * Every test acts as the local owner ("Just me on this computer"), so suites that call server modules directly keep
+ * working now that server code asks who is acting (docs/research/accounts-8.md §13). A test that needs nobody calls
+ * asNobody() (tests/helpers/actors.ts); one that needs someone else wraps its work in runAs().
+ */
+enterAs(LOCAL_OWNER);
+beforeAll(() => enterAs(LOCAL_OWNER));
+beforeEach(() => enterAs(LOCAL_OWNER));
diff --git a/vitest.config.ts b/vitest.config.ts
index cc92f57f..09f56d83 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({
"server-only": path.resolve(__dirname, "tests/stubs/server-only.ts"),
},
},
- test: { include: ["tests/**/*.test.ts"], environment: "node" },
+ test: { include: ["tests/**/*.test.ts"], environment: "node", setupFiles: ["tests/setup/actor.ts"] },
});