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
Admin tokens: manage an install from your own tools
Adarsh01fb8ff032df
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 73c533a0..2712616f 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -363,6 +363,7 @@ only on those routes; `validToken()` never takes one. See [gpu-workers.md](gpu-w- **Sign-in** is off until a password is set in Settings → Security or `FUOBE_PASSWORD`. State lives in `data/auth.json` (not SQLite) so the proxy can check requests with `fs` and `crypto` alone: a scrypt password hash, an HMAC secret for 30-day session cookies (replaced when the password changes), and API tokens stored as SHA-256 hashes (with public sign-up, below, the accounts too). The proxy lets `/login` and `/api/auth/login` through (and, since round 4 part 4, GET and HEAD on a share link's page and files, checked by `openShare`: see Share links), answers other API calls with 401 and redirects pages to `/login?next=…` (`safeNext()` in `src/lib/safe-redirect.ts` keeps it on the same origin). Its matcher leaves out only build assets, `samples/`, `previews/`, `vendor/`, root SVGs and `/api/uploads` (which makes the proxy's checks itself: `src/server/direct-gate.ts`).- **Public sign-up** (the owner's, on main; [`docs/public-signup.md`](public-signup.md) is the whole design). It is off by default and needs a password; `FUOBE_PUBLIC_SIGNUP` or Settings → Security turns it on. `src/lib/guest-access.ts` holds the path rules and `src/proxy.ts` applies them. Guests (signed out) read the pages and catalogs, and every change answers 401. Accounts see a guest view of the owner's library: a change to it or to a project answers 403 `library` (`LIBRARY_CHANGES`), and settings, keys and tokens are the owner's. Price checks stay open to both (`isPriceCheck`: the estimate routes in `ESTIMATES`, `?preview=1` on the run routes in `PREVIEWS`), and `priceAs` (`src/server/visitor.ts`) prices a visitor's run as it would go on its own GPU. The one run an account may start is `POST /api/generations` (`ownGpuRun`), on its own ComfyUI; without one connected, any run answers `connect-gpu`, and with one, every other tool answers `own-gpu-tool`. Round 5 part 2's tools follow these rules. `/api/turnaround?preview=1` is in `PREVIEWS` and `/api/turnaround/estimate` in `ESTIMATES`. Split soundtrack and its remux (`POST /api/audio-tools`), the turnaround and Cinema's `path` and `turnaround` actions answer a guest 401, an account without a GPU `connect-gpu`, and an account with one `own-gpu-tool`. Export mix (`POST /api/audio-tools/export`) is in `LIBRARY_CHANGES`, since it saves into the owner's Library. MOSS-Image runs for an account through `POST /api/generations` on its own ComfyUI, the only new tool an account can run. A turnaround that names a character (`elementId`) answers any visitor 404 "Character not found", whether or not it exists (`requestViewer`, `recordExists`). `tests/public-signup-tools.test.ts` (12 tests) checks these answers through the API; the browser checks ran with public sign-up off.+- **Admin tokens** (`src/server/admin-tokens.ts`, [`docs/admin-api.md`](admin-api.md)): `fuobe_adm_…` tokens with scopes, stored in SQLite (`admin_tokens`, SHA-256 only) and made in Settings → Security from the owner's signed-in browser. The proxy lets one through only on `/api/admin/*` (not `/api/admin/tokens`, except `/self`); every admin route checks it with `adminAccess(request, scope)`, which judges a request by its admin token alone, and otherwise asks for the owner as before. `validToken()` never takes one. Per-token limits (120 a minute, 30 changes) and a separate budget for wrong tokens. Changes, a token's reads and file views, and refusals go to `admin_audit` (kept a year).- **Host allowlist** (`hostAllowed`), for every method when no password is set, before anything else: IP literals, localhost and `*.localhost`, single-label names, `.local` / `.lan` / `.home.arpa` / `.internal` / `.localdomain`, this machine's hostname, and `FUOBE_ALLOWED_ORIGINS` (`*` allows any). This stops DNS rebinding. `X-Forwarded-Host` is not trusted here.- **Cross-site writes** (`crossSite`): non-GET/HEAD/OPTIONS requests get 403 when `Origin` matches neither Host, `X-Forwarded-Host` nor `FUOBE_ALLOWED_ORIGINS`, when it is `null`, or when `Sec-Fetch-Site` is cross-site — with or without a password.- **Login throttle** (`LoginGuard`): 5 misses per client and 20 a minute overall, bounded map, `Retry-After`. Route handlers can't see the socket address, so the client key is the last `X-Forwarded-For` hop only with `FUOBE_TRUST_PROXY=1` (then a 60 s lock per client); otherwise everyone shares a key that is slowed to one attempt every 4 s and never locked. Since round 4 part 4 the same client key drives `ShareGuard`, the throttle on wrong share tokens.diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex f32d9526..ee312368 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -72,6 +72,8 @@ Share links are the one exception: `/s/<token>` and its files open for anyone whA sign-in lasts 30 days. If you think someone else has signed in as you, open **Settings → Security** and press **Sign everyone out**. It ends every sign-in on every device, yours included (an open live feed too), and can revoke every API token too. Your password stays the same. A new password also ends every owner sign-in: a Settings password change at once (it signs accounts out too), and a new `FUOBE_PASSWORD` when the server restarts (accounts stay signed in). API tokens are not tied to the password: revoke them in **Settings → Security**, or tick **Also revoke every API token** when you sign everyone out.+To manage accounts, runs and workers from your own tools without the owner's sign-in, make an **admin token** in the same place: it works only on `/api/admin`, and only for the rights you tick ([admin-api.md](admin-api.md)).+Public sign-up, guest browsing and connecting your own GPU to a shared install are described in [public-signup.md](public-signup.md).## Environment variablesdiff --git a/docs/admin-api.md b/docs/admin-api.mdnew file mode 100644index 00000000..efaab536--- /dev/null+++ b/docs/admin-api.md@@ -0,0 +1,147 @@+# Manage your Fuobe from your own tools++An install can be managed from your own tools with an **admin API token**: a script, a dashboard or a small admin app+of your own can list accounts, switch them off, read and delete their runs, take results down, read reports and run+the workers, without signing in as the owner.++An admin token:++- works **only on `/api/admin/*`**. Anywhere else (pages, Settings, sign-in, the studio's API, `/api/mcp`) it gets+ `403 "An admin token only works on the admin API."`;+- does **only what you ticked** when you made it (its scopes);+- is **never the owner**: it can't sign in, change settings or keys, or make or revoke tokens;+- is judged on its own: a session cookie sent with it is ignored;+- is stored only as its SHA-256. You see the token once, when you make it.++Every change made through the admin API is written to the **admin log**, and so is every file a token opens and its+reads of people's data. The log never holds a token, a password, a prompt or an IP address.++## Make a token++1. Open **Settings → Security** in the owner's signed-in browser.+2. Under **Admin tokens**, press **New admin token**.+3. Name it, tick what it may do (**Read only** and **Full admin** tick sets for you), pick an expiry and press+ **Create admin token**.+4. Copy the token (`fuobe_adm_…`, 53 characters). It isn't shown again.++The list shows each token's first characters, its scopes, when it was made and last used, and when it expires.+**Revoke** stops it at once. **Sign everyone out** with **Also revoke every API token** revokes admin tokens too. An+install keeps at most 20 live admin tokens.++Keep the token out of URLs, logs and shared files. Send it only in the `Authorization` header, and only over HTTPS.++## Scopes++| Scope | Lets the token |+|---|---|+| `accounts:read` | `GET /api/admin/accounts` (JSON or CSV), `GET /api/admin/accounts/{id}` |+| `accounts:write` | `PATCH /api/admin/accounts/{id}` with `{ "disabled": true \| false }` or `{ "signOut": true }` |+| `accounts:delete` | `DELETE /api/admin/accounts/{id}`: its runs, files and record go. It can't be undone |+| `runs:read` | `GET /api/admin/generations`: accounts' runs, prompts included (never the owner's own runs) |+| `runs:delete` | `DELETE /api/admin/generations/{id}`: a run still going is canceled first |+| `outputs:view` | `GET /api/admin/files/{path}`: an account's stored file, or a held one. Each view is logged |+| `outputs:hide` | `POST /api/admin/outputs/hide` |+| `outputs:moderate` | `POST /api/admin/outputs/hide`, `/unhide` and `/remove` |+| `reports:read` | `GET /api/admin/reports` (reporters' emails included) |+| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/download` |+| `workers:write` | `POST /api/admin/workers`, `PATCH /api/admin/workers/{id}` |+| `queue:read` | `GET /api/admin/queue` |+| `audit:read` | `GET /api/admin/audit` |++Any valid admin token may call `GET /api/admin/tokens/self`, which says the token's name and scopes, so a tool can+offer only what it may do. `/api/admin/tokens` itself (make, list, revoke) is the owner's signed-in browser's only.++## Examples++```sh+export FUOBE=https://fuobe.example.com+export TOKEN=fuobe_adm_... # from Settings → Security → Admin tokens++# Which token is this, and what may it do?+curl -s "$FUOBE/api/admin/tokens/self" -H "Authorization: Bearer $TOKEN"++# Accounts, with their runs and space; one by email; every email containing "studio"+curl -s "$FUOBE/api/admin/accounts" -H "Authorization: Bearer $TOKEN"+curl -s "$FUOBE/api/admin/[email protected]" -H "Authorization: Bearer $TOKEN"+curl -s "$FUOBE/api/admin/accounts?q=studio" -H "Authorization: Bearer $TOKEN"++# Switch an account off, sign it out everywhere, delete it+curl -s -X PATCH "$FUOBE/api/admin/accounts/ACCOUNT_ID" -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: application/json" -d '{"disabled": true}'+curl -s -X PATCH "$FUOBE/api/admin/accounts/ACCOUNT_ID" -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: application/json" -d '{"signOut": true}'+curl -s -X DELETE "$FUOBE/api/admin/accounts/ACCOUNT_ID" -H "Authorization: Bearer $TOKEN"++# Accounts' failed video runs, 50 a page; then the next page+curl -s "$FUOBE/api/admin/generations?status=failed&kind=video&limit=50" -H "Authorization: Bearer $TOKEN"+curl -s "$FUOBE/api/admin/generations?status=failed&kind=video&limit=50&before=NEXT" -H "Authorization: Bearer $TOKEN"++# Open a result's file (an output's url is /api/files/<path>: ask /api/admin/files/<path>)+curl -s -o result.png "$FUOBE/api/admin/files/PATH" -H "Authorization: Bearer $TOKEN"++# Hide a run's results+curl -s -X POST "$FUOBE/api/admin/outputs/hide" -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: application/json" -d '{"generationIds": ["RUN_ID"]}'++# The admin log, newest first+curl -s "$FUOBE/api/admin/audit?limit=50" -H "Authorization: Bearer $TOKEN"+```++## Calls++Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control: no-store`.++| Call | Request | Answer |+|---|---|---|+| `GET /api/admin/accounts` | `q` (the email contains it, up to 100 characters), `email` (exactly that address), `format=csv` | `{ total, items, totals }`; with `q` or `email`, also `matched`. `total` and `totals` always cover every account. CSV: a `text/csv` download |+| `GET /api/admin/accounts/{id}` | | one account with its numbers; 404 `No such account` |+| `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }` or `{ signOut: true }` | the account (no numbers) |+| `DELETE /api/admin/accounts/{id}` | | 204 |+| `GET /api/admin/generations` | `account`, `status` (`finished`, `running`, `failed`), `kind` (`image`, `video`, `audio`, `model3d`, `text`), `before` (the last page's `next`), `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page |+| `DELETE /api/admin/generations/{id}` | | 204; 404 for an unknown run or the owner's own |+| `POST /api/admin/outputs/hide` | `{ assetIds?, generationIds? }` (up to 500 each) | `{ hidden }` |+| `POST /api/admin/outputs/unhide` | the same | `{ shown }` |+| `POST /api/admin/outputs/remove` | the same, and `evidence?: true` to keep the files in a locked folder | `{ removed }` |+| `GET /api/admin/files/{path}` | `Range` works | the file; 404 for the owner's own files and unknown paths |+| `GET /api/admin/reports` | `limit` (1 to 500, default 100) | `{ items }`, newest first |+| `GET /api/admin/queue` | | `{ lanes }` |+| `GET /api/admin/workers` | | `{ workers, lanes }` |+| `POST /api/admin/workers` | `{ name, pool? }` | 201 `{ id, token }`: the worker's token, once |+| `PATCH /api/admin/workers/{id}` | any of `paused`, `pauseNow`, `drain`, `autoResume`, `hours`, `allow`, `claimAfterMs`, `switchAfterMs`, `rotate`, `revoke` | `{ worker, token? }`: a new worker token after `rotate`, once |+| `GET /api/admin/workers/download` | | the worker program, `fuobe-worker.zip` |+| `GET /api/admin/audit` | `before` (the last page's `next`), `limit` (1 to 200, default 50), `actor` (`owner` or `token`), `token` (a token id), `action` | `{ items, next }` |+| `GET /api/admin/tokens/self` | | `{ id, name, prefix, scopes, expiresAt, createdAt }` |++A log row is `{ id, at, actor: "owner" | "token", token: { id, name } | null, action, target, detail, status }`.+`token.name` is the name the token had at the time. Actions: `account.disable`, `account.enable`, `account.signout`,+`account.delete`, `run.delete`, `outputs.hide`, `outputs.unhide`, `outputs.remove`, `worker.add`, `worker.change`,+`worker.rotate`, `worker.revoke`, `token.create`, `token.revoke`; a token's reads `accounts.list`, `accounts.csv`,+`account.read`, `runs.list`, `reports.list`, `audit.read` (one row per token and action every 10 minutes) and+`file.view` (one row per token and file every hour); and refusals `scope.denied` and `rate.limited`. The owner's own+reads in the browser aren't logged. Rows go after a year.++## Errors and limits++Errors are `{ "error": "…" }`, with a `code` where a tool may want to act on it:++| Status | When | Body |+|---|---|---|+| 400 | a wrong body or query | `{ error }` |+| 401 | the token is unknown, revoked or expired | `{ error: "This admin token isn't valid.", code: "token" }` |+| 403 | the token doesn't have the scope | `{ error: "This admin token can't do that.", code: "scope", scope }` |+| 403 | an admin token outside `/api/admin` | `{ error: "An admin token only works on the admin API." }` |+| 404 | not found | `{ error }` |+| 429 | too many requests | `{ error: "Too many requests. Try again in a minute.", code: "rate" }` and `Retry-After` |++A token may send 120 requests a minute, of which 30 may be changes. Wrong tokens count against their sender only (10 a+minute per client behind a trusted proxy, `FUOBE_TRUST_PROXY=1`; else 60 a minute together) and never slow down a+valid token.++The limits are kept in the server's memory: a restart starts them again.++## Behind a proxy or a CDN++The `Authorization` header must reach Fuobe: most reverse proxies forward it as it is. If a CDN or a bot check sits in+front of the site, a script's request may get a challenge page instead of JSON. Let `/api/admin/` requests that carry+`Authorization: Bearer fuobe_adm_…` through without a challenge. Call the site's own HTTPS address, and don't follow+redirects with the token.diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.tsindex aa276136..f732dc0b 100644--- a/src/app/api/admin/accounts/[id]/route.ts+++ b/src/app/api/admin/accounts/[id]/route.ts@@ -1,41 +1,68 @@+import { connection } from "next/server";import { z } from "zod";-import { AccountError, isOwnerRequest, listAccounts, sessionCookieOf, setAccountDisabled } from "@/server/auth";+import { accountsWithStats } from "@/server/account-admin";+import { adminAccess, audit, auditRead, type Actor } from "@/server/admin-tokens";+import { AccountError, listAccounts, setAccountDisabled, signOutAccount } from "@/server/auth";import { removeAccount } from "@/server/account-sweep";-async function owner(request: Request): Promise<Response | null> {- return isOwnerRequest(request, sessionCookieOf(request)) ? null : Response.json({ error: "You can't open this." }, { status: 403 });-}+const NO_STORE = { "Cache-Control": "no-store" };+const DENIED = "You can't open this.";-const failed = (e: unknown) => {- if (e instanceof AccountError) return Response.json({ error: e.message }, { status: e.status });+/** The answer for a failed change, written to the admin log too. */+function failed(e: unknown, actor: Actor, action: string, id: string): Response {+ if (e instanceof AccountError) {+ audit(actor, action, id, null, e.status);+ return Response.json({ error: e.message }, { status: e.status, headers: NO_STORE });+ }throw e;-};+}++/** One account with its numbers (an admin token with accounts:read, or the owner). */+export async function GET(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {+ await connection();+ const access = adminAccess(request, "accounts:read", DENIED);+ if (access instanceof Response) return access;+ const { id } = await ctx.params;+ const account = listAccounts().find((a) => a.id === id);+ if (!account) return Response.json({ error: "No such account" }, { status: 404, headers: NO_STORE });+ auditRead(access.actor, "account.read", null, id);+ return Response.json(accountsWithStats([account]).items[0], { headers: NO_STORE });+}++const Patch = z.union([z.object({ disabled: z.boolean() }).strict(), z.object({ signOut: z.literal(true) }).strict()]);-/** Switch an account off (`{ disabled: true }`: signed out, can't log in) or on again. */+/**+ * Switch an account off (`{ disabled: true }`: signed out, can't log in) or on again, or sign it out everywhere+ * (`{ signOut: true }`: every sign-in ends, and it stays on).+ */export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {- const denied = await owner(request);- if (denied) return denied;- const parsed = z.object({ disabled: z.boolean() }).safeParse(await request.json().catch(() => null));- if (!parsed.success) return Response.json({ error: "Send { disabled: true } or { disabled: false }" }, { status: 400 });+ const access = adminAccess(request, "accounts:write", DENIED);+ if (access instanceof Response) return access;+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Send { disabled: true }, { disabled: false } or { signOut: true }" }, { status: 400, headers: NO_STORE });const { id } = await ctx.params;+ const action = "signOut" in parsed.data ? "account.signout" : parsed.data.disabled ? "account.disable" : "account.enable";try {- setAccountDisabled(id, parsed.data.disabled);+ if ("signOut" in parsed.data) signOutAccount(id);+ else setAccountDisabled(id, parsed.data.disabled);} catch (e) {- return failed(e);+ return failed(e, access.actor, action, id);}- return Response.json(listAccounts().find((a) => a.id === id));+ audit(access.actor, action, id, null, 200);+ return Response.json(listAccounts().find((a) => a.id === id), { headers: NO_STORE });}/** Delete an account. */export async function DELETE(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {- const denied = await owner(request);- if (denied) return denied;+ const access = adminAccess(request, "accounts:delete", DENIED);+ if (access instanceof Response) return access;const { id } = await ctx.params;// Switched off at once, its running jobs stopped (on its own keys), then its runs, files and record go.try {await removeAccount(id);} catch (e) {- return failed(e);+ return failed(e, access.actor, "account.delete", id);}- return new Response(null, { status: 204 });+ audit(access.actor, "account.delete", id, null, 204);+ return new Response(null, { status: 204, headers: NO_STORE });}diff --git a/src/app/api/admin/accounts/route.ts b/src/app/api/admin/accounts/route.tsindex a74d6cb3..065104e6 100644--- a/src/app/api/admin/accounts/route.ts+++ b/src/app/api/admin/accounts/route.ts@@ -1,23 +1,40 @@import { connection } from "next/server";import { accountsWithStats } from "@/server/account-admin";-import { accountsCsv, isOwnerRequest, listAccounts, sessionCookieOf } from "@/server/auth";+import { adminAccess, auditRead } from "@/server/admin-tokens";+import { accountsCsv, listAccounts, normalizeEmail } from "@/server/auth";const NO_STORE = { "Cache-Control": "no-store" };/**- * Settings → Accounts (owner only): everyone who signed up, newest first, with their runs and space and the totals.- * `?format=csv` downloads the list.+ * Settings → Accounts (owner only, or an admin token with accounts:read): everyone who signed up, newest first, with+ * their runs and space and the totals. `?q=` keeps the emails that contain it, `?email=` the one with that address;+ * `total` and `totals` still count every account. `?format=csv` downloads the list.*/export async function GET(request: Request) {await connection();- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "You can't open this." }, { status: 403, headers: NO_STORE });- const items = listAccounts();- if (new URL(request.url).searchParams.get("format") === "csv") {+ const access = adminAccess(request, "accounts:read", "You can't open this.");+ if (access instanceof Response) return access;+ const sp = new URL(request.url).searchParams;+ const q = sp.get("q")?.trim().toLowerCase() ?? "";+ if (q.length > 100) return Response.json({ error: "Search with up to 100 characters" }, { status: 400, headers: NO_STORE });+ const emailAsked = sp.get("email");+ const email = emailAsked === null ? null : normalizeEmail(emailAsked);+ if (emailAsked !== null && !email) return Response.json({ error: "Enter a valid email address" }, { status: 400, headers: NO_STORE });+ const all = listAccounts();+ const filtered = !!q || email !== null;+ const items = filtered ? all.filter((a) => (!q || a.email.includes(q)) && (email === null || a.email === email)) : all;+ const filters = filtered ? { ...(q && { q: true }), ...(email && { email: true }) } : null;+ if (sp.get("format") === "csv") {+ auditRead(access.actor, "accounts.csv", filters);const day = new Date().toISOString().slice(0, 10);return new Response(accountsCsv(items), {headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="fuobe-accounts-${day}.csv"`, ...NO_STORE },});}- const { items: listed, totals } = accountsWithStats(items);- return Response.json({ total: items.length, items: listed, totals }, { headers: NO_STORE });+ auditRead(access.actor, "accounts.list", filters);+ const { items: listed, totals } = accountsWithStats(all);+ if (!filtered) return Response.json({ total: all.length, items: listed, totals }, { headers: NO_STORE });+ const keep = new Set(items.map((a) => a.id));+ const matches = listed.filter((a) => keep.has(a.id));+ return Response.json({ total: all.length, matched: matches.length, items: matches, totals }, { headers: NO_STORE });}diff --git a/src/app/api/admin/audit/route.ts b/src/app/api/admin/audit/route.tsnew file mode 100644index 00000000..d2050337--- /dev/null+++ b/src/app/api/admin/audit/route.ts@@ -0,0 +1,18 @@+import { connection } from "next/server";+import { adminAccess, auditQueryFrom, auditRead, listAudit } from "@/server/admin-tokens";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * The admin log, newest first (an admin token with audit:read, or the owner): `before=<id>` (the `next` of the last+ * page), `limit` (1 to 200, 50 when not given), `actor=owner|token`, `token=<id>`, `action=<name>`.+ */+export async function GET(request: Request) {+ await connection();+ const access = adminAccess(request, "audit:read", "You can't open this.");+ if (access instanceof Response) return access;+ const q = auditQueryFrom(new URL(request.url).searchParams);+ if ("error" in q) return Response.json({ error: q.error }, { status: 400, headers: NO_STORE });+ auditRead(access.actor, "audit.read");+ return Response.json(listAudit(q), { headers: NO_STORE });+}diff --git a/src/app/api/admin/files/[...path]/route.ts b/src/app/api/admin/files/[...path]/route.tsnew file mode 100644index 00000000..315980ba--- /dev/null+++ b/src/app/api/admin/files/[...path]/route.ts@@ -0,0 +1,24 @@+import { connection } from "next/server";+import { fileAccount, HELD_FILE } from "@/server/account-library";+import { adminAccess, auditFileView } from "@/server/admin-tokens";+import { fileResponse } from "@/server/file-response";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * An account's stored file, for an admin token with outputs:view (or the owner): the path as in an output's url after+ * /api/files/. Only accounts' files and held ones (waiting for their check, or hidden: what moderation has to see);+ * the owner's own files and unknown paths are a 404. Every view by a token is logged. Byte ranges work.+ */+export async function GET(request: Request, ctx: RouteContext<"/api/admin/files/[...path]">) {+ await connection();+ const access = adminAccess(request, "outputs:view", "You can't open this.");+ if (access instanceof Response) return access;+ const { path: parts } = await ctx.params;+ // Next has decoded each segment once already: decoding again would turn %252e into "." (stored names never need it).+ const rel = parts.join("/");+ const owner = fileAccount(rel);+ if (!owner) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });+ auditFileView(access.actor, rel, owner === HELD_FILE ? "held" : owner);+ return fileResponse(request, rel, { cache: "no-store" });+}diff --git a/src/app/api/admin/generations/[id]/route.ts b/src/app/api/admin/generations/[id]/route.tsindex 7cd5069f..d109a01b 100644--- a/src/app/api/admin/generations/[id]/route.ts+++ b/src/app/api/admin/generations/[id]/route.ts@@ -1,20 +1,23 @@import { generationAccount } from "@/server/account-library";-import { isOwnerRequest, sessionCookieOf } from "@/server/auth";+import { adminAccess, audit } from "@/server/admin-tokens";import { deleteForever } from "@/server/library";const NO_STORE = { "Cache-Control": "no-store" };/**- * Delete an account's run for good (owner only), as the account's own delete does: a run still going is canceled- * first, and its files go unless another run still uses them, so the account's space comes back at once. The- * owner's own runs aren't deleted here (the Library has its Trash).+ * Delete an account's run for good (owner only, or an admin token with runs:delete), as the account's own delete does:+ * a run still going is canceled first, and its files go unless another run still uses them, so the account's space+ * comes back at once. The owner's own runs aren't deleted here (the Library has its Trash).*/export async function DELETE(request: Request, ctx: RouteContext<"/api/admin/generations/[id]">) {- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "You can't open this." }, { status: 403, headers: NO_STORE });+ const access = adminAccess(request, "runs:delete", "You can't open this.");+ if (access instanceof Response) return access;const { id } = await ctx.params;const account = generationAccount(id);+ if (account === undefined || account === null) audit(access.actor, "run.delete", id, null, 404);if (account === undefined) return Response.json({ error: "No such run" }, { status: 404, headers: NO_STORE });if (account === null) return Response.json({ error: "That run is yours, not an account's. Delete it in the Library." }, { status: 404, headers: NO_STORE });await deleteForever([id]);+ audit(access.actor, "run.delete", id, { account }, 204);return new Response(null, { status: 204, headers: NO_STORE });}diff --git a/src/app/api/admin/generations/route.ts b/src/app/api/admin/generations/route.tsindex 1d35f884..53e3cc55 100644--- a/src/app/api/admin/generations/route.ts+++ b/src/app/api/admin/generations/route.ts@@ -1,18 +1,21 @@import { connection } from "next/server";import { accountRunOptions, listAccountRuns } from "@/server/account-admin";-import { isOwnerRequest, sessionCookieOf } from "@/server/auth";+import { adminAccess, auditRead } from "@/server/admin-tokens";const NO_STORE = { "Cache-Control": "no-store" };/**- * Accounts' runs (owner only), newest first: `?account=<id>` (else every account's), `status` (finished, running,- * failed), `kind` (image, video, audio, model3d, text), `before=<createdAt>:<id>` (the `next` of the last page) and- * `limit` (≤ 100). Never the owner's own runs: those are in the Library.+ * Accounts' runs (owner only, or an admin token with runs:read), newest first: `?account=<id>` (else every account's),+ * `status` (finished, running, failed), `kind` (image, video, audio, model3d, text), `before=<createdAt>:<id>` (the+ * `next` of the last page) and `limit` (≤ 100). Never the owner's own runs: those are in the Library.*/export async function GET(request: Request) {await connection();- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "You can't open this." }, { status: 403, headers: NO_STORE });- const o = accountRunOptions(new URL(request.url).searchParams);+ const access = adminAccess(request, "runs:read", "You can't open this.");+ if (access instanceof Response) return access;+ const sp = new URL(request.url).searchParams;+ const o = accountRunOptions(sp);if ("error" in o) return Response.json({ error: o.error }, { status: 400, headers: NO_STORE });+ auditRead(access.actor, "runs.list", { ...(o.account && { account: o.account }), ...(sp.get("status") && { status: sp.get("status") }), ...(o.kind && { kind: o.kind }) });return Response.json(listAccountRuns(o), { headers: NO_STORE });}diff --git a/src/app/api/admin/outputs/[action]/route.ts b/src/app/api/admin/outputs/[action]/route.tsindex 0f626fe2..78c250c0 100644--- a/src/app/api/admin/outputs/[action]/route.ts+++ b/src/app/api/admin/outputs/[action]/route.ts@@ -1,22 +1,42 @@-import { isOwnerRequest, sessionCookieOf } from "@/server/auth";+import { adminAccess, audit, type Scope } from "@/server/admin-tokens";import { hideOutputs, removeOutputs, unhideOutputs, type Targets } from "@/server/takedown";const NO_STORE = { "Cache-Control": "no-store" };const list = (v: unknown): string[] | undefined => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, 500) : undefined);+/** Who may do each action: hiding is outputs:hide's (or outputs:moderate's); showing again and removing are outputs:moderate's. */+const SCOPE: Record<string, Scope[]> = { hide: ["outputs:hide", "outputs:moderate"], unhide: ["outputs:moderate"], remove: ["outputs:moderate"] };+/**- * Take results down (owner only): `hide` (served to no account and by no link; kept), `unhide`, `remove` (deleted;- * with `evidence: true`, moved to a locked folder instead). Body: `{ assetIds?, generationIds?, evidence? }`.+ * Take results down (owner only, or an admin token with the action's scope): `hide` (served to no account and by no+ * link; kept), `unhide`, `remove` (deleted; with `evidence: true`, moved to a locked folder instead). Body:+ * `{ assetIds?, generationIds?, evidence? }`.*/export async function POST(request: Request, ctx: RouteContext<"/api/admin/outputs/[action]">) {- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner can take results down" }, { status: 403, headers: NO_STORE });const { action } = await ctx.params;+ const access = adminAccess(request, SCOPE[action] ?? ["outputs:moderate"], "Only the studio's owner can take results down");+ if (access instanceof Response) return access;const body = (await request.json().catch(() => null)) as { assetIds?: unknown; generationIds?: unknown; evidence?: unknown } | null;const t: Targets = { assetIds: list(body?.assetIds), generationIds: list(body?.generationIds) };if (!t.assetIds?.length && !t.generationIds?.length) return Response.json({ error: "Name the results: assetIds or generationIds" }, { status: 400, headers: NO_STORE });- if (action === "hide") return Response.json({ hidden: hideOutputs(t) }, { headers: NO_STORE });- if (action === "unhide") return Response.json({ shown: unhideOutputs(t) }, { headers: NO_STORE });- if (action === "remove") return Response.json({ removed: removeOutputs(t, body?.evidence === true) }, { headers: NO_STORE });+ // The log keeps the counts and the first ids named (ids only: never a file's content or a prompt).+ const asked = { assets: t.assetIds?.length ?? 0, runs: t.generationIds?.length ?? 0, ids: [...(t.assetIds ?? []), ...(t.generationIds ?? [])].slice(0, 20).map((s) => s.slice(0, 64)) };+ if (action === "hide") {+ const hidden = hideOutputs(t);+ audit(access.actor, "outputs.hide", null, { ...asked, changed: hidden }, 200);+ return Response.json({ hidden }, { headers: NO_STORE });+ }+ if (action === "unhide") {+ const shown = unhideOutputs(t);+ audit(access.actor, "outputs.unhide", null, { ...asked, changed: shown }, 200);+ return Response.json({ shown }, { headers: NO_STORE });+ }+ if (action === "remove") {+ const evidence = body?.evidence === true;+ const removed = removeOutputs(t, evidence);+ audit(access.actor, "outputs.remove", null, { ...asked, changed: removed, evidence }, 200);+ return Response.json({ removed }, { headers: NO_STORE });+ }return Response.json({ error: "Unknown action" }, { status: 404, headers: NO_STORE });}diff --git a/src/app/api/admin/queue/route.ts b/src/app/api/admin/queue/route.tsindex a4c3b390..f31ec0f4 100644--- a/src/app/api/admin/queue/route.ts+++ b/src/app/api/admin/queue/route.ts@@ -1,10 +1,14 @@import { connection } from "next/server";-import { isOwnerRequest, sessionCookieOf } from "@/server/auth";+import { adminAccess } from "@/server/admin-tokens";import { queueView } from "@/server/computer/pool";-/** The line for workers (owner only): per lane, how many wait, the oldest, the estimate, and which workers have it warm. */+/**+ * The line for workers (owner only, or an admin token with queue:read): per lane, how many wait, the oldest, the+ * estimate, and which workers have it warm.+ */export async function GET(request: Request) {await connection();- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner sees the queue" }, { status: 403 });+ const access = adminAccess(request, "queue:read", "Only the studio's owner sees the queue");+ if (access instanceof Response) return access;return Response.json(queueView(), { headers: { "Cache-Control": "no-store" } });}diff --git a/src/app/api/admin/reports/route.ts b/src/app/api/admin/reports/route.tsnew file mode 100644index 00000000..8b633634--- /dev/null+++ b/src/app/api/admin/reports/route.ts@@ -0,0 +1,20 @@+import { connection } from "next/server";+import { adminAccess, auditRead } from "@/server/admin-tokens";+import { listReports } from "@/server/moderation";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * The reports kept here (no moderation service set), newest first, for an admin token with reports:read or the owner:+ * the same list as the owner's GET /api/reports. `limit` 1 to 500 (100 when not given).+ */+export async function GET(request: Request) {+ await connection();+ const access = adminAccess(request, "reports:read", "Only the studio's owner sees reports");+ if (access instanceof Response) return access;+ const asked = new URL(request.url).searchParams.get("limit");+ const limit = asked === null ? 100 : Math.trunc(Number(asked));+ if (!Number.isFinite(limit) || limit < 1 || limit > 500) return Response.json({ error: "limit is 1 to 500" }, { status: 400, headers: NO_STORE });+ auditRead(access.actor, "reports.list");+ return Response.json({ items: listReports(limit) }, { headers: NO_STORE });+}diff --git a/src/app/api/admin/tokens/route.ts b/src/app/api/admin/tokens/route.tsnew file mode 100644index 00000000..04a3132a--- /dev/null+++ b/src/app/api/admin/tokens/route.ts@@ -0,0 +1,38 @@+import { connection } from "next/server";+import { AdminTokenError, audit, createAdminToken, listAdminTokens, ownerBrowser, revokeAdminToken, SCOPE_LABELS, SCOPES } from "@/server/admin-tokens";++const NO_STORE = { "Cache-Control": "no-store" };++/** Admin tokens are managed from the owner's signed-in browser only: an API token or an admin token can't. */+const denied = () => Response.json({ error: "Manage admin tokens from the owner's signed-in browser" }, { status: 403, headers: NO_STORE });++/** The admin tokens (never their values) and the scopes one may have. */+export async function GET(request: Request) {+ await connection();+ if (!ownerBrowser(request)) return denied();+ return Response.json({ tokens: listAdminTokens(), scopes: SCOPES.map((id) => ({ id, label: SCOPE_LABELS[id] })) }, { headers: NO_STORE });+}++/** Make one: `{ name, scopes, expiresInDays? }`. The token's value is in this answer only. */+export async function POST(request: Request) {+ if (!ownerBrowser(request)) return denied();+ const body = (await request.json().catch(() => null)) as { name?: unknown; scopes?: unknown; expiresInDays?: unknown } | null;+ try {+ const made = createAdminToken({ name: body?.name, scopes: body?.scopes, expiresInDays: body?.expiresInDays });+ audit({ kind: "owner" }, "token.create", made.info.id, { name: made.info.name, scopes: made.info.scopes, expiresAt: made.info.expiresAt }, 201);+ return Response.json(made, { status: 201, headers: NO_STORE });+ } catch (e) {+ if (e instanceof AdminTokenError) return Response.json({ error: e.message }, { status: e.status, headers: NO_STORE });+ throw e;+ }+}++/** Revoke one (`?id=`): it stops working at once. */+export async function DELETE(request: Request) {+ if (!ownerBrowser(request)) return denied();+ const id = new URL(request.url).searchParams.get("id");+ if (!id || !/^[0-9a-f]{12}$/.test(id)) return Response.json({ error: "Which token?" }, { status: 400, headers: NO_STORE });+ const revoked = revokeAdminToken(id);+ if (revoked) audit({ kind: "owner" }, "token.revoke", id, { name: revoked.name }, 204);+ return new Response(null, { status: 204, headers: NO_STORE });+}diff --git a/src/app/api/admin/tokens/self/route.ts b/src/app/api/admin/tokens/self/route.tsnew file mode 100644index 00000000..4b53816e--- /dev/null+++ b/src/app/api/admin/tokens/self/route.ts@@ -0,0 +1,23 @@+import { connection } from "next/server";+import { listAdminTokens, tokenActor } from "@/server/admin-tokens";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * The admin token this request carries: its name, scopes and dates (never its value or hash), so a tool can offer only+ * what the token may do. Any valid admin token; nothing else.+ */+export async function GET(request: Request) {+ await connection();+ const t = tokenActor(request);+ if (t instanceof Response) return t;+ if (!t) {+ return Response.json(+ { error: "Send an admin token as Authorization: Bearer fuobe_adm_…", code: "token" },+ { status: 401, headers: { ...NO_STORE, "WWW-Authenticate": 'Bearer realm="fuobe"' } },+ );+ }+ const info = listAdminTokens().find((x) => x.id === t.id);+ if (!info) return Response.json({ error: "This admin token isn't valid.", code: "token" }, { status: 401, headers: NO_STORE });+ return Response.json({ id: info.id, name: info.name, prefix: info.prefix, scopes: info.scopes, expiresAt: info.expiresAt, createdAt: info.createdAt }, { headers: NO_STORE });+}diff --git a/src/app/api/admin/workers/[id]/route.ts b/src/app/api/admin/workers/[id]/route.tsindex c8803c1a..e037800d 100644--- a/src/app/api/admin/workers/[id]/route.ts+++ b/src/app/api/admin/workers/[id]/route.ts@@ -1,23 +1,35 @@-import { isOwnerRequest, sessionCookieOf } from "@/server/auth";+import { adminAccess, audit } from "@/server/admin-tokens";import { patchWorker, type WorkerPatch } from "@/server/computer/pool";const NO_STORE = { "Cache-Control": "no-store" };+/** The changes a worker takes: the log names which were sent, never their values (a rotate's token least of all). */+const KEYS = ["paused", "pauseNow", "drain", "autoResume", "hours", "allow", "claimAfterMs", "switchAfterMs", "rotate", "revoke"] as const;+/**- * Change a worker (owner only): `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs, rotate, revoke }`.+ * Change a worker (owner only, or an admin token with workers:write):+ * `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs, rotate, revoke }`.* Each reaches the worker at its next beat. Rotate answers with the new token, once; revoke stops the old token at once* and puts its job back in line.*/export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/workers/[id]">) {- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner manages workers" }, { status: 403, headers: NO_STORE });+ const access = adminAccess(request, "workers:write", "Only the studio's owner manages workers");+ if (access instanceof Response) return access;const { id } = await ctx.params;const body = (await request.json().catch(() => null)) as WorkerPatch | null;if (!body || typeof body !== "object") return Response.json({ error: "Say what to change" }, { status: 400, headers: NO_STORE });+ const action = body.revoke ? "worker.revoke" : body.rotate ? "worker.rotate" : "worker.change";+ const keys = KEYS.filter((k) => k in body);try {const r = patchWorker(id, body);- if (!r.view && !body.revoke) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });+ if (!r.view && !body.revoke) {+ audit(access.actor, action, id, { keys }, 404);+ return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });+ }+ audit(access.actor, action, id, { keys }, 200);return Response.json({ worker: r.view, ...(r.token && { token: r.token }) }, { headers: NO_STORE });} catch (e) {+ audit(access.actor, action, id, { keys }, 400);return Response.json({ error: (e as Error).message }, { status: 400, headers: NO_STORE });}}diff --git a/src/app/api/admin/workers/download/route.ts b/src/app/api/admin/workers/download/route.tsindex 34acb698..09d3efd8 100644--- a/src/app/api/admin/workers/download/route.ts+++ b/src/app/api/admin/workers/download/route.ts@@ -1,5 +1,5 @@import { connection } from "next/server";-import { isOwnerRequest, sessionCookieOf } from "@/server/auth";+import { adminAccess } from "@/server/admin-tokens";import fs from "node:fs";import path from "node:path";@@ -7,12 +7,12 @@ import path from "node:path";* Download the worker program as a zip, so its version always matches the server's (docs/gpu-workers.md).* The zip contains bin/ with the fuobe.mjs entry point, bin/lib/commands.mjs, bin/lib/worker/ and the* package.json that names the dependencies (`better-sqlite3` is not needed on the worker; the runner- * is bundled). Owner only.+ * is bundled). Owner only, or an admin token with workers:read.*/export async function GET(request: Request) {await connection();- if (!isOwnerRequest(request, sessionCookieOf(request)))- return Response.json({ error: "Only the studio's owner manages workers" }, { status: 403 });+ const access = adminAccess(request, "workers:read", "Only the studio's owner manages workers");+ if (access instanceof Response) return access;// Dynamic import so the zip helper is loaded only for this route.const { zipFiles } = await import("../../../../../../bin/lib/zip.mjs");diff --git a/src/app/api/admin/workers/route.ts b/src/app/api/admin/workers/route.tsindex b1e29420..04c4518f 100644--- a/src/app/api/admin/workers/route.ts+++ b/src/app/api/admin/workers/route.ts@@ -1,27 +1,35 @@import { connection } from "next/server";-import { isOwnerRequest, sessionCookieOf } from "@/server/auth";+import { adminAccess, audit } from "@/server/admin-tokens";import { addWorker, lanesCatalog, listWorkers } from "@/server/computer/pool";const NO_STORE = { "Cache-Control": "no-store" };+const DENIED = "Only the studio's owner manages workers";/**- * Settings → Workers (owner only, docs/gpu-workers.md): the shared GPUs with their state in words, and the lanes this- * studio's catalog has (to allow per worker). POST `{ name, pool? }` adds one: paused, with no hours and no lanes; its- * token is in this answer only.+ * Settings → Workers (owner only, or an admin token with workers:read / workers:write; docs/gpu-workers.md): the shared+ * GPUs with their state in words, and the lanes this studio's catalog has (to allow per worker). POST+ * `{ name, pool? }` adds one: paused, with no hours and no lanes; its token is in this answer only.*/export async function GET(request: Request) {await connection();- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner manages workers" }, { status: 403, headers: NO_STORE });+ const access = adminAccess(request, "workers:read", DENIED);+ if (access instanceof Response) return access;return Response.json({ workers: listWorkers(), lanes: lanesCatalog() }, { headers: NO_STORE });}export async function POST(request: Request) {- if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner manages workers" }, { status: 403, headers: NO_STORE });+ const access = adminAccess(request, "workers:write", DENIED);+ if (access instanceof Response) return access;const body = (await request.json().catch(() => null)) as { name?: unknown; pool?: unknown } | null;+ const name = typeof body?.name === "string" ? body.name.slice(0, 48) : "";+ const pool = typeof body?.pool === "string" ? body.pool : undefined;try {- const w = addWorker(typeof body?.name === "string" ? body.name.slice(0, 48) : "", typeof body?.pool === "string" ? body.pool : undefined);+ const w = addWorker(name, pool);+ // The worker's token is in this answer only: never in the log.+ audit(access.actor, "worker.add", w.id, { name: name.trim(), pool: pool ?? "pool" }, 201);return Response.json(w, { status: 201, headers: NO_STORE });} catch (e) {+ audit(access.actor, "worker.add", null, { name: name.trim().slice(0, 48) }, 400);return Response.json({ error: (e as Error).message }, { status: 400, headers: NO_STORE });}}diff --git a/src/app/api/auth/sessions/route.ts b/src/app/api/auth/sessions/route.tsindex 7348cf03..03eb0c95 100644--- a/src/app/api/auth/sessions/route.ts+++ b/src/app/api/auth/sessions/route.ts@@ -1,10 +1,12 @@import { z } from "zod";+import { revokeAllAdminTokens } from "@/server/admin-tokens";import { authEnabled, SESSION_COOKIE, sessionCookieOf, signOutEveryone, validSession } from "@/server/auth";/*** Settings → Security → Sign everyone out: a new session secret, so every signed-in browser (the owner's, this one* too, and every account's) has to sign in again. It works while FUOBE_PASSWORD is set. Only from the owner's- * signed-in browser (an API token can't do it). With { tokens: true }, every API token is revoked too.+ * signed-in browser (an API token can't do it). With { tokens: true }, every API token is revoked too, admin tokens+ * included.*/export async function POST(request: Request) {if (!authEnabled()) return Response.json({ error: "Set a password first. Without one, nobody signs in." }, { status: 400 });@@ -12,6 +14,7 @@ export async function POST(request: Request) {const parsed = z.object({ tokens: z.boolean().optional() }).safeParse(await request.json().catch(() => ({})));const tokensRevoked = parsed.success && parsed.data.tokens === true;signOutEveryone({ tokens: tokensRevoked });+ if (tokensRevoked) revokeAllAdminTokens();const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";return Response.json({ ok: true, tokensRevoked },diff --git a/src/components/admin-tokens.tsx b/src/components/admin-tokens.tsxnew file mode 100644index 00000000..192ee684--- /dev/null+++ b/src/components/admin-tokens.tsx@@ -0,0 +1,367 @@+"use client";++import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";+import { Copy, KeyRound, Loader2, Trash2 } from "lucide-react";+import { useId, useState } from "react";+import { toast } from "sonner";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { copyWithToast } from "@/lib/clipboard";+import { timeAgo } from "@/lib/format";+import { responseError, toastError } from "@/lib/refusals";++/** An admin token as GET /api/admin/tokens lists it (src/server/admin-tokens.ts): never its value. */+export interface AdminTokenRow {+ id: string;+ name: string;+ prefix: string;+ scopes: string[];+ createdAt: number;+ expiresAt: number | null;+ lastUsedAt: number | null;+}+interface AdminTokensAnswer {+ tokens: AdminTokenRow[];+ scopes: { id: string; label: string }[];+}+interface AuditRow {+ id: number;+ at: number;+ actor: "owner" | "token";+ token: { id: string; name: string } | null;+ action: string;+ target: string | null;+ status: number;+}++const READ_ONLY = ["accounts:read", "runs:read", "reports:read", "workers:read", "queue:read", "audit:read"];++const EXPIRY = [+ { value: "never", label: "Never expires" },+ { value: "30", label: "Expires in 30 days" },+ { value: "90", label: "Expires in 90 days" },+ { value: "365", label: "Expires in a year" },+];++/** What each logged action did, in a few words. */+const ACTION_WORDS: Record<string, string> = {+ "account.disable": "Switched an account off",+ "account.enable": "Switched an account on",+ "account.signout": "Signed an account out",+ "account.delete": "Deleted an account",+ "run.delete": "Deleted a run",+ "outputs.hide": "Hid results",+ "outputs.unhide": "Showed results again",+ "outputs.remove": "Removed results",+ "worker.add": "Added a worker",+ "worker.change": "Changed a worker",+ "worker.rotate": "Gave a worker a new token",+ "worker.revoke": "Revoked a worker",+ "token.create": "Made an admin token",+ "token.revoke": "Revoked an admin token",+ "accounts.list": "Read the accounts",+ "accounts.csv": "Downloaded the accounts",+ "account.read": "Read an account",+ "runs.list": "Read accounts' runs",+ "reports.list": "Read the reports",+ "audit.read": "Read this log",+ "file.view": "Opened a file",+ "scope.denied": "Refused: not allowed",+ "rate.limited": "Refused: too many requests",+};++export const ADMIN_TOKENS_KEY = ["admin-tokens"];++async function call<T>(url: string, method = "GET", body?: unknown): Promise<T> {+ const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });+ if (res.status === 204) return undefined as T;+ const j = (await res.json().catch(() => ({}))) as T & { error?: string };+ if (!res.ok) throw responseError(res, j.error ?? "Something went wrong. Please try again.");+ return j;+}++export const fetchAdminTokens = () => call<AdminTokensAnswer>("/api/admin/tokens");++/** Expired: it no longer works (it stays listed until revoked). */+export const isExpired = (t: Pick<AdminTokenRow, "expiresAt">, now = Date.now()) => t.expiresAt !== null && t.expiresAt <= now;++function expiryText(t: AdminTokenRow, now = Date.now()): string {+ if (t.expiresAt === null) return "never expires";+ if (t.expiresAt <= now) return "expired";+ const days = Math.ceil((t.expiresAt - now) / 86_400_000);+ return days <= 1 ? "expires within a day" : `expires in ${days} days`;+}++function CreateForm({ scopes, onMade, onCancel }: { scopes: AdminTokensAnswer["scopes"]; onMade: (token: string) => void; onCancel: () => void }) {+ const id = useId();+ const [name, setName] = useState("");+ const [picked, setPicked] = useState<Set<string>>(() => new Set(READ_ONLY));+ const [expiry, setExpiry] = useState("90");+ const [busy, setBusy] = useState(false);+ const all = scopes.map((s) => s.id);+ const same = (ids: string[]) => ids.length === picked.size && ids.every((s) => picked.has(s));+ const create = async () => {+ setBusy(true);+ try {+ const r = await call<{ token: string }>("/api/admin/tokens", "POST", { name: name.trim(), scopes: [...picked], expiresInDays: expiry === "never" ? null : Number(expiry) });+ setName("");+ onMade(r.token);+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(false);+ }+ };+ return (+ <div className="space-y-3 rounded-xl border p-3 sm:w-[36rem] sm:max-w-full">+ <div className="space-y-1.5">+ <Label htmlFor={`${id}-name`} className="text-[13px]">Name</Label>+ <Input id={`${id}-name`} placeholder="What it's for, e.g. “Admin panel”" maxLength={60} value={name} onChange={(e) => setName(e.target.value)} />+ </div>+ <div role="group" aria-labelledby={`${id}-scopes`} className="space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <p id={`${id}-scopes`} className="flex-1 text-[13px] font-medium">+ What it may do+ </p>+ <Button size="sm" variant={same(READ_ONLY) ? "secondary" : "ghost"} className="h-7" onClick={() => setPicked(new Set(READ_ONLY))}>+ Read only+ </Button>+ <Button size="sm" variant={same(all) ? "secondary" : "ghost"} className="h-7" onClick={() => setPicked(new Set(all))}>+ Full admin+ </Button>+ </div>+ <div className="grid grid-cols-1 gap-x-4 gap-y-2 sm:grid-cols-2">+ {scopes.map((s) => (+ <div key={s.id} className="flex items-start gap-2">+ <Checkbox+ id={`${id}-${s.id}`}+ className="mt-0.5"+ checked={picked.has(s.id)}+ onCheckedChange={(on) =>+ setPicked((p) => {+ const next = new Set(p);+ if (on) next.add(s.id);+ else next.delete(s.id);+ return next;+ })+ }+ />+ <Label htmlFor={`${id}-${s.id}`} className="block text-[13px] leading-snug font-normal">+ {s.label}+ <span className="block font-mono text-[11px] text-muted-foreground">{s.id}</span>+ </Label>+ </div>+ ))}+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <Select value={expiry} onValueChange={setExpiry}>+ <SelectTrigger aria-label="Expiry" className="h-9 w-full sm:w-52">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {EXPIRY.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button size="sm" className="h-9" disabled={busy || !name.trim() || picked.size === 0} onClick={() => void create()}>+ {busy && <Loader2 className="animate-spin" />}+ Create admin token+ </Button>+ <Button size="sm" variant="ghost" className="h-9" disabled={busy} onClick={onCancel}>+ Cancel+ </Button>+ </div>+ </div>+ );+}++function TokenItem({ t, onRevoke }: { t: AdminTokenRow; onRevoke: () => void }) {+ const expired = isExpired(t);+ return (+ <li className="flex items-start gap-3 px-3 py-2">+ <KeyRound className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-medium">+ {t.name}+ {expired && <span className="ml-2 text-[11px] font-normal text-muted-foreground">Expired</span>}+ </p>+ <p className="font-mono text-[11px] break-words text-muted-foreground">+ {t.prefix}… · created {timeAgo(t.createdAt)} · {t.lastUsedAt ? `used ${timeAgo(t.lastUsedAt)}` : "never used"} · {expiryText(t)}+ </p>+ <p className="mt-1 flex flex-wrap gap-1">+ {t.scopes.map((s) => (+ <span key={s} className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10.5px] text-muted-foreground">+ {s}+ </span>+ ))}+ </p>+ </div>+ <Button size="icon" variant="ghost" className="size-8 shrink-0 text-muted-foreground hover:text-destructive" aria-label={`Revoke ${t.name}`} onClick={onRevoke}>+ <Trash2 className="size-3.5" />+ </Button>+ </li>+ );+}++/** The admin log, newest first: what the admin API changed, and what tokens read. */+function AdminLog() {+ const q = useInfiniteQuery({+ queryKey: ["admin-audit"],+ initialPageParam: "",+ queryFn: ({ pageParam }) => call<{ items: AuditRow[]; next: string | null }>(`/api/admin/audit?limit=20${pageParam ? `&before=${pageParam}` : ""}`),+ getNextPageParam: (last) => last.next ?? undefined,+ });+ const rows = q.data?.pages.flatMap((p) => p.items) ?? [];+ return (+ <div className="space-y-1.5 sm:w-[36rem] sm:max-w-full">+ <h4 className="text-[12px] font-medium">Admin log</h4>+ {q.isPending ? (+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ ) : q.isError ? (+ <p className="text-[12px] text-muted-foreground">{q.error.message}</p>+ ) : rows.length === 0 ? (+ <p className="text-[12px] text-muted-foreground">Nothing yet. Changes made through the admin API, and what tokens read, show here.</p>+ ) : (+ <>+ <ul className="divide-y rounded-xl border text-[12px]">+ {rows.map((r) => (+ <li key={r.id} className="flex flex-wrap items-baseline gap-x-2 px-3 py-1.5">+ <span className="min-w-0 flex-1">+ {ACTION_WORDS[r.action] ?? r.action}+ {r.target && <span className="ml-1.5 font-mono text-[11px] break-all text-muted-foreground">{r.target}</span>}+ {r.status >= 400 && <span className="ml-1.5 text-[11px] text-destructive">{r.status}</span>}+ </span>+ <span className="text-[11px] text-muted-foreground">+ {r.actor === "token" ? (r.token?.name ?? "A token") : "You"} · {timeAgo(r.at)}+ </span>+ </li>+ ))}+ </ul>+ {q.hasNextPage && (+ <Button size="sm" variant="ghost" className="h-7" disabled={q.isFetchingNextPage} onClick={() => void q.fetchNextPage()}>+ {q.isFetchingNextPage && <Loader2 className="animate-spin" />}+ Show older+ </Button>+ )}+ </>+ )}+ </div>+ );+}++/**+ * Settings → Security → Admin tokens (the owner's signed-in browser only): tokens for your own tools to manage this+ * install through the admin API, each with only the rights ticked. The value is shown once.+ */+export function AdminTokens() {+ const qc = useQueryClient();+ const q = useQuery({ queryKey: ADMIN_TOKENS_KEY, queryFn: fetchAdminTokens });+ const [fresh, setFresh] = useState<string | null>(null);+ const [making, setMaking] = useState(false);+ const [revoking, setRevoking] = useState<AdminTokenRow | null>(null);+ const refresh = () => {+ void qc.invalidateQueries({ queryKey: ADMIN_TOKENS_KEY });+ void qc.invalidateQueries({ queryKey: ["admin-audit"] });+ };+ if (q.isError) return null;+ const revoke = async (t: AdminTokenRow) => {+ try {+ await call(`/api/admin/tokens?id=${encodeURIComponent(t.id)}`, "DELETE");+ toast.success(`Revoked ${t.name}`);+ } catch (e) {+ toastError(e);+ }+ refresh();+ };+ return (+ <div className="space-y-3">+ <div className="space-y-1 sm:w-[36rem] sm:max-w-full">+ <div className="flex items-center gap-3">+ <h3 className="flex-1 text-[13px] font-medium">Admin tokens</h3>+ {!making && q.data && (+ <Button size="sm" variant="secondary" className="h-8" onClick={() => setMaking(true)}>+ New admin token+ </Button>+ )}+ </div>+ <p className="text-[12px] text-muted-foreground">+ An admin token lets your own tools manage this install's accounts, runs and workers through the admin API. It only works on{" "}+ <code className="font-mono">/api/admin</code>, and only for the rights you tick.+ </p>+ </div>+ {fresh && (+ <div className="rounded-xl border border-primary/40 bg-brand-faint p-3 sm:w-[36rem] sm:max-w-full">+ <p className="text-[12px] font-medium">Copy this token now — it won't be shown again.</p>+ <div className="mt-2 flex items-center gap-2">+ <code aria-label="New admin token" className="min-w-0 flex-1 rounded-md bg-background px-2 py-1.5 font-mono text-[12px] break-all select-all">+ {fresh}+ </code>+ <Button size="sm" variant="secondary" className="shrink-0" onClick={() => void copyWithToast(fresh)}>+ <Copy /> Copy+ </Button>+ </div>+ </div>+ )}+ {making && q.data && (+ <CreateForm+ scopes={q.data.scopes}+ onCancel={() => setMaking(false)}+ onMade={(token) => {+ setFresh(token);+ setMaking(false);+ refresh();+ }}+ />+ )}+ {!q.data ? (+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ ) : (+ q.data.tokens.length > 0 && (+ <ul className="divide-y rounded-xl border sm:w-[36rem] sm:max-w-full">+ {q.data.tokens.map((t) => (+ <TokenItem key={t.id} t={t} onRevoke={() => setRevoking(t)} />+ ))}+ </ul>+ )+ )}+ {q.data && <AdminLog />}+ <AlertDialog open={!!revoking} onOpenChange={(open) => !open && setRevoking(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Revoke {revoking?.name}?</AlertDialogTitle>+ <AlertDialogDescription>It stops working at once. Tools that use it need a new token.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ if (revoking) void revoke(revoking);+ setRevoking(null);+ }}+ >+ Revoke+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex 886e916e..4f75d560 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -20,6 +20,7 @@ import { Checkbox } from "@/components/ui/checkbox";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";+import { ADMIN_TOKENS_KEY, AdminTokens, fetchAdminTokens, isExpired } from "@/components/admin-tokens";import { announceAuthChange, rememberViewer } from "@/lib/api";import { copyWithToast } from "@/lib/clipboard";import { timeAgo } from "@/lib/format";@@ -319,6 +320,9 @@ export function SecuritySettings() {const qc = useQueryClient();const router = useRouter();const status = useQuery({ queryKey: ["auth"], queryFn: () => call<AuthStatus>("/api/auth/password", "GET") });+ // Admin tokens are revoked with the API tokens when everyone is signed out: the count includes the live ones.+ const admin = useQuery({ queryKey: ADMIN_TOKENS_KEY, queryFn: fetchAdminTokens, enabled: status.isSuccess });+ const liveAdmin = admin.data?.tokens.filter((t) => !isExpired(t)).length ?? 0;const refresh = () => void qc.invalidateQueries({ queryKey: ["auth"] });if (status.isError) return <p className="text-[13px] text-muted-foreground">{status.error.message} Only the studio's owner sees these settings.</p>;if (!status.data) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;@@ -352,8 +356,9 @@ export function SecuritySettings() {)}{!s.fromEnv && <PasswordForm status={s} onDone={refresh} />}{s.enabled && <PublicSignup />}- {s.enabled && <SignOutEveryone tokens={s.tokens.length} />}+ {s.enabled && <SignOutEveryone tokens={s.tokens.length + liveAdmin} />}<Tokens status={s} onChange={refresh} />+ <AdminTokens /></div>);}diff --git a/src/proxy.ts b/src/proxy.tsindex 47ad7035..0b97b013 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -27,7 +27,7 @@ import {ownerOnly,ownGpuRun,} from "@/lib/guest-access";-import { authEnabled, crossSite, hasCloudKey, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";+import { ADMIN_BEARER, authEnabled, crossSite, hasCloudKey, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";import { fileAccount, generationAccount } from "@/server/account-library";import { hit } from "@/server/rate";import { recordExists } from "@/server/records";@@ -47,6 +47,16 @@ const OPEN = new Set(["/login", "/api/auth/login", "/api/auth/signup", "/api/autconst WORKER_BEARER = /^Bearer\s+fuobe_wkr_/i;const workerRoute = (pathname: string) => pathname.startsWith("/api/gpu/computer/");+/**+ * An admin token (src/server/admin-tokens.ts) works only on the admin API; the route checks the token and its scope+ * itself. Making, listing and revoking admin tokens is the owner's signed-in browser's only: /api/admin/tokens/self is+ * how a token reads its own name and scopes. Anywhere else it is refused, whatever else the request carries.+ */+const adminRoute = (pathname: string) => {+ const p = safeDecode(pathname);+ return p.startsWith("/api/admin/") && (!/^\/api\/admin\/tokens(\/|$)/i.test(p) || p === "/api/admin/tokens/self");+};+const APP_IDS = new Set(APPS.map((a) => a.id));/**@@ -330,6 +340,11 @@ export function proxy(request: NextRequest) {return NextResponse.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });}const { pathname, search } = request.nextUrl;+ if (ADMIN_BEARER.test(request.headers.get("authorization") ?? "")) {+ return adminRoute(pathname)+ ? NextResponse.next()+ : NextResponse.json({ error: "An admin token only works on the admin API." }, { status: 403, headers: { "Cache-Control": "no-store" } });+ }// Share links are read-only and public, password or not: exactly a share's page and its files.const read = request.method === "GET" || request.method === "HEAD";const share = read && shareRoute(pathname);diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.tsnew file mode 100644index 00000000..cdc5ca62--- /dev/null+++ b/src/server/admin-tokens.ts@@ -0,0 +1,401 @@+import "server-only";+import crypto from "node:crypto";+import { authEnabled, hasAdminBearer, isOwnerRequest, LoginGuard, sessionCookieOf, validSession } from "./auth";+import { db } from "./db";+import { hit, peek } from "./rate";++/**+ * Admin tokens: an install can be managed from your own tools with an admin API token (docs/admin-api.md).+ *+ * A token (`fuobe_adm_` + 43 characters) works only on /api/admin (src/proxy.ts refuses it everywhere else), and only for+ * the scopes the owner ticked when making it in Settings → Security. It is never the owner: it can't sign in, open a+ * page, change settings or make tokens. A request that carries one is judged by the token alone (a session cookie beside+ * it is ignored). Only its SHA-256 is stored; the token itself is in the answer that made it and nowhere else.+ *+ * Every change made through the admin API (by the owner or a token) is written to admin_audit, and so are a token's+ * reads of people's data (coalesced), each file it views, and the refusals of a valid token. Never a token, a password,+ * a prompt or an IP address.+ */++export const SCOPES = [+ "accounts:read",+ "accounts:write",+ "accounts:delete",+ "runs:read",+ "runs:delete",+ "outputs:view",+ "outputs:hide",+ "outputs:moderate",+ "reports:read",+ "workers:read",+ "workers:write",+ "queue:read",+ "audit:read",+] as const;++export type Scope = (typeof SCOPES)[number];++/** What each scope lets a token do, in the words Settings shows. */+export const SCOPE_LABELS: Record<Scope, string> = {+ "accounts:read": "See accounts",+ "accounts:write": "Switch accounts off and on, sign them out",+ "accounts:delete": "Delete accounts",+ "runs:read": "See accounts' runs",+ "runs:delete": "Delete accounts' runs",+ "outputs:view": "Open accounts' files",+ "outputs:hide": "Hide results",+ "outputs:moderate": "Hide, show again and remove results",+ "reports:read": "See reports",+ "workers:read": "See workers",+ "workers:write": "Add and change workers",+ "queue:read": "See the queue",+ "audit:read": "See the admin log",+};++/** The Settings preset that only reads. */+export const READ_ONLY_SCOPES: Scope[] = ["accounts:read", "runs:read", "reports:read", "workers:read", "queue:read", "audit:read"];++export const ADMIN_TOKEN_PREFIX = "fuobe_adm_";+const SHAPE = /^fuobe_adm_[A-Za-z0-9_-]{43}$/;+/** Live (not revoked, not expired) tokens an install may hold at once. */+export const MAX_LIVE_TOKENS = 20;+const NAME_MAX = 60;++/** Requests a token may send a minute, and how many of them may be changes. */+export const TOKEN_PER_MINUTE = 120;+export const TOKEN_CHANGES_PER_MINUTE = 30;+/** Wrong tokens a client may send a minute (or every client together, when they can't be told apart). */+const MISSES_PER_MINUTE = 10;+const SHARED_MISSES_PER_MINUTE = 60;++const MINUTE = 60_000;+const DAY = 86_400_000;+const AUDIT_KEEP_MS = 365 * DAY;++export interface AdminTokenInfo {+ id: string;+ name: string;+ /** The first 14 characters ("fuobe_adm_Xy3k"), shown with an ellipsis. */+ prefix: string;+ scopes: Scope[];+ createdAt: number;+ expiresAt: number | null;+ lastUsedAt: number | null;+ revokedAt: number | null;+}++export type Actor = { kind: "owner" } | { kind: "token"; id: string; name: string; scopes: Scope[] };++export class AdminTokenError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ }+}++interface TokenRow {+ id: string;+ name: string;+ hash: string;+ prefix: string;+ scopes_json: string;+ created_at: number;+ expires_at: number | null;+ last_used_at: number | null;+ revoked_at: number | null;+}++const NO_STORE = { "Cache-Control": "no-store" };++const sha256 = (s: string) => crypto.createHash("sha256").update(s).digest("hex");++const isScope = (s: unknown): s is Scope => typeof s === "string" && (SCOPES as readonly string[]).includes(s);++function scopesOf(json: string): Scope[] {+ try {+ const v = JSON.parse(json) as unknown;+ return Array.isArray(v) ? v.filter(isScope) : [];+ } catch {+ return [];+ }+}++const info = (r: TokenRow): AdminTokenInfo => ({+ id: r.id,+ name: r.name,+ prefix: r.prefix,+ scopes: scopesOf(r.scopes_json),+ createdAt: r.created_at,+ expiresAt: r.expires_at,+ lastUsedAt: r.last_used_at,+ revokedAt: r.revoked_at,+});++const LIVE_SQL = "revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)";++const liveRows = (now = Date.now()) => db().prepare(`SELECT * FROM admin_tokens WHERE ${LIVE_SQL}`).all(now) as TokenRow[];++/** The tokens Settings lists: every one not revoked (an expired one too, marked so), newest first. */+export function listAdminTokens(): AdminTokenInfo[] {+ return (db().prepare("SELECT * FROM admin_tokens WHERE revoked_at IS NULL ORDER BY created_at DESC").all() as TokenRow[]).map(info);+}++/** Live tokens: not revoked and not expired. */+export const liveAdminTokenCount = (now = Date.now()) => (db().prepare(`SELECT COUNT(*) AS n FROM admin_tokens WHERE ${LIVE_SQL}`).get(now) as { n: number }).n;++/** Make a token. Its value is in this answer only; the database keeps its SHA-256. */+export function createAdminToken(input: { name: unknown; scopes: unknown; expiresInDays?: unknown }, now = Date.now()): { token: string; info: AdminTokenInfo } {+ const name = typeof input.name === "string" ? input.name.trim() : "";+ if (!name || name.length > NAME_MAX) throw new AdminTokenError(`Name the token (up to ${NAME_MAX} characters)`, 400);+ if (!Array.isArray(input.scopes) || !input.scopes.length || !input.scopes.every(isScope)) throw new AdminTokenError("Pick what the token may do", 400);+ const scopes = [...new Set(input.scopes as Scope[])].sort();+ const days = input.expiresInDays ?? null;+ if (days !== null && !(typeof days === "number" && Number.isInteger(days) && days >= 1 && days <= 365)) throw new AdminTokenError("An expiry is 1 to 365 days, or never", 400);+ const live = liveRows(now);+ if (live.length >= MAX_LIVE_TOKENS) throw new AdminTokenError(`An install keeps at most ${MAX_LIVE_TOKENS} admin tokens. Revoke one first.`, 409);+ if (live.some((r) => r.name.toLowerCase() === name.toLowerCase())) throw new AdminTokenError("An admin token with that name exists", 409);+ const token = `${ADMIN_TOKEN_PREFIX}${crypto.randomBytes(32).toString("base64url")}`;+ const row: TokenRow = {+ id: crypto.randomBytes(6).toString("hex"),+ name,+ hash: sha256(token),+ prefix: token.slice(0, 14),+ scopes_json: JSON.stringify(scopes),+ created_at: now,+ expires_at: days === null ? null : now + days * DAY,+ last_used_at: null,+ revoked_at: null,+ };+ db()+ .prepare("INSERT INTO admin_tokens (id, name, hash, prefix, scopes_json, created_at, expires_at) VALUES (@id, @name, @hash, @prefix, @scopes_json, @created_at, @expires_at)")+ .run(row);+ return { token, info: info(row) };+}++/** Revoke a token: it stops working at once. Its row stays, so the log can still name it. Null when there is no such token, or it was revoked already. */+export function revokeAdminToken(id: string, now = Date.now()): AdminTokenInfo | null {+ const row = db().prepare("SELECT * FROM admin_tokens WHERE id = ? AND revoked_at IS NULL").get(id) as TokenRow | undefined;+ if (!row) return null;+ db().prepare("UPDATE admin_tokens SET revoked_at = ? WHERE id = ?").run(now, id);+ return info({ ...row, revoked_at: now });+}++/** Settings → Security → Sign everyone out, with every API token revoked: admin tokens go too. How many were revoked. */+export function revokeAllAdminTokens(now = Date.now()): number {+ return db().prepare("UPDATE admin_tokens SET revoked_at = ? WHERE revoked_at IS NULL").run(now).changes;+}++// ---------------------------------------------------------------------------+// Checking a request++declare global {+ var __fuobeAdminTouched: Map<string, number> | undefined;+ var __fuobeAdminAuditSeen: Map<string, number> | undefined;+ var __fuobeAdminAuditPruned: number | undefined;+}++/**+ * The live token this value is, or null. Its SHA-256 is compared with every live token's in constant time (no lookup+ * by hash, no early exit), so the answer's timing says nothing about how close a guess came.+ */+function findToken(value: string, now: number): TokenRow | null {+ const h = Buffer.from(sha256(value), "hex");+ let found: TokenRow | null = null;+ for (const row of liveRows(now)) {+ const other = Buffer.from(row.hash, "hex");+ if (other.length === h.length && crypto.timingSafeEqual(other, h) && !found) found = row;+ }+ return SHAPE.test(value) ? found : null;+}++const json = (body: Record<string, unknown>, status: number, headers: Record<string, string> = {}) => Response.json(body, { status, headers: { ...NO_STORE, ...headers } });++const invalid = () => json({ error: "This admin token isn't valid.", code: "token" }, 401, { "WWW-Authenticate": 'Bearer realm="fuobe", error="invalid_token"' });+const tooMany = (seconds: number) => json({ error: "Too many requests. Try again in a minute.", code: "rate" }, 429, { "Retry-After": String(seconds) });++/** Write a token's last use at most once a minute (not a write per request). */+function touch(id: string, now: number): void {+ const touched = (globalThis.__fuobeAdminTouched ??= new Map());+ if (now - (touched.get(id) ?? 0) < MINUTE) return;+ touched.set(id, now);+ db().prepare("UPDATE admin_tokens SET last_used_at = ? WHERE id = ?").run(now, id);+}++const isChange = (method: string) => !["GET", "HEAD", "OPTIONS"].includes(method.toUpperCase());++/**+ * The admin token this request carries, checked: its actor, or the answer to send (401 unknown, revoked or expired;+ * 429 past a limit). Null when the request carries no admin token. Misses count against the client's own budget,+ * checked only after the token was found wrong, so someone else's misses never slow down a valid token.+ */+export function tokenActor(request: Request, now = Date.now()): Extract<Actor, { kind: "token" }> | Response | null {+ if (!hasAdminBearer(request)) return null;+ const value = (request.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();+ const row = findToken(value, now);+ if (!row) {+ const client = LoginGuard.clientKey(request.headers);+ const shared = client === LoginGuard.DIRECT;+ const r = hit(`admin-miss:${client}`, shared ? SHARED_MISSES_PER_MINUTE : MISSES_PER_MINUTE, MINUTE, now);+ return r.ok ? invalid() : tooMany(r.retryAfterS);+ }+ const actor = { kind: "token" as const, id: row.id, name: row.name, scopes: scopesOf(row.scopes_json) };+ // Changes have their own, smaller budget inside the whole one.+ const change = isChange(request.method);+ const changes = change ? peek(`admin-change:${row.id}`, TOKEN_CHANGES_PER_MINUTE, MINUTE, now) : { ok: true, retryAfterS: 0 };+ const all = changes.ok ? hit(`admin-token:${row.id}`, TOKEN_PER_MINUTE, MINUTE, now) : changes;+ if (!all.ok) {+ auditOnce(`rate:${row.id}`, MINUTE, actor, "rate.limited", null, { change }, 429, now);+ return tooMany(all.retryAfterS);+ }+ if (change) hit(`admin-change:${row.id}`, TOKEN_CHANGES_PER_MINUTE, MINUTE, now);+ touch(row.id, now);+ return actor;+}++/**+ * Who may use an admin route: a token with one of `scopes`, or (with no admin token on the request) the owner, as+ * before. `denied` is the route's own answer for anyone else. Returns the actor, or the answer to send.+ */+export function adminAccess(request: Request, scopes: Scope | Scope[], denied: string): { actor: Actor } | Response {+ const t = tokenActor(request);+ if (t instanceof Response) return t;+ if (t) {+ const wanted = Array.isArray(scopes) ? scopes : [scopes];+ if (!wanted.some((s) => t.scopes.includes(s))) {+ auditOnce(`scope:${t.id}:${wanted[0]}:${new URL(request.url).pathname}:${request.method}`, MINUTE, t, "scope.denied", null, { scope: wanted[0], method: request.method }, 403);+ return json({ error: "This admin token can't do that.", code: "scope", scope: wanted[0] }, 403);+ }+ return { actor: t };+ }+ if (isOwnerRequest(request, sessionCookieOf(request))) return { actor: { kind: "owner" } };+ return json({ error: denied }, 403);+}++/**+ * The owner's signed-in browser (or anyone while no password is set): the only one who may make, list or revoke admin+ * tokens. An owner API token or an admin token can't.+ */+export function ownerBrowser(request: Request): boolean {+ if (hasAdminBearer(request)) return false;+ return !authEnabled() || validSession(sessionCookieOf(request));+}++// ---------------------------------------------------------------------------+// The log++export interface AuditRow {+ id: number;+ at: number;+ actor: "owner" | "token";+ token: { id: string; name: string } | null;+ action: string;+ target: string | null;+ detail: Record<string, unknown> | null;+ status: number;+}++const DETAIL_MAX = 2000;++function prune(now: number): void {+ if (now - (globalThis.__fuobeAdminAuditPruned ?? 0) < DAY) return;+ globalThis.__fuobeAdminAuditPruned = now;+ db().prepare("DELETE FROM admin_audit WHERE at < ?").run(now - AUDIT_KEEP_MS);+}++/** Write one row: who (the owner, or a token by id and its name at the time), what, on what, and the status answered. */+export function audit(actor: Actor, action: string, target: string | null, detail: Record<string, unknown> | null, status: number, now = Date.now()): void {+ let d = detail ? JSON.stringify(detail) : null;+ if (d && d.length > DETAIL_MAX) d = JSON.stringify({ truncated: true });+ try {+ db()+ .prepare("INSERT INTO admin_audit (at, actor, token_id, token_name, action, target, detail_json, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")+ .run(now, actor.kind, actor.kind === "token" ? actor.id : null, actor.kind === "token" ? actor.name : null, action, target ? target.slice(0, 300) : null, d, status);+ prune(now);+ } catch (e) {+ console.warn(`[fuobe] Couldn't write the admin log: ${(e as Error).message}`);+ }+}++/** One row per key in `windowMs`: a token's repeated reads or refusals don't fill the log. */+function auditOnce(key: string, windowMs: number, actor: Actor, action: string, target: string | null, detail: Record<string, unknown> | null, status: number, now = Date.now()): void {+ const seen = (globalThis.__fuobeAdminAuditSeen ??= new Map());+ if (now - (seen.get(key) ?? 0) < windowMs) return;+ seen.set(key, now);+ if (seen.size > 5000) for (const [k, t] of seen) if (now - t > DAY) seen.delete(k);+ audit(actor, action, target, detail, status, now);+}++/** A token's read of people's data: one row per token and action every 10 minutes. The owner's own reads aren't logged. */+export function auditRead(actor: Actor, action: string, detail: Record<string, unknown> | null = null, target: string | null = null): void {+ if (actor.kind !== "token") return;+ auditOnce(`read:${actor.id}:${action}:${target ?? ""}`, 10 * MINUTE, actor, action, target, detail, 200);+}++/** A token opened a stored file: one row per token and file every hour. */+export function auditFileView(actor: Actor, path: string, account: string): void {+ if (actor.kind !== "token") return;+ auditOnce(`file:${actor.id}:${path}`, 60 * MINUTE, actor, "file.view", path, { account }, 200);+}++export interface AuditQuery {+ before?: number;+ limit: number;+ actor?: "owner" | "token";+ token?: string;+ action?: string;+}++/** GET /api/admin/audit's query, or the reason it's wrong. */+export function auditQueryFrom(sp: URLSearchParams): AuditQuery | { error: string } {+ const before = sp.get("before");+ if (before !== null && !/^\d{1,15}$/.test(before)) return { error: "before is a row id" };+ const limitRaw = sp.get("limit");+ const limit = limitRaw === null ? 50 : Math.trunc(Number(limitRaw));+ if (!Number.isFinite(limit) || limit < 1 || limit > 200) return { error: "limit is 1 to 200" };+ const actor = sp.get("actor");+ if (actor !== null && actor !== "owner" && actor !== "token") return { error: "actor is owner or token" };+ const token = sp.get("token");+ if (token !== null && !/^[0-9a-f]{12}$/.test(token)) return { error: "token is a token id" };+ const action = sp.get("action");+ if (action !== null && !/^[a-z.]{1,40}$/.test(action)) return { error: "Unknown action" };+ return { limit, ...(before !== null && { before: Number(before) }), ...(actor && { actor }), ...(token && { token }), ...(action && { action }) };+}++/** The log, newest first; `next` is the last row's id (pass it as `before`), null on the last page. */+export function listAudit(q: AuditQuery): { items: AuditRow[]; next: string | null } {+ const filters: [string, string | number | undefined][] = [+ ["id < ?", q.before],+ ["actor = ?", q.actor],+ ["token_id = ?", q.token],+ ["action = ?", q.action],+ ];+ const used = filters.filter((f): f is [string, string | number] => f[1] !== undefined);+ const where = used.map((f) => f[0]);+ const args = used.map((f) => f[1]);+ const rows = db()+ .prepare(`SELECT * FROM admin_audit ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`)+ .all(...args, q.limit) as { id: number; at: number; actor: string; token_id: string | null; token_name: string | null; action: string; target: string | null; detail_json: string | null; status: number }[];+ const items = rows.map((r) => ({+ id: r.id,+ at: r.at,+ actor: r.actor === "token" ? ("token" as const) : ("owner" as const),+ token: r.token_id ? { id: r.token_id, name: r.token_name ?? "" } : null,+ action: r.action,+ target: r.target,+ detail: parseDetail(r.detail_json),+ status: r.status,+ }));+ return { items, next: items.length === q.limit ? String(items[items.length - 1].id) : null };+}++function parseDetail(s: string | null): Record<string, unknown> | null {+ if (!s) return null;+ try {+ const v = JSON.parse(s) as unknown;+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;+ } catch {+ return null;+ }+}diff --git a/src/server/auth.ts b/src/server/auth.tsindex 23e17ddd..9f2d8ae7 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -73,6 +73,8 @@ export interface Account {lastLoginAt?: number;/** Switched off by the owner (Settings → Accounts): signed out, and can't log in. */disabled?: boolean;+ /** Signed out everywhere by the owner at this time (the admin API): its sign-ins from before then were ended. */+ sessionsAfter?: number;gpu?: AccountGpu;/** Its own keys ("Your keys"), sealed: src/server/account-keys.ts opens them. */keys?: Partial<Record<CloudProvider, StoredKey>>;@@ -281,6 +283,8 @@ export function sessionViewer(value: string | undefined): Viewer | null {// Signed out with Sign out: a copy of the cookie (another tab's, a stolen one) is refused too.if (d.signedOut?.length && d.signedOut.some((s) => s.hash === cookieHash(value))) return null;if (!account) return { kind: "owner" };+ // Signed out everywhere (signOutAccount): a cookie issued at or before then is refused.+ if (account.sessionsAfter && Number(exp) - SESSION_MS <= account.sessionsAfter) return null;return account.disabled ? null : { kind: "account", account };}@@ -440,6 +444,14 @@ export function setAccountDisabled(id: string, disabled: boolean): void {write({ ...d, accounts: d.accounts.map((a) => (a.id === id ? { ...a, disabled } : a)) });}+/** End every sign-in of an account at once, without switching it off: it can log in again. */+export function signOutAccount(id: string): void {+ const d = read();+ if (!d.accounts?.some((a) => a.id === id)) throw new AccountError("No such account", 404);+ const now = Date.now();+ write({ ...d, accounts: d.accounts.map((a) => (a.id === id ? { ...a, sessionsAfter: now } : a)) });+}+/** Delete an account (its sessions stop working at once). */export function deleteAccount(id: string): void {const d = read();@@ -539,7 +551,12 @@ export function sessionCookieOf(request: Request): string | undefined {return sessionCookieFrom(request.headers.get("cookie"));}+/** An admin token (src/server/admin-tokens.ts): only the admin API takes it, and it is never the owner or an account. */+export const ADMIN_BEARER = /^Bearer\s+fuobe_adm_/i;+export const hasAdminBearer = (request: Request) => ADMIN_BEARER.test(request.headers.get("authorization") ?? "");+export function requestViewer(request: Request, cookie = sessionCookieOf(request)): RequestViewer {+ if (hasAdminBearer(request)) return { kind: "guest" };if (!authEnabled() || validToken(request.headers.get("authorization"))) return { kind: "owner" };const v = sessionViewer(cookie);if (v?.kind === "owner") return v;@@ -549,7 +566,7 @@ export function requestViewer(request: Request, cookie = sessionCookieOf(request/** The account behind this request's session, while public sign-up is on for its address (null: the owner, a guest, or off). */export function requestAccount(request: Request, cookie = sessionCookieOf(request)): Account | null {- if (validToken(request.headers.get("authorization"))) return null;+ if (hasAdminBearer(request) || validToken(request.headers.get("authorization"))) return null;const v = sessionViewer(cookie);return v?.kind === "account" && publicSignup(request.headers.get("host")) ? v.account : null;}@@ -764,7 +781,10 @@ export class LoginGuard {const tokenHash = (t: string) => crypto.createHash("sha256").update(t).digest("hex");export function createToken(name: string): { token: string; info: Omit<ApiToken, "hash"> } {- const token = `fuobe_${crypto.randomBytes(24).toString("base64url")}`;+ // A random part that starts like a worker's or an admin token's would never work as the owner's (validToken): roll again.+ let token: string;+ do token = `fuobe_${crypto.randomBytes(24).toString("base64url")}`;+ while (/^fuobe_(wkr|adm)_/i.test(token));const t: ApiToken = { id: crypto.randomBytes(6).toString("hex"), name: name.trim() || "API token", hash: tokenHash(token), prefix: token.slice(0, 12), createdAt: Date.now() };const d = withSecret(read());write({ ...d, tokens: [...d.tokens, t] });diff --git a/src/server/db.ts b/src/server/db.tsindex 41614237..e1bea8a5 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -759,6 +759,35 @@ export const HOOK_TABLES = `CREATE TABLE IF NOT EXISTS billing_outbox (done_at INTEGER);`;+/**+ * Admin tokens (src/server/admin-tokens.ts): scoped tokens for the admin API, stored by their SHA-256 only, and the log+ * of what the admin API changed and which token read what. A revoked token's row stays, so the log can name it. Made here+ * rather than as numbered migrations (other branches add those at the same time). Safe to run on every start.+ */+export const ADMIN_TABLES = `CREATE TABLE IF NOT EXISTS admin_tokens (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ hash TEXT NOT NULL UNIQUE,+ prefix TEXT NOT NULL,+ scopes_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ expires_at INTEGER,+ last_used_at INTEGER,+ revoked_at INTEGER+ );+ CREATE TABLE IF NOT EXISTS admin_audit (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ at INTEGER NOT NULL,+ actor TEXT NOT NULL,+ token_id TEXT,+ token_name TEXT,+ action TEXT NOT NULL,+ target TEXT,+ detail_json TEXT,+ status INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS admin_audit_at ON admin_audit(at);`;+/** Columns the optional services added to existing tables: [table, column, type]. */const HOOK_COLUMNS: [string, string, string][] = [// 1: never served to the account (its output check hasn't said "show").@@ -847,6 +876,8 @@ function open(): Database.Database {const has = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column);if (!has) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);}+ // Admin tokens and the admin API's log.+ db.exec(ADMIN_TABLES);// A billing hold's rows are found through this index (only rows that have one are in it).try {db.exec("CREATE INDEX IF NOT EXISTS generations_hold ON generations(json_extract(request_json, '$.hold')) WHERE json_extract(request_json, '$.hold') IS NOT NULL");diff --git a/src/server/direct-gate.ts b/src/server/direct-gate.tsindex 487c4630..4a919311 100644--- a/src/server/direct-gate.ts+++ b/src/server/direct-gate.ts@@ -2,7 +2,7 @@ import "server-only";import { NextRequest } from "next/server";import { GUEST_HEADER, GUEST_RUN_MESSAGE } from "@/lib/guest-access";import { proxy } from "@/proxy";-import { authEnabled, crossSite, hostAllowed, publicSignup, requestViewer, type Account } from "./auth";+import { authEnabled, crossSite, hasAdminBearer, hostAllowed, publicSignup, requestViewer, type Account } from "./auth";/*** The proxy's checks, for a route the proxy doesn't run on (src/proxy.ts config.matcher leaves /api/uploads out, so a@@ -77,6 +77,8 @@ export function gateDirect(request: Request): { kind: "owner" } | { kind: "accouif (crossSite(request, url.host)) {return Response.json({ error: "Blocked a request from another website. Use Fuobe from its own address (or add it to FUOBE_ALLOWED_ORIGINS)." }, { status: 403 });}+ // An admin token works on the admin API only (as the proxy says).+ if (hasAdminBearer(request)) return Response.json({ error: "An admin token only works on the admin API." }, { status: 403, headers: { "Cache-Control": "no-store" } });const viewer = requestViewer(request);if (viewer.kind === "owner" || viewer.kind === "account") return viewer;if (publicSignup(host)) return Response.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: { [GUEST_HEADER]: "1", "Cache-Control": "no-store" } });diff --git a/src/server/generations.ts b/src/server/generations.tsindex 3d6514f7..4525a220 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -418,6 +418,8 @@ export const ASSET_FREE: Record<string, string> = {"generations.external_meta_json": "the provider's job handles","billing_outbox.payload_json": "reports for the billing service: hold and run ids, counts and words, never a file","reports_inbox.target_json": "what a report is about: a run, asset or share id, never a file",+ "admin_tokens.scopes_json": "an admin token's scope names",+ "admin_audit.detail_json": "small facts about an admin action: counts, ids and names, never a file's URL","shorts_sessions.range_json": "start and end times","shorts_sessions.settings_json": "ratio, language, model and resolution","shorts_sessions.segments_json": "generation ids of each take",diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.tsnew file mode 100644index 00000000..c527fbca--- /dev/null+++ b/tests/admin-tokens.test.ts@@ -0,0 +1,455 @@+import crypto from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { TINY_PNG } from "./helpers/fake-comfy-runner";++// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-admin-tokens-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+process.env.COMFYUI_URL = "http://127.0.0.1:9";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_TRUST_PROXY;+const auth = await import("@/server/auth");+const admin = await import("@/server/admin-tokens");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { saveFile } = await import("@/server/storage");+const { proxy } = await import("@/proxy");+const routes = {+ accounts: await import("@/app/api/admin/accounts/route"),+ account: await import("@/app/api/admin/accounts/[id]/route"),+ runs: await import("@/app/api/admin/generations/route"),+ run: await import("@/app/api/admin/generations/[id]/route"),+ outputs: await import("@/app/api/admin/outputs/[action]/route"),+ queue: await import("@/app/api/admin/queue/route"),+ workers: await import("@/app/api/admin/workers/route"),+ worker: await import("@/app/api/admin/workers/[id]/route"),+ download: await import("@/app/api/admin/workers/download/route"),+ reports: await import("@/app/api/admin/reports/route"),+ audit: await import("@/app/api/admin/audit/route"),+ files: await import("@/app/api/admin/files/[...path]/route"),+ tokens: await import("@/app/api/admin/tokens/route"),+ self: await import("@/app/api/admin/tokens/self/route"),+ sessions: await import("@/app/api/auth/sessions/route"),+};+afterAll(() => {+ delete process.env.FUOBE_PUBLIC_SIGNUP;+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++type Scope = (typeof admin.SCOPES)[number];++const req = (url: string, o: { method?: string; token?: string; cookie?: string; body?: unknown; headers?: Record<string, string> } = {}) =>+ new NextRequest(`http://localhost:3000${url}`, {+ method: o.method ?? "GET",+ headers: {+ ...(o.token && { authorization: `Bearer ${o.token}` }),+ ...(o.cookie && { cookie: `${auth.SESSION_COOKIE}=${o.cookie}` }),+ ...(o.body !== undefined && { "content-type": "application/json" }),+ ...o.headers,+ },+ ...(o.body !== undefined && { body: JSON.stringify(o.body) }),+ });++const ctx = <P>(params: P) => ({ params: Promise.resolve(params) }) as never;++let n = 0;+const make = (scopes: Scope[], o: { expiresInDays?: number | null; now?: number } = {}) =>+ admin.createAdminToken({ name: `token ${++n}`, scopes, expiresInDays: o.expiresInDays ?? null }, o.now);++const auditRows = () => db().prepare("SELECT * FROM admin_audit ORDER BY id").all() as { actor: string; token_id: string | null; token_name: string | null; action: string; target: string | null; detail_json: string | null; status: number }[];++let ownerCookie = "";+beforeAll(() => {+ auth.setPassword("install password");+ ownerCookie = auth.createSession().value;+});+beforeEach(() => resetRates());++describe("admin tokens: making, storing, revoking", () => {+ it("makes a fuobe_adm_ token shown once and keeps only its SHA-256", () => {+ const { token, info } = make(["queue:read", "accounts:read"]);+ expect(token).toMatch(/^fuobe_adm_[A-Za-z0-9_-]{43}$/);+ expect(info.prefix).toBe(token.slice(0, 14));+ expect(info.scopes).toEqual(["accounts:read", "queue:read"]);+ const row = db().prepare("SELECT * FROM admin_tokens WHERE id = ?").get(info.id) as Record<string, unknown>;+ expect(row.hash).toBe(crypto.createHash("sha256").update(token).digest("hex"));+ expect(JSON.stringify(db().prepare("SELECT * FROM admin_tokens").all())).not.toContain(token);+ expect(JSON.stringify(admin.listAdminTokens())).not.toContain(row.hash as string);+ });++ it("refuses a bad name, unknown scopes, a wrong expiry and a 21st live token", () => {+ expect(() => admin.createAdminToken({ name: " ", scopes: ["queue:read"] })).toThrow(/Name the token/);+ expect(() => admin.createAdminToken({ name: "x".repeat(61), scopes: ["queue:read"] })).toThrow(/Name the token/);+ expect(() => admin.createAdminToken({ name: "a", scopes: [] })).toThrow(/Pick/);+ expect(() => admin.createAdminToken({ name: "a", scopes: ["everything"] })).toThrow(/Pick/);+ expect(() => admin.createAdminToken({ name: "a", scopes: ["queue:read"], expiresInDays: 0 })).toThrow(/expiry/);+ expect(() => admin.createAdminToken({ name: "a", scopes: ["queue:read"], expiresInDays: 366 })).toThrow(/expiry/);+ const dup = make(["queue:read"]);+ expect(() => admin.createAdminToken({ name: dup.info.name.toUpperCase(), scopes: ["queue:read"] })).toThrow(/exists/);+ while (admin.liveAdminTokenCount() < admin.MAX_LIVE_TOKENS) make(["queue:read"]);+ let err: unknown;+ try {+ make(["queue:read"]);+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(admin.AdminTokenError);+ expect((err as InstanceType<typeof admin.AdminTokenError>).status).toBe(409);+ // A revoked token frees its place.+ expect(admin.revokeAdminToken(dup.info.id)?.revokedAt).toBeGreaterThan(0);+ expect(admin.revokeAdminToken(dup.info.id)).toBeNull();+ expect(() => make(["queue:read"])).not.toThrow();+ admin.revokeAllAdminTokens();+ expect(admin.liveAdminTokenCount()).toBe(0);+ });++ it("checks a token: valid, wrong, revoked and expired (401 at once)", () => {+ const now = Date.now();+ const { token, info } = make(["queue:read"], { expiresInDays: 1, now });+ const ok = admin.tokenActor(req("/api/admin/queue", { token }), now);+ expect(ok).toMatchObject({ kind: "token", id: info.id, name: info.name, scopes: ["queue:read"] });+ const wrong = admin.tokenActor(req("/api/admin/queue", { token: `fuobe_adm_${"x".repeat(43)}` }), now) as Response;+ expect(wrong.status).toBe(401);+ expect(wrong.headers.get("www-authenticate")).toContain("invalid_token");+ const expired = admin.tokenActor(req("/api/admin/queue", { token }), now + 86_400_000 + 1) as Response;+ expect(expired.status).toBe(401);+ admin.revokeAdminToken(info.id);+ expect((admin.tokenActor(req("/api/admin/queue", { token }), now) as Response).status).toBe(401);+ // No admin token: not this check's business.+ expect(admin.tokenActor(req("/api/admin/queue"), now)).toBeNull();+ });++ it("compares against every live token in constant time, with no early exit", () => {+ admin.revokeAllAdminTokens();+ const a = make(["queue:read"]);+ make(["queue:read"]);+ make(["queue:read"]);+ const spy = vi.spyOn(crypto, "timingSafeEqual");+ try {+ admin.tokenActor(req("/api/admin/queue", { token: a.token }));+ expect(spy).toHaveBeenCalledTimes(3);+ spy.mockClear();+ admin.tokenActor(req("/api/admin/queue", { token: `fuobe_adm_${"y".repeat(43)}` }));+ expect(spy).toHaveBeenCalledTimes(3);+ } finally {+ spy.mockRestore();+ }+ });++ it("an owner API token is never rolled with a worker's or an admin token's prefix", () => {+ const spy = vi.spyOn(crypto, "randomBytes").mockImplementationOnce(() => Buffer.from(`adm_${"A".repeat(28)}`, "base64url"));+ try {+ const { token } = auth.createToken("script");+ expect(token).toMatch(/^fuobe_/);+ expect(token).not.toMatch(/^fuobe_(adm|wkr)_/i);+ expect(auth.validToken(`Bearer ${token}`)).toBe(true);+ } finally {+ spy.mockRestore();+ }+ });+});++describe("admin tokens: never the owner, only the admin API", () => {+ it("is refused by the proxy everywhere but /api/admin, a session cookie beside it or not", () => {+ const { token } = make(["queue:read"]);+ const refused = ["/", "/settings", "/library", "/api/settings", "/api/auth/tokens", "/api/auth/password", "/api/auth/sessions", "/api/reports", "/api/files/outputs/x.png", "/api/generations", "/api/mcp", "/api/gpu/computer/claim", "/api/admin", "/api/admin/tokens", "/api/admin/tokens/x", "/api/admin/%74okens"];+ for (const p of refused) {+ for (const cookie of [undefined, ownerCookie]) {+ const res = proxy(req(p, { token, cookie }));+ expect(res.status, p).toBe(403);+ expect(res.headers.get("x-middleware-next"), p).toBeNull();+ }+ }+ expect(proxy(req("/api/admin/tokens", { token, method: "POST", body: {} })).status).toBe(403);+ for (const p of ["/api/admin/queue", "/api/admin/accounts", "/api/admin/tokens/self", "/api/admin/files/outputs/x.png"]) {+ expect(proxy(req(p, { token })).headers.get("x-middleware-next"), p).toBe("1");+ }+ // Even a made-up one: the route judges it.+ expect(proxy(req("/api/admin/queue", { token: `fuobe_adm_${"x".repeat(43)}` })).headers.get("x-middleware-next")).toBe("1");+ });++ it("is never the owner, an account or a worker", () => {+ const { token } = make(["accounts:read"]);+ const r = req("/api/admin/accounts", { token, cookie: ownerCookie });+ expect(auth.validToken(`Bearer ${token}`)).toBe(false);+ expect(auth.requestViewer(r).kind).toBe("guest");+ expect(auth.requestAccount(r)).toBeNull();+ expect(auth.isOwnerRequest(req("/api/admin/accounts", { token }), undefined)).toBe(false);+ // A worker's route refuses it too (only fuobe_wkr_ reaches those).+ expect(proxy(req("/api/gpu/computer/tasks", { token })).status).toBe(403);+ });++ it("leaves owner and worker tokens as they were", () => {+ const owner = auth.createToken("owner script").token;+ expect(proxy(req("/api/settings", { token: owner })).headers.get("x-middleware-next")).toBe("1");+ expect(proxy(req("/api/admin/queue", { token: owner })).headers.get("x-middleware-next")).toBe("1");+ expect(proxy(req("/api/settings", { token: `fuobe_wkr_${"x".repeat(43)}` })).status).toBe(403);+ });++ it("can't make, list or revoke admin tokens; the owner's signed-in browser can", async () => {+ const { token, info } = make(["audit:read"]);+ const owner = auth.createToken("owner script 2").token;+ for (const o of [{ token }, { token, cookie: ownerCookie }, { token: owner }, {}]) {+ expect((await routes.tokens.GET(req("/api/admin/tokens", o))).status).toBe(403);+ expect((await routes.tokens.POST(req("/api/admin/tokens", { ...o, method: "POST", body: { name: "x", scopes: ["queue:read"] } }))).status).toBe(403);+ expect((await routes.tokens.DELETE(req(`/api/admin/tokens?id=${info.id}`, { ...o, method: "DELETE" }))).status).toBe(403);+ }+ const list = await routes.tokens.GET(req("/api/admin/tokens", { cookie: ownerCookie }));+ expect(list.status).toBe(200);+ const body = (await list.json()) as { tokens: { id: string }[]; scopes: { id: string; label: string }[] };+ expect(body.tokens.some((t) => t.id === info.id)).toBe(true);+ expect(body.scopes.map((s) => s.id)).toEqual([...admin.SCOPES]);+ expect(JSON.stringify(body)).not.toContain("hash");+ const made = await routes.tokens.POST(req("/api/admin/tokens", { cookie: ownerCookie, method: "POST", body: { name: "Panel", scopes: [...admin.SCOPES], expiresInDays: 90 } }));+ expect(made.status).toBe(201);+ const fresh = (await made.json()) as { token: string; info: { id: string; expiresAt: number } };+ expect(fresh.token).toMatch(/^fuobe_adm_/);+ expect(fresh.info.expiresAt).toBeGreaterThan(Date.now() + 89 * 86_400_000);+ expect((await routes.tokens.POST(req("/api/admin/tokens", { cookie: ownerCookie, method: "POST", body: { name: "", scopes: [] } }))).status).toBe(400);+ expect((await routes.tokens.DELETE(req(`/api/admin/tokens?id=${fresh.info.id}`, { cookie: ownerCookie, method: "DELETE" }))).status).toBe(204);+ expect((await routes.queue.GET(req("/api/admin/queue", { token: fresh.token }))).status).toBe(401);+ const logged = auditRows().filter((r) => r.target === fresh.info.id);+ expect(logged.map((r) => r.action)).toEqual(["token.create", "token.revoke"]);+ expect(JSON.stringify(auditRows())).not.toContain(fresh.token);+ });++ it("tells a token its own name and scopes at /tokens/self", async () => {+ const { token, info } = make(["queue:read", "runs:read"]);+ const res = await routes.self.GET(req("/api/admin/tokens/self", { token }));+ expect(res.status).toBe(200);+ const body = (await res.json()) as Record<string, unknown>;+ expect(body).toEqual({ id: info.id, name: info.name, prefix: info.prefix, scopes: ["queue:read", "runs:read"], expiresAt: null, createdAt: info.createdAt });+ expect((await routes.self.GET(req("/api/admin/tokens/self", { cookie: ownerCookie }))).status).toBe(401);+ expect((await routes.self.GET(req("/api/admin/tokens/self", { token: `fuobe_adm_${"z".repeat(43)}` }))).status).toBe(401);+ });+});++describe("admin tokens: every admin route asks for its scope", () => {+ type Call = { name: string; scope: Scope; run: (o: { token?: string; cookie?: string }) => Promise<Response> };+ const calls: Call[] = [+ { name: "GET accounts", scope: "accounts:read", run: (o) => routes.accounts.GET(req("/api/admin/accounts", o)) },+ { name: "GET accounts csv", scope: "accounts:read", run: (o) => routes.accounts.GET(req("/api/admin/accounts?format=csv", o)) },+ { name: "GET account", scope: "accounts:read", run: (o) => routes.account.GET(req("/api/admin/accounts/nope", o), ctx({ id: "nope" })) },+ { name: "PATCH account", scope: "accounts:write", run: (o) => routes.account.PATCH(req("/api/admin/accounts/nope", { ...o, method: "PATCH", body: { disabled: true } }), ctx({ id: "nope" })) },+ { name: "DELETE account", scope: "accounts:delete", run: (o) => routes.account.DELETE(req("/api/admin/accounts/nope", { ...o, method: "DELETE" }), ctx({ id: "nope" })) },+ { name: "GET runs", scope: "runs:read", run: (o) => routes.runs.GET(req("/api/admin/generations", o)) },+ { name: "DELETE run", scope: "runs:delete", run: (o) => routes.run.DELETE(req("/api/admin/generations/nope", { ...o, method: "DELETE" }), ctx({ id: "nope" })) },+ { name: "POST hide", scope: "outputs:hide", run: (o) => routes.outputs.POST(req("/api/admin/outputs/hide", { ...o, method: "POST", body: { assetIds: ["nope"] } }), ctx({ action: "hide" })) },+ { name: "POST unhide", scope: "outputs:moderate", run: (o) => routes.outputs.POST(req("/api/admin/outputs/unhide", { ...o, method: "POST", body: { assetIds: ["nope"] } }), ctx({ action: "unhide" })) },+ { name: "POST remove", scope: "outputs:moderate", run: (o) => routes.outputs.POST(req("/api/admin/outputs/remove", { ...o, method: "POST", body: { assetIds: ["nope"] } }), ctx({ action: "remove" })) },+ { name: "GET files", scope: "outputs:view", run: (o) => routes.files.GET(req("/api/admin/files/outputs/nope.png", o), ctx({ path: ["outputs", "nope.png"] })) },+ { name: "GET queue", scope: "queue:read", run: (o) => routes.queue.GET(req("/api/admin/queue", o)) },+ { name: "GET workers", scope: "workers:read", run: (o) => routes.workers.GET(req("/api/admin/workers", o)) },+ { name: "GET download", scope: "workers:read", run: (o) => routes.download.GET(req("/api/admin/workers/download", o)) },+ { name: "POST workers", scope: "workers:write", run: (o) => routes.workers.POST(req("/api/admin/workers", { ...o, method: "POST", body: { name: `w${++n}` } })) },+ { name: "PATCH worker", scope: "workers:write", run: (o) => routes.worker.PATCH(req("/api/admin/workers/nope", { ...o, method: "PATCH", body: { paused: true } }), ctx({ id: "nope" })) },+ { name: "GET reports", scope: "reports:read", run: (o) => routes.reports.GET(req("/api/admin/reports", o)) },+ { name: "GET audit", scope: "audit:read", run: (o) => routes.audit.GET(req("/api/admin/audit", o)) },+ ];++ it("refuses no token (the route's own 403), a wrong token (401) and an expired one (401)", async () => {+ const now = Date.now();+ const old = make([...admin.SCOPES], { expiresInDays: 1, now: now - 2 * 86_400_000 });+ for (const c of calls) {+ const none = await c.run({});+ expect(none.status, c.name).toBe(403);+ expect(((await none.json()) as { code?: string }).code, c.name).toBeUndefined();+ expect((await c.run({ token: `fuobe_adm_${"q".repeat(43)}` })).status, c.name).toBe(401);+ expect((await c.run({ token: old.token })).status, c.name).toBe(401);+ resetRates();+ }+ });++ it("refuses a token without the scope (403 scope) and takes one with it", async () => {+ for (const c of calls) {+ const other = make(admin.SCOPES.filter((s) => s !== c.scope && !(c.scope === "outputs:hide" && s === "outputs:moderate")));+ const res = await c.run({ token: other.token });+ expect(res.status, c.name).toBe(403);+ expect(await res.json(), c.name).toMatchObject({ code: "scope", scope: c.scope });+ const own = make([c.scope]);+ const ok = await c.run({ token: own.token });+ expect([200, 201, 204, 404], c.name).toContain(ok.status);+ admin.revokeAllAdminTokens();+ resetRates();+ }+ expect(auditRows().filter((r) => r.action === "scope.denied").length).toBeGreaterThanOrEqual(calls.length - 1);+ });++ it("outputs:hide can hide but not show again or remove", async () => {+ const { token } = make(["outputs:hide"]);+ const body = { assetIds: ["nope"] };+ expect((await routes.outputs.POST(req("/api/admin/outputs/hide", { token, method: "POST", body }), ctx({ action: "hide" }))).status).toBe(200);+ for (const action of ["unhide", "remove"]) {+ const res = await routes.outputs.POST(req(`/api/admin/outputs/${action}`, { token, method: "POST", body }), ctx({ action }));+ expect(res.status, action).toBe(403);+ expect(await res.json()).toMatchObject({ code: "scope", scope: "outputs:moderate" });+ }+ // outputs:moderate hides too.+ const mod = make(["outputs:moderate"]);+ expect((await routes.outputs.POST(req("/api/admin/outputs/hide", { token: mod.token, method: "POST", body }), ctx({ action: "hide" }))).status).toBe(200);+ });++ it("judges a request by its token alone: an owner session beside it doesn't help", async () => {+ const { token } = make(["queue:read"]);+ expect((await routes.accounts.GET(req("/api/admin/accounts", { token, cookie: ownerCookie }))).status).toBe(403);+ expect((await routes.accounts.GET(req("/api/admin/accounts", { token: `fuobe_adm_${"w".repeat(43)}`, cookie: ownerCookie }))).status).toBe(401);+ });++ it("answers the owner's session exactly as before", async () => {+ const a = auth.createAccount(`owner-view-${++n}@example.com`, "long enough");+ const res = await routes.accounts.GET(req("/api/admin/accounts", { cookie: ownerCookie }));+ expect(res.status).toBe(200);+ expect(Object.keys((await res.json()) as object).sort()).toEqual(["items", "total", "totals"]);+ const off = await routes.account.PATCH(req(`/api/admin/accounts/${a.id}`, { cookie: ownerCookie, method: "PATCH", body: { disabled: true } }), ctx({ id: a.id }));+ expect(await off.json()).toMatchObject({ id: a.id, disabled: true });+ const denied = await routes.accounts.GET(req("/api/admin/accounts"));+ expect(await denied.json()).toEqual({ error: "You can't open this." });+ const queue = await routes.queue.GET(req("/api/admin/queue"));+ expect(await queue.json()).toEqual({ error: "Only the studio's owner sees the queue" });+ // The owner's change is logged as the owner's; the owner's reads aren't logged.+ const last = auditRows().at(-1)!;+ expect(last).toMatchObject({ actor: "owner", action: "account.disable", target: a.id, token_id: null, status: 200 });+ expect(auditRows().some((r) => r.actor === "owner" && r.action === "accounts.list")).toBe(false);+ });+});++describe("admin tokens: limits", () => {+ it("allows 120 requests a minute per token, 30 of them changes", () => {+ const { token, info } = make(["workers:write"]);+ const now = Date.now();+ for (let i = 0; i < admin.TOKEN_CHANGES_PER_MINUTE; i++) expect(admin.tokenActor(req("/api/admin/workers", { token, method: "POST" }), now)).toMatchObject({ kind: "token" });+ const change = admin.tokenActor(req("/api/admin/workers", { token, method: "POST" }), now) as Response;+ expect(change.status).toBe(429);+ expect(change.headers.get("retry-after")).toBeTruthy();+ for (let i = admin.TOKEN_CHANGES_PER_MINUTE; i < admin.TOKEN_PER_MINUTE; i++) expect(admin.tokenActor(req("/api/admin/workers", { token }), now)).toMatchObject({ kind: "token" });+ const read = admin.tokenActor(req("/api/admin/workers", { token }), now) as Response;+ expect(read.status).toBe(429);+ expect(auditRows().some((r) => r.action === "rate.limited" && r.token_id === info.id)).toBe(true);+ // A minute later it works again.+ expect(admin.tokenActor(req("/api/admin/workers", { token }), now + 61_000)).toMatchObject({ kind: "token" });+ });++ it("slows down wrong tokens without ever blocking a valid one", async () => {+ const { token } = make(["queue:read"]);+ const statuses: number[] = [];+ for (let i = 0; i < 70; i++) statuses.push((admin.tokenActor(req("/api/admin/queue", { token: `fuobe_adm_${String(i).padStart(43, "0")}` })) as Response).status);+ expect(statuses.slice(0, 60).every((s) => s === 401)).toBe(true);+ expect(statuses.slice(60).every((s) => s === 429)).toBe(true);+ expect((await routes.queue.GET(req("/api/admin/queue", { token }))).status).toBe(200);+ });+});++describe("admin tokens: the log", () => {+ it("writes a token's changes with its name, never its value; coalesces its reads", async () => {+ const { token, info } = make(["accounts:read", "accounts:write"]);+ const a = auth.createAccount(`logged-${++n}@example.com`, "long enough");+ const before = auditRows().length;+ await routes.account.PATCH(req(`/api/admin/accounts/${a.id}`, { token, method: "PATCH", body: { disabled: true } }), ctx({ id: a.id }));+ await routes.account.PATCH(req("/api/admin/accounts/nope", { token, method: "PATCH", body: { disabled: false } }), ctx({ id: "nope" }));+ await routes.accounts.GET(req("/api/admin/accounts", { token }));+ await routes.accounts.GET(req("/api/admin/accounts?q=logged", { token }));+ const rows = auditRows().slice(before);+ expect(rows.map((r) => [r.action, r.status])).toEqual([+ ["account.disable", 200],+ ["account.enable", 404],+ ["accounts.list", 200],+ ]);+ expect(rows[0]).toMatchObject({ actor: "token", token_id: info.id, token_name: info.name, target: a.id });+ const all = JSON.stringify(db().prepare("SELECT * FROM admin_audit").all());+ expect(all).not.toContain(token);+ expect(all).not.toContain("logged-");+ });++ it("reads the log in pages, filtered", async () => {+ const { token } = make(["audit:read"]);+ const first = (await (await routes.audit.GET(req("/api/admin/audit?limit=2", { token }))).json()) as { items: { id: number }[]; next: string | null };+ expect(first.items).toHaveLength(2);+ expect(first.items[0].id).toBeGreaterThan(first.items[1].id);+ expect(first.next).toBe(String(first.items[1].id));+ const second = (await (await routes.audit.GET(req(`/api/admin/audit?limit=2&before=${first.next}`, { token }))).json()) as { items: { id: number }[] };+ expect(second.items[0].id).toBeLessThan(first.items[1].id);+ const owner = (await (await routes.audit.GET(req("/api/admin/audit?actor=owner&limit=200", { token }))).json()) as { items: { actor: string }[] };+ expect(owner.items.every((r) => r.actor === "owner")).toBe(true);+ expect((await routes.audit.GET(req("/api/admin/audit?limit=500", { token }))).status).toBe(400);+ expect((await routes.audit.GET(req("/api/admin/audit?before=x", { token }))).status).toBe(400);+ });+});++describe("admin tokens: accounts and files", () => {+ it("finds accounts by part of the email or the exact email; totals still cover everyone", async () => {+ const { token } = make(["accounts:read"]);+ const a = auth.createAccount(`findme-${++n}@example.com`, "long enough");+ const all = (await (await routes.accounts.GET(req("/api/admin/accounts", { token }))).json()) as { total: number };+ const q = (await (await routes.accounts.GET(req("/api/admin/accounts?q=FINDME", { token }))).json()) as { total: number; matched: number; items: { id: string }[]; totals: { accounts: number } };+ expect(q.items.map((x) => x.id)).toEqual([a.id]);+ expect(q.matched).toBe(1);+ expect(q.total).toBe(all.total);+ expect(q.totals.accounts).toBe(all.total);+ const e = (await (await routes.accounts.GET(req(`/api/admin/accounts?email=${encodeURIComponent(a.email.toUpperCase())}`, { token }))).json()) as { items: { id: string }[] };+ expect(e.items.map((x) => x.id)).toEqual([a.id]);+ expect((await routes.accounts.GET(req("/api/admin/accounts?email=not-an-email", { token }))).status).toBe(400);+ expect((await routes.accounts.GET(req(`/api/admin/accounts?q=${"x".repeat(101)}`, { token }))).status).toBe(400);+ const one = await routes.account.GET(req(`/api/admin/accounts/${a.id}`, { token }), ctx({ id: a.id }));+ expect(await one.json()).toMatchObject({ id: a.id, email: a.email, runs: 0, bytes: 0 });+ });++ it("signs an account out everywhere and keeps it on", async () => {+ const { token } = make(["accounts:write"]);+ const a = auth.createAccount(`signout-${++n}@example.com`, "long enough");+ const s = auth.createSession(a.id).value;+ expect(auth.sessionViewer(s)?.kind).toBe("account");+ const res = await routes.account.PATCH(req(`/api/admin/accounts/${a.id}`, { token, method: "PATCH", body: { signOut: true } }), ctx({ id: a.id }));+ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({ id: a.id, disabled: false });+ expect(auth.sessionViewer(s)).toBeNull();+ await new Promise((r) => setTimeout(r, 5));+ expect(auth.sessionViewer(auth.createSession(a.id).value)?.kind).toBe("account");+ expect(auditRows().at(-1)).toMatchObject({ action: "account.signout", target: a.id });+ expect((await routes.account.PATCH(req(`/api/admin/accounts/${a.id}`, { token, method: "PATCH", body: { signOut: true, disabled: true } }), ctx({ id: a.id }))).status).toBe(400);+ expect((await routes.account.PATCH(req("/api/admin/accounts/nope", { token, method: "PATCH", body: { signOut: true } }), ctx({ id: "nope" }))).status).toBe(404);+ });++ it("serves accounts' and held files to outputs:view, never the owner's, and logs each view", async () => {+ const { token, info } = make(["outputs:view"]);+ const a = auth.createAccount(`files-${++n}@example.com`, "long enough");+ const mine = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload" });+ const theirs = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: a.id });+ const held = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: a.id });+ db().prepare("UPDATE assets SET held = 1 WHERE id = ?").run(held.id);+ const get = (url: string) => {+ const rel = url.replace(/^\/api\/files\//, "");+ return routes.files.GET(req(`/api/admin/files/${rel}`, { token }), ctx({ path: rel.split("/") }));+ };+ const ok = await get(theirs.url);+ expect(ok.status).toBe(200);+ expect(ok.headers.get("cache-control")).toBe("no-store");+ expect(Buffer.from(await ok.arrayBuffer()).equals(TINY_PNG)).toBe(true);+ expect((await get(held.url)).status).toBe(200);+ expect((await get(mine.url)).status).toBe(404);+ expect((await get("/api/files/outputs/none.png")).status).toBe(404);+ const views = auditRows().filter((r) => r.action === "file.view" && r.token_id === info.id);+ expect(views.map((v) => JSON.parse(v.detail_json!))).toEqual([{ account: a.id }, { account: "held" }]);+ // One row per file an hour.+ await get(theirs.url);+ expect(auditRows().filter((r) => r.action === "file.view" && r.token_id === info.id)).toHaveLength(2);+ });++ it("Sign everyone out with every API token revokes admin tokens too", async () => {+ const { token } = make(["queue:read"]);+ expect((await routes.queue.GET(req("/api/admin/queue", { token }))).status).toBe(200);+ const res = await routes.sessions.POST(req("/api/auth/sessions", { cookie: ownerCookie, method: "POST", body: { tokens: true } }));+ expect(res.status).toBe(200);+ expect((await routes.queue.GET(req("/api/admin/queue", { token }))).status).toBe(401);+ expect(admin.liveAdminTokenCount()).toBe(0);+ ownerCookie = auth.createSession().value;+ });+});