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 1: tests for the bootstrap, proxy, snapshots, headers and load
Claude072dfb34c41f
diff --git a/tests/identity-bootstrap.test.ts b/tests/identity-bootstrap.test.tsnew file mode 100644index 00000000..3f4c1e86--- /dev/null+++ b/tests/identity-bootstrap.test.ts@@ -0,0 +1,267 @@+/**+ * The identity bootstrap (docs/research/accounts-8.md §7.9, §7.15, §7.16), as a matrix of data folders: fresh, an+ * install from before accounts with and without a password and API tokens, FUOBE_PASSWORD, a second start, a+ * changed secret key and FUOBE_MODE. Each case boots fresh modules on its own folder, as a server start would.+ */+import crypto from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import Database from "better-sqlite3";+import { NextRequest } from "next/server";+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";++const ENV = ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET", "FUOBE_ACCEPT_NEW_SECRET", "FUOBE_DEV_PLATFORM", "FUOBE_SITE_URL", "FUOBE_TRUST_PROXY", "FUOBE_TRUSTED_PROXIES"];+for (const k of ENV) delete process.env[k];+const dirs: string[] = [];+afterAll(() => {+ closeDbs();+ for (const d of dirs) fs.rmSync(d, { recursive: true, force: true });+});+afterEach(() => {+ for (const k of ENV) delete process.env[k];+});++function closeDbs() {+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+ globalThis.__fuobeAuthDb?.db.close();+ globalThis.__fuobeAuthDb = undefined;+}++const newDir = () => {+ const d = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-boot-"));+ dirs.push(d);+ return d;+};++/** Fresh modules on `dir`, as a new server process would load them. */+async function load(dir: string) {+ closeDbs();+ vi.resetModules();+ process.env.FUOBE_DATA_DIR = dir;+ return {+ bootstrap: await import("@/server/identity/bootstrap"),+ mode: await import("@/server/mode"),+ dbm: await import("@/server/db"),+ owner: await import("@/server/identity/owner"),+ ops: await import("@/server/identity/admin-ops"),+ tokens: await import("@/server/identity/tokens"),+ principal: await import("@/server/identity/principal"),+ proxy: (await import("@/proxy")).proxy,+ login: await import("@/app/api/auth/login/route"),+ };+}++async function boot(dir: string) {+ const m = await load(dir);+ const report = await m.bootstrap.bootstrapIdentity();+ return { ...m, report };+}++/** A database as a build from before accounts left it: every migration but the identity one. */+async function preAccountsDb(dir: string) {+ const { dbm } = await load(dir);+ const d = dbm.db();+ for (const t of ["users", "workspaces", "workspace_members", "invites", "grants", "item_marks", "api_tokens", "audit_log", "user_settings", "workspace_settings", "session_step_up", "auth_user", "auth_session", "auth_account", "auth_verification", "auth_rate_limit"]) d.exec(`DROP TABLE IF EXISTS "${t}"`);+ d.prepare("DELETE FROM _migrations WHERE id = ?").run(dbm.IDENTITY_MIGRATION);+ d.prepare("INSERT INTO settings (key, value) VALUES ('engine.mode', 'open')").run();+ closeDbs();+}++const legacyHash = (password: string) => {+ const salt = crypto.randomBytes(16);+ return `${salt.toString("hex")}:${crypto.scryptSync(password, salt, 32).toString("hex")}`;+};+const sha = (t: string) => crypto.createHash("sha256").update(t).digest("hex");+const TOKEN_A = `fuobe_${"a".repeat(32)}`;+const TOKEN_B = `fuobe_${"b".repeat(32)}`;++function writeAuthJson(dir: string, opts: { password?: string; tokens?: boolean }) {+ const data = {+ ...(opts.password && { password: legacyHash(opts.password) }),+ secret: crypto.randomBytes(32).toString("hex"),+ tokens: opts.tokens+ ? [+ { id: "aaaaaaaaaaaa", name: "CLI", hash: sha(TOKEN_A), prefix: TOKEN_A.slice(0, 12), createdAt: 1_700_000_000_000, lastUsedAt: 1_700_000_100_000 },+ { id: "bbbbbbbbbbbb", name: "MCP", hash: sha(TOKEN_B), prefix: TOKEN_B.slice(0, 12), createdAt: 1_700_000_200_000 },+ ]+ : [],+ };+ fs.writeFileSync(path.join(dir, "auth.json"), JSON.stringify(data), { mode: 0o600 });+ return data;+}++const req = (url: string, headers: Record<string, string> = {}) => new NextRequest(url, { headers: { host: new URL(url).host, ...headers } });+const loginPost = (password: string) =>+ new Request("http://localhost:3000/api/auth/login", { method: "POST", headers: { "content-type": "application/json", host: "localhost:3000", origin: "http://localhost:3000" }, body: JSON.stringify({ password }) });++describe("a fresh data folder", () => {+ it("boots as Personal, sign-in off, setup done: Just me on this computer, as before accounts", async () => {+ const dir = newDir();+ const m = await boot(dir);+ expect(m.report).toMatchObject({ snapshot: null, importedPassword: false, importedTokens: 0, signin: "off" });+ expect(m.mode.installMode()).toBe("personal");+ expect(m.mode.setupState()).toBe("done");+ expect(m.mode.signInRequired()).toBe(false);+ expect(m.principal.justMe(req("http://localhost:3000/"))).toBe(true);+ expect((await m.principal.resolvePrincipal(req("http://localhost:3000/library"))).actor).toMatchObject({ userId: "u_owner", via: "local", role: "owner" });+ // The owner exists, unclaimed, with a personal workspace; the install catalog too.+ const d = m.dbm.db();+ expect(d.prepare("SELECT id, role, status, auth_user_id, personal_workspace_id FROM users").all()).toEqual([+ { id: "u_owner", role: "owner", status: "active", auth_user_id: null, personal_workspace_id: "w_owner" },+ ]);+ expect(d.prepare("SELECT id, kind FROM workspaces ORDER BY id").all()).toEqual([+ { id: "w_install", kind: "install" },+ { id: "w_owner", kind: "personal" },+ ]);+ // The root secret, private, and its fingerprint (never the secret) in the database.+ const key = path.join(dir, "secret.key");+ expect(fs.statSync(key).size).toBe(32);+ expect(fs.statSync(key).mode & 0o777).toBe(0o600);+ expect(m.mode.installValue("identity.secret_check")).toMatch(/^[0-9a-f]{32}$/);+ expect(fs.existsSync(path.join(dir, "backups"))).toBe(false);+ });+});++describe("an install from before accounts", () => {+ it("is copied first, then its password and tokens move to accounts; old cookies stop, tokens keep working", async () => {+ const dir = newDir();+ await preAccountsDb(dir);+ const before = writeAuthJson(dir, { password: "the old password", tokens: true });+ const m = await boot(dir);++ // 1. The pre-accounts snapshot: the database as it was, beside a manifest, private.+ const snap = m.report.snapshot!;+ expect(path.basename(snap.db)).toMatch(/^fuobe-\d{8}T\d{6}Z-pre-accounts\.db$/);+ expect(fs.statSync(snap.db).mode & 0o777).toBe(0o600);+ const copy = new Database(snap.db, { readonly: true });+ const tables = (copy.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as { name: string }[]).map((r) => r.name);+ expect(tables).not.toContain("users");+ expect(copy.prepare("SELECT value FROM settings WHERE key = 'engine.mode'").get()).toEqual({ value: "open" });+ copy.close();+ expect(JSON.parse(fs.readFileSync(snap.manifest, "utf8"))).toMatchObject({ kind: "pre-accounts", stripped: [] });++ // 2. Personal with sign-in; the password and both tokens imported once.+ expect(m.report).toMatchObject({ importedPassword: true, importedTokens: 2, signin: "on" });+ expect(m.mode.signInRequired()).toBe(true);+ expect(m.mode.installValue("engine.mode")).toBe("open");+ expect(m.dbm.db().prepare("SELECT source FROM users WHERE id = 'u_owner'").get()).toEqual({ source: "legacy" });+ const id = m.owner.ownerAuthUserId()!;+ expect(await m.ops.passwordNeedsRehash(id)).toBe(true);++ // 3. The old password signs in (one password field), and is rewritten as scrypt v2.+ expect((await m.login.POST(loginPost("not it at all"))).status).toBe(401);+ const ok = await m.login.POST(loginPost("the old password"));+ expect(ok.status).toBe(200);+ expect(ok.headers.getSetCookie().some((c) => c.startsWith("fuobe.session_token="))).toBe(true);+ expect(await m.ops.passwordNeedsRehash(id)).toBe(false);++ // 4. The tokens are legacy Full tokens with the same hashes: the CLI and MCP keep working.+ expect(m.tokens.listTokens("u_owner")).toEqual([+ { id: "aaaaaaaaaaaa", name: "CLI", prefix: TOKEN_A.slice(0, 12), createdAt: 1_700_000_000_000, lastUsedAt: 1_700_000_100_000, legacy: true },+ { id: "bbbbbbbbbbbb", name: "MCP", prefix: TOKEN_B.slice(0, 12), createdAt: 1_700_000_200_000, legacy: true },+ ]);+ const api = await m.proxy(req("http://localhost:3000/api/generations", { authorization: `Bearer ${TOKEN_B}` }));+ expect(api.headers.get("x-middleware-next")).toBe("1");+ // A pre-accounts session cookie is no longer accepted.+ const old = await m.proxy(req("http://localhost:3000/library", { cookie: `fuobe_session=${Date.now() + 1e9}.abc` }));+ expect(old.status).toBe(307);++ // 5. auth.json stays, untouched, for one release.+ expect(JSON.parse(fs.readFileSync(path.join(dir, "auth.json"), "utf8"))).toEqual(before);++ // A second start changes nothing and imports nothing again.+ const again = await boot(dir);+ expect(again.report).toMatchObject({ snapshot: null, importedPassword: false, importedTokens: 0, signin: "on" });+ expect(again.tokens.listTokens("u_owner")).toHaveLength(2);+ });++ it("without a password stays Just me, and its tokens still move", async () => {+ const dir = newDir();+ await preAccountsDb(dir);+ writeAuthJson(dir, { tokens: true });+ const m = await boot(dir);+ expect(m.report).toMatchObject({ importedPassword: false, importedTokens: 2, signin: "off" });+ expect(m.report.snapshot).not.toBeNull();+ expect(m.mode.signInRequired()).toBe(false);+ expect(m.owner.ownerAuthUserId()).toBeNull();+ expect(m.tokens.tokenFromHeader(`Bearer ${TOKEN_A}`)).toMatchObject({ userId: "u_owner" });+ });+});++describe("FUOBE_PASSWORD", () => {+ it("turns sign-in on, is the owner's password, and is synced at every start", async () => {+ const dir = newDir();+ process.env.FUOBE_PASSWORD = "break glass one";+ const m = await boot(dir);+ expect(m.report).toMatchObject({ syncedEnvPassword: true, signin: "on" });+ expect(m.dbm.db().prepare("SELECT source FROM users WHERE id = 'u_owner'").get()).toEqual({ source: "env" });+ expect(await m.owner.checkOwnerPassword("break glass one")).toBe(true);+ const cookie = (await m.login.POST(loginPost("break glass one"))).headers.getSetCookie()[0].split(";")[0];+ expect((await m.proxy(req("http://localhost:3000/library", { cookie }))).headers.get("x-middleware-next")).toBe("1");++ // Same value: nothing rewritten, sessions kept.+ const same = await boot(dir);+ expect(same.report.syncedEnvPassword).toBe(false);+ expect((await same.proxy(req("http://localhost:3000/library", { cookie }))).headers.get("x-middleware-next")).toBe("1");++ // A new value replaces the old one and signs every browser out.+ process.env.FUOBE_PASSWORD = "break glass two";+ const changed = await boot(dir);+ expect(changed.report.syncedEnvPassword).toBe(true);+ expect(await changed.owner.checkOwnerPassword("break glass two")).toBe(true);+ expect(await changed.owner.checkOwnerPassword("break glass one")).toBe(false);+ expect((await changed.proxy(req("http://localhost:3000/library", { cookie }))).status).toBe(307);+ });++ it("also works as FUOBE_OWNER_PASSWORD", async () => {+ process.env.FUOBE_OWNER_PASSWORD = "owner from env";+ const m = await boot(newDir());+ expect(m.report.signin).toBe("on");+ expect(await m.owner.checkOwnerPassword("owner from env")).toBe(true);+ });+});++describe("the secret key's fingerprint (§7.15)", () => {+ it("refuses to start with another key, unless FUOBE_ACCEPT_NEW_SECRET=1 (which signs everyone out)", async () => {+ const dir = newDir();+ process.env.FUOBE_PASSWORD = "a password here";+ const m = await boot(dir);+ const cookie = (await m.login.POST(loginPost("a password here"))).headers.getSetCookie()[0].split(";")[0];+ const sessions = () => (m.dbm.db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n;+ expect(sessions()).toBe(1);++ process.env.FUOBE_SECRET = "f".repeat(64);+ const refused = await load(dir);+ await expect(refused.bootstrap.bootstrapIdentity()).rejects.toThrow(/secret key doesn't match/);+ await expect(refused.bootstrap.bootstrapIdentity()).rejects.toBeInstanceOf(refused.bootstrap.StartupError);++ process.env.FUOBE_ACCEPT_NEW_SECRET = "1";+ const accepted = await boot(dir);+ expect((accepted.dbm.db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(0);+ expect((await accepted.proxy(req("http://localhost:3000/library", { cookie }))).status).toBe(307);+ // From now on the new key is the expected one.+ delete process.env.FUOBE_ACCEPT_NEW_SECRET;+ expect((await boot(dir)).report.signin).toBe("on");+ });++ it("refuses a FUOBE_SECRET that is too short", async () => {+ process.env.FUOBE_SECRET = "short";+ const m = await load(newDir());+ await expect(m.bootstrap.bootstrapIdentity()).rejects.toThrow(/FUOBE_SECRET is too short/);+ });+});++describe("FUOBE_MODE", () => {+ it("personal boots (Just me unless a password says otherwise); studio and platform aren't ready yet", async () => {+ process.env.FUOBE_MODE = "personal";+ expect((await boot(newDir())).report.signin).toBe("off");+ process.env.FUOBE_MODE = "studio";+ await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/FUOBE_MODE=studio needs the first-run setup/);+ process.env.FUOBE_MODE = "platform";+ await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/FUOBE_DEV_PLATFORM=1/);+ process.env.FUOBE_MODE = "public";+ await expect((await load(newDir())).bootstrap.bootstrapIdentity()).rejects.toThrow(/isn't a mode/);+ });+});diff --git a/tests/identity-load.test.ts b/tests/identity-load.test.tsnew file mode 100644index 00000000..500beedd--- /dev/null+++ b/tests/identity-load.test.ts@@ -0,0 +1,69 @@+/**+ * Better Auth's connection and Fuobe's share one SQLite file (docs/research/accounts-8.md §7.1). Busy waits+ * block the event loop, so a lock held across an await would stall everything: 50 sign-ins while a runner keeps+ * writing must never wait anywhere near the 5 s busy timeout (each wait stays under 1 s), and nothing fails.+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { monitorEventLoopDelay } from "node:perf_hooks";+import { afterAll, describe, expect, it } from "vitest";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-load-"));+process.env.FUOBE_DATA_DIR = dir;+for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET"]) delete process.env[k];++const { db } = await import("@/server/db");+const { bootstrapIdentity } = await import("@/server/identity/bootstrap");+const { signInOwner } = await import("@/server/identity/owner");+const { setOwnerPassword } = await import("./helpers/identity");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++await bootstrapIdentity();+const PASSWORD = "correct horse battery";+await setOwnerPassword(PASSWORD);++describe("sign-ins while the runner writes", () => {+ it("50 sign-ins succeed, the runner's writes all land, and no busy wait reaches 1 s", { timeout: 60_000 }, async () => {+ // A runner: a write transaction every couple of milliseconds, like the generation runner's ticks.+ let writes = 0;+ const failures: string[] = [];+ const upsert = db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value");+ const tick = db().transaction((n: number) => {+ for (let i = 0; i < 20; i++) upsert.run(`load.${n % 50}.${i}`, String(n));+ });+ const runner = setInterval(() => {+ try {+ tick(writes++);+ } catch (e) {+ failures.push((e as Error).message);+ }+ }, 2);++ const delay = monitorEventLoopDelay({ resolution: 10 });+ delay.enable();+ const durations: number[] = [];+ try {+ for (let batch = 0; batch < 10; batch++) {+ await Promise.all(+ Array.from({ length: 5 }, async () => {+ const t = performance.now();+ const r = await signInOwner(PASSWORD, new Headers({ "user-agent": `load test ${batch}` }));+ durations.push(performance.now() - t);+ if (!r.ok) failures.push(`sign-in: ${r.code ?? "refused"}`);+ }),+ );+ }+ } finally {+ clearInterval(runner);+ delay.disable();+ }++ expect(failures).toEqual([]);+ expect(durations).toHaveLength(50);+ expect(writes).toBeGreaterThan(50);+ expect((db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(50);+ // A busy wait blocks the event loop: the longest block is the longest wait.+ expect(delay.max / 1e6).toBeLessThan(1000);+ });+});diff --git a/tests/identity-proxy.test.ts b/tests/identity-proxy.test.tsnew file mode 100644index 00000000..aa14dda3--- /dev/null+++ b/tests/identity-proxy.test.ts@@ -0,0 +1,174 @@+/**+ * The proxy after accounts (docs/research/accounts-8.md §7.1, §8): Just me on this computer, a password install,+ * API tokens (valid, wrong, revoked), Better Auth's session cookie, refusal codes, share links, the client-IP+ * header only a trusted proxy may set, session refresh on POST, and no-store on sign-in paths.+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { NextRequest } from "next/server";+import { afterAll, describe, expect, it, vi } from "vitest";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-proxy-"));+process.env.FUOBE_DATA_DIR = dir;+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 { proxy } = await import("@/proxy");+const { db } = await import("@/server/db");+const { bootstrapIdentity } = await import("@/server/identity/bootstrap");+const tokens = await import("@/server/identity/tokens");+const shares = await import("@/server/shares");+const gens = await import("@/server/generations");+const { saveFile } = await import("@/server/storage");+const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");+const { SHARE_VIEW_HEADER } = await import("@/lib/share");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++await bootstrapIdentity();+const PASSWORD = "correct horse battery";++const req = (url: string, init: { method?: string; headers?: Record<string, string> } = {}) =>+ new NextRequest(url, {+ method: init.method ?? "GET",+ headers: { host: new URL(url).host, ...(init.method && init.method !== "GET" && { origin: new URL(url).origin }), ...init.headers },+ ...(init.method && init.method !== "GET" && init.method !== "HEAD" && { body: "{}" }),+ });+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";+const forwarded = (r: Response, name: string) => r.headers.get(`x-middleware-request-${name}`);++describe("Just me on this computer", () => {+ it("lets every page and API through as the owner, with no sign-in", async () => {+ expect(passed(await proxy(req("http://localhost:3000/library")))).toBe(true);+ expect(passed(await proxy(req("http://localhost:3000/api/generations", { method: "POST" })))).toBe(true);+ });++ it("ignores a wrong bearer token and accepts a right one", async () => {+ expect(passed(await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: "Bearer fuobe_wrong" } })))).toBe(true);+ const { token } = tokens.createToken("u_owner", "CLI");+ expect(passed(await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: `Bearer ${token}` } })))).toBe(true);+ });++ it("sends /login home: there is nothing to sign in to", async () => {+ const r = await proxy(req("http://localhost:3000/login"));+ expect(r.status).toBe(307);+ expect(new URL(r.headers.get("location")!).pathname).toBe("/");+ });++ it("keeps the DNS-rebinding and cross-site checks", async () => {+ expect((await proxy(req("http://rebind.attacker.example/library"))).status).toBe(403);+ expect((await proxy(req("http://localhost:3000/api/generations", { method: "POST", headers: { origin: "http://evil.example" } }))).status).toBe(403);+ });++ it("answers 404 at /api/identity: Better Auth isn't mounted", async () => {+ const route = await import("@/app/api/identity/[...all]/route");+ expect((await route.GET(new Request("http://localhost:3000/api/identity/get-session", { headers: { host: "localhost:3000" } }))).status).toBe(404);+ });+});++describe("the client address Better Auth sees", () => {+ it("is never what the client wrote", async () => {+ const r = await proxy(req("http://localhost:3000/api/generations", { headers: { "x-fuobe-client-ip": "6.6.6.6", "x-forwarded-for": "6.6.6.6" } }));+ expect(passed(r)).toBe(true);+ expect(forwarded(r, "x-fuobe-client-ip")).toBeNull();+ expect(r.headers.get("x-middleware-override-headers") ?? "").not.toContain("x-fuobe-client-ip");+ });++ it("comes from X-Forwarded-For only behind a trusted proxy (hops or ranges)", async () => {+ vi.stubEnv("FUOBE_TRUST_PROXY", "1");+ try {+ const r = await proxy(req("http://localhost:3000/api/generations", { headers: { "x-fuobe-client-ip": "6.6.6.6", "x-forwarded-for": "6.6.6.6, 203.0.113.5" } }));+ expect(forwarded(r, "x-fuobe-client-ip")).toBe("203.0.113.5");+ } finally {+ vi.unstubAllEnvs();+ }+ vi.stubEnv("FUOBE_TRUSTED_PROXIES", "10.0.0.0/8, 192.0.2.1");+ try {+ const r = await proxy(req("http://localhost:3000/api/generations", { headers: { "x-forwarded-for": "6.6.6.6, 198.51.100.7, 10.1.2.3, 192.0.2.1" } }));+ expect(forwarded(r, "x-fuobe-client-ip")).toBe("198.51.100.7");+ } finally {+ vi.unstubAllEnvs();+ }+ });+});++describe("a password install", () => {+ it("needs a session or a token for everything but sign-in", async () => {+ await setOwnerPassword(PASSWORD);+ const api = await proxy(req("http://localhost:3000/api/generations"));+ expect(api.status).toBe(401);+ expect(api.headers.get("www-authenticate")).toMatch(/Bearer/);+ const page = await proxy(req("http://localhost:3000/cinema?tab=new"));+ expect(page.status).toBe(307);+ const to = new URL(page.headers.get("location")!);+ expect(to.pathname).toBe("/login");+ expect(to.searchParams.get("next")).toBe("/cinema?tab=new");+ for (const open of ["/login", "/api/auth/login", "/api/identity/get-session"]) {+ const r = await proxy(req(`http://localhost:3000${open}`, open === "/api/auth/login" ? { method: "POST" } : {}));+ expect(passed(r), open).toBe(true);+ expect(r.headers.get("cache-control"), open).toBe("no-store");+ }+ expect((await proxy(req("http://localhost:3000/library"))).headers.get("cache-control")).toBeNull();+ });++ it("takes API tokens: a right one passes, a wrong or revoked one is 401 with a way forward", async () => {+ const { token, info } = tokens.createToken("u_owner", "MCP");+ expect(passed(await proxy(req("http://localhost:3000/api/mcp", { method: "POST", headers: { authorization: `Bearer ${token}` } })))).toBe(true);+ const wrong = await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: "Bearer fuobe_wrong" } }));+ expect(wrong.status).toBe(401);+ expect(((await wrong.json()) as { error: string }).error).toMatch(/isn't valid/);+ tokens.revokeToken("u_owner", info.id);+ expect((await proxy(req("http://localhost:3000/api/generations", { headers: { authorization: `Bearer ${token}` } }))).status).toBe(401);+ });++ it("takes Better Auth's session cookie, until the session ends", async () => {+ const cookie = await ownerCookie(PASSWORD);+ expect(cookie).toMatch(/^fuobe\.session_token=/);+ expect(passed(await proxy(req("http://localhost:3000/library", { headers: { cookie } })))).toBe(true);+ const logout = await import("@/app/api/auth/logout/route");+ const out = await logout.POST(new Request("http://localhost:3000/api/auth/logout", { method: "POST", headers: { cookie, host: "localhost:3000" } }));+ expect(out.headers.getSetCookie().some((c) => /fuobe\.session_token=;/.test(c) && /Max-Age=0/i.test(c))).toBe(true);+ expect((await proxy(req("http://localhost:3000/library", { headers: { cookie } }))).status).toBe(307);+ });++ it("refuses a person who may not act with their code (API) or on the sign-in card (pages)", async () => {+ const cookie = await ownerCookie(PASSWORD);+ db().prepare("UPDATE users SET status = 'disabled' WHERE id = 'u_owner'").run();+ try {+ const api = await proxy(req("http://localhost:3000/api/generations", { headers: { cookie } }));+ expect(api.status).toBe(403);+ expect(await api.json()).toMatchObject({ code: "ACCOUNT_DISABLED", error: expect.stringMatching(/turned off/) });+ const page = await proxy(req("http://localhost:3000/library", { headers: { cookie } }));+ expect(new URL(page.headers.get("location")!).searchParams.get("code")).toBe("ACCOUNT_DISABLED");+ } finally {+ db().prepare("UPDATE users SET status = 'active' WHERE id = 'u_owner'").run();+ }+ });++ it("refreshes a session that is due, on a POST only", async () => {+ const cookie = await ownerCookie(PASSWORD);+ // Two days into a 30-day session: due for its daily refresh.+ const token = decodeURIComponent(cookie.split("=")[1]).split(".")[0];+ const due = new Date(Date.now() + 28 * 86_400_000);+ db().prepare('UPDATE auth_session SET "expiresAt" = ? WHERE token = ?').run(due.toISOString(), token);+ const get = await proxy(req("http://localhost:3000/library", { headers: { cookie } }));+ expect(passed(get)).toBe(true);+ expect(get.headers.getSetCookie()).toEqual([]);+ const post = await proxy(req("http://localhost:3000/api/generations", { method: "POST", headers: { cookie } }));+ expect(passed(post)).toBe(true);+ expect(post.headers.getSetCookie().some((c) => c.startsWith("fuobe.session_token="))).toBe(true);+ const after = db().prepare('SELECT "expiresAt" AS e FROM auth_session WHERE token = ?').get(token) as { e: string };+ expect(new Date(after.e).getTime()).toBeGreaterThan(due.getTime() + 86_400_000);+ });++ it("opens a live share link without a session, and the signed-in owner's own visit isn't a view", async () => {+ const asset = saveFile({ data: Buffer.from("not really a png"), contentType: "image/png", source: "generation" });+ const g = gens.recordLocalGeneration({ feature: "grade", modelId: "local-color-grade", op: "grade", prompt: "proxy pier", inputs: {}, output: { url: asset.url, kind: "image", contentType: "image/png" } });+ const S = shares.createShare({ kind: "result", targetId: g.id });+ const visitor = await proxy(req(`http://localhost:3000/s/${S.token}`, { headers: { "user-agent": "Mozilla/5.0 Chrome/141.0" } }));+ expect(passed(visitor)).toBe(true);+ expect(forwarded(visitor, SHARE_VIEW_HEADER)).toBe("1");+ const cookie = await ownerCookie(PASSWORD);+ const own = await proxy(req(`http://localhost:3000/s/${S.token}`, { headers: { "user-agent": "Mozilla/5.0 Chrome/141.0", cookie } }));+ expect(forwarded(own, SHARE_VIEW_HEADER)).toBeNull();+ });+});diff --git a/tests/identity-snapshot.test.ts b/tests/identity-snapshot.test.tsnew file mode 100644index 00000000..abd4d982--- /dev/null+++ b/tests/identity-snapshot.test.ts@@ -0,0 +1,83 @@+/**+ * Snapshots never carry live credentials (docs/research/accounts-8.md §7.16), and the security headers (§7.1).+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import Database from "better-sqlite3";+import { afterAll, describe, expect, it } from "vitest";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-snap-"));+process.env.FUOBE_DATA_DIR = dir;+for (const k of ["FUOBE_PASSWORD", "FUOBE_OWNER_PASSWORD", "FUOBE_SIGNIN", "FUOBE_MODE", "FUOBE_SECRET"]) delete process.env[k];++const { db } = await import("@/server/db");+const { bootstrapIdentity } = await import("@/server/identity/bootstrap");+const { snapshotDatabase, STRIPPED_TABLES } = await import("@/server/backup/snapshot");+const { setOwnerPassword, ownerCookie } = await import("./helpers/identity");+const nextConfig = (await import("../next.config")).default;+const { getPathMatch } = await import("next/dist/shared/lib/router/utils/path-match");+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++await bootstrapIdentity();++describe("database snapshots", () => {+ it("strip sessions, verifications and step-up marks, even from free pages, and keep everything else", async () => {+ await setOwnerPassword("correct horse battery");+ const cookie = await ownerCookie("correct horse battery");+ const token = decodeURIComponent(cookie.split("=")[1]).split(".")[0];+ const now = new Date().toISOString();+ db().prepare(`INSERT INTO auth_verification (id, identifier, value, "expiresAt", "createdAt", "updatedAt") VALUES ('v1', 'reset:owner', 'secret-reset-value', ?, ?, ?)`).run(now, now, now);+ db().prepare("INSERT INTO session_step_up (session_id, user_id, confirmed_at, expires_at) VALUES ('s1', 'u_owner', 1, 2)").run();+ expect((db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(1);++ const snap = snapshotDatabase({ kind: "manual" });+ expect(path.dirname(snap.db)).toBe(path.join(dir, "backups"));+ expect(fs.statSync(path.join(dir, "backups")).mode & 0o777).toBe(0o700);+ for (const f of [snap.db, snap.secret!, snap.manifest]) expect(fs.statSync(f).mode & 0o777, f).toBe(0o600);+ expect(fs.readFileSync(snap.secret!)).toEqual(fs.readFileSync(path.join(dir, "secret.key")));++ const copy = new Database(snap.db, { readonly: true });+ for (const t of ["auth_session", "auth_verification", "session_step_up"]) expect((copy.prepare(`SELECT COUNT(*) AS n FROM "${t}"`).get() as { n: number }).n, t).toBe(0);+ expect(copy.prepare("SELECT id FROM users").all()).toEqual([{ id: "u_owner" }]);+ expect((copy.prepare("SELECT COUNT(*) AS n FROM auth_account").get() as { n: number }).n).toBe(1);+ copy.close();+ // Not even the bytes of a deleted row survive.+ const bytes = fs.readFileSync(snap.db).toString("latin1");+ expect(bytes).not.toContain(token);+ expect(bytes).not.toContain("secret-reset-value");++ const manifest = JSON.parse(fs.readFileSync(snap.manifest, "utf8"));+ expect(manifest).toMatchObject({ kind: "manual", database: path.basename(snap.db), stripped: ["auth_session", "auth_verification", "session_step_up"] });+ expect(STRIPPED_TABLES).toEqual(expect.arrayContaining(["auth_session", "auth_verification", "session_step_up", "cli_connect_requests", "request_keys"]));+ // The live database still has its session.+ expect((db().prepare("SELECT COUNT(*) AS n FROM auth_session").get() as { n: number }).n).toBe(1);+ });++ it("refuse an odd kind name", () => {+ expect(() => snapshotDatabase({ kind: "../escape" })).toThrow(/kind/);+ });+});++describe("security headers", () => {+ const rules = async () => (await nextConfig.headers!()) as { source: string; headers: { key: string; value: string }[] }[];+ const headersFor = async (pathname: string) => {+ const out: Record<string, string> = {};+ for (const r of await rules()) if (getPathMatch(r.source, { removeUnnamedParams: true, strict: true })(pathname)) for (const h of r.headers) out[h.key] = h.value;+ return out;+ };++ it("forbid framing everywhere but share pages", async () => {+ for (const p of ["/", "/library", "/settings", "/login", "/api/files/outputs/a.png", "/s"]) {+ expect(await headersFor(p), p).toMatchObject({ "X-Frame-Options": "DENY", "Content-Security-Policy": "frame-ancestors 'none'" });+ }+ for (const p of ["/s/abcdefabcdefabcdefabcdefabcdefabcdefabcdefab", "/s/abc/f/outputs/a.png"]) {+ expect(await headersFor(p), p).not.toHaveProperty("X-Frame-Options");+ }+ });++ it("keep sign-in pages and their APIs out of every cache", async () => {+ for (const p of ["/login", "/api/auth/login", "/api/auth/tokens", "/api/identity/get-session"]) expect((await headersFor(p))["Cache-Control"], p).toBe("no-store");+ expect(await headersFor("/library")).not.toHaveProperty("Cache-Control");+ });+});