Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Admin tokens: own limits for file views, a scope for worker tokens

Adarshd49e9b2d74e2
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 2712616f..aa7281d0 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -363,7 +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).
+- **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 checks a request by its admin token alone, and otherwise asks for the owner as before. `validToken()` never takes one. Per-token limits a minute (120 reads, 30 changes, 600 file views, each counted on its own) and a separate budget for wrong tokens. Changes, a token's reads and file views, and refusals go to `admin_audit` (kept a year). A worker token is made only with `workers:tokens`.
- **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/admin-api.md b/docs/admin-api.md
index efaab536..29aa2dd3 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -10,7 +10,7 @@ An admin token:
`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;
+- stands 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
@@ -35,16 +35,17 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz
| 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:write` | `PATCH /api/admin/accounts/{id}` with `{ "disabled": true \| false }` or `{ "signOut": true }` (its paired ComfyUIs stop too) |
| `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:view` | `GET /api/admin/files/{path}`: an account's stored file, held ones too (never the owner's own). 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}` |
+| `workers:write` | `PATCH /api/admin/workers/{id}`: pause, resume, drain, hours, lanes, revoke |
+| `workers:tokens` | `POST /api/admin/workers`, and `PATCH /api/admin/workers/{id}` with `rotate`: both answer with a worker token. A worker receives accounts' queued jobs with their input files and sends back the results, so give this scope only to a tool you'd trust with those |
| `queue:read` | `GET /api/admin/queue` |
| `audit:read` | `GET /api/admin/audit` |
@@ -97,29 +98,32 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `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 |
+| `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. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone) |
| `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/files/{path}` | `Range` works | the file; 404 for the owner's own files (held or not) 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 |
+| `PATCH /api/admin/workers/{id}` | any of `paused`, `pauseNow`, `drain`, `autoResume`, `hours`, `allow`, `claimAfterMs`, `switchAfterMs`, `rotate` (needs `workers:tokens`), `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/audit` | `before` (the last page's `next`), `limit` (1 to 200, default 50), `actor` (`owner` or `token`), `token` (a token id), `action`, `changes=1` (changes only: no reads, file views or refusals) | `{ 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`,
+`worker.rotate`, `worker.revoke`, `token.create`, `token.revoke`, `token.revoke_all`; 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.
+A row is written once the change is made. If the server can't write it (a full disk, say), the change still stands and
+the server's own log notes the missing row.
+
## Errors and limits
Errors are `{ "error": "…" }`, with a `code` where a tool may want to act on it:
@@ -133,9 +137,9 @@ Errors are `{ "error": "…" }`, with a `code` where a tool may want to act on i
| 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.
+Each minute, a token may send 120 reads, 30 changes and 600 file views (`/api/admin/files`), each counted on its own,
+so a page of previews never uses up the next change. 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.
diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.ts
index f732dc0b..3bf70236 100644
--- a/src/app/api/admin/accounts/[id]/route.ts
+++ b/src/app/api/admin/accounts/[id]/route.ts
@@ -4,6 +4,7 @@ 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";
+import { revokeWorkersOf } from "@/server/computer/workers";
const NO_STORE = { "Cache-Control": "no-store" };
const DENIED = "You can't open this.";
@@ -33,7 +34,7 @@ const Patch = z.union([z.object({ disabled: z.boolean() }).strict(), z.object({
/**
* 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).
+ * (`{ signOut: true }`: every sign-in ends and its paired ComfyUIs stop, and it stays on).
*/
export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {
const access = adminAccess(request, "accounts:write", DENIED);
@@ -42,13 +43,16 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/acco
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";
+ let computers = 0;
try {
- if ("signOut" in parsed.data) signOutAccount(id);
- else setAccountDisabled(id, parsed.data.disabled);
+ if ("signOut" in parsed.data) {
+ signOutAccount(id);
+ computers = revokeWorkersOf(`acct:${id}`);
+ } else setAccountDisabled(id, parsed.data.disabled);
} catch (e) {
return failed(e, access.actor, action, id);
}
- audit(access.actor, action, id, null, 200);
+ audit(access.actor, action, id, computers ? { computers } : null, 200);
return Response.json(listAccounts().find((a) => a.id === id), { headers: NO_STORE });
}
diff --git a/src/app/api/admin/audit/route.ts b/src/app/api/admin/audit/route.ts
index d2050337..89c7fee2 100644
--- a/src/app/api/admin/audit/route.ts
+++ b/src/app/api/admin/audit/route.ts
@@ -5,7 +5,7 @@ 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>`.
+ * page), `limit` (1 to 200, 50 when not given), `actor=owner|token`, `token=<id>`, `action=<name>`, `changes=1` (no reads, file views or refusals).
*/
export async function GET(request: Request) {
await connection();
diff --git a/src/app/api/admin/files/[...path]/route.ts b/src/app/api/admin/files/[...path]/route.ts
index 315980ba..20dfcb78 100644
--- a/src/app/api/admin/files/[...path]/route.ts
+++ b/src/app/api/admin/files/[...path]/route.ts
@@ -1,5 +1,5 @@
import { connection } from "next/server";
-import { fileAccount, HELD_FILE } from "@/server/account-library";
+import { fileRecord } from "@/server/account-library";
import { adminAccess, auditFileView } from "@/server/admin-tokens";
import { fileResponse } from "@/server/file-response";
@@ -7,8 +7,8 @@ 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.
+ * /api/files/. Accounts' files only, held ones too (waiting for their check, or hidden: what moderation has to see);
+ * the owner's own files, held or not, 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();
@@ -17,8 +17,8 @@ export async function GET(request: Request, ctx: RouteContext<"/api/admin/files/
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);
+ const file = fileRecord(rel);
+ if (!file?.account) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });
+ auditFileView(access.actor, rel, file.account, file.held);
return fileResponse(request, rel, { cache: "no-store" });
}
diff --git a/src/app/api/admin/outputs/[action]/route.ts b/src/app/api/admin/outputs/[action]/route.ts
index 78c250c0..32a03ed2 100644
--- a/src/app/api/admin/outputs/[action]/route.ts
+++ b/src/app/api/admin/outputs/[action]/route.ts
@@ -15,7 +15,7 @@ const SCOPE: Record<string, Scope[]> = { hide: ["outputs:hide", "outputs:moderat
*/
export async function POST(request: Request, ctx: RouteContext<"/api/admin/outputs/[action]">) {
const { action } = await ctx.params;
- const access = adminAccess(request, SCOPE[action] ?? ["outputs:moderate"], "Only the studio's owner can take results down");
+ const access = adminAccess(request, Object.hasOwn(SCOPE, action) ? 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) };
diff --git a/src/app/api/admin/workers/[id]/route.ts b/src/app/api/admin/workers/[id]/route.ts
index e037800d..b4f47a29 100644
--- a/src/app/api/admin/workers/[id]/route.ts
+++ b/src/app/api/admin/workers/[id]/route.ts
@@ -1,4 +1,4 @@
-import { adminAccess, audit } from "@/server/admin-tokens";
+import { adminAccess, audit, lacksScope } from "@/server/admin-tokens";
import { patchWorker, type WorkerPatch } from "@/server/computer/pool";
const NO_STORE = { "Cache-Control": "no-store" };
@@ -9,8 +9,8 @@ const KEYS = ["paused", "pauseNow", "drain", "autoResume", "hours", "allow", "cl
/**
* 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.
+ * Each reaches the worker at its next beat. Rotate answers with the new token, once (an admin token needs
+ * workers:tokens for it); 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]">) {
const access = adminAccess(request, "workers:write", "Only the studio's owner manages workers");
@@ -18,6 +18,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/work
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 });
+ if (body.rotate) {
+ const refused = lacksScope(access.actor, "workers:tokens", request);
+ if (refused) return refused;
+ }
const action = body.revoke ? "worker.revoke" : body.rotate ? "worker.rotate" : "worker.change";
const keys = KEYS.filter((k) => k in body);
try {
diff --git a/src/app/api/admin/workers/route.ts b/src/app/api/admin/workers/route.ts
index 04c4518f..62b4b61a 100644
--- a/src/app/api/admin/workers/route.ts
+++ b/src/app/api/admin/workers/route.ts
@@ -6,9 +6,10 @@ const NO_STORE = { "Cache-Control": "no-store" };
const DENIED = "Only the studio's owner manages workers";
/**
- * 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.
+ * Settings → Workers (owner only, or an admin token with workers:read / workers:tokens; 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. A worker's token
+ * receives accounts' queued jobs and their files, so making one needs workers:tokens, not just workers:write.
*/
export async function GET(request: Request) {
await connection();
@@ -18,7 +19,7 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
- const access = adminAccess(request, "workers:write", DENIED);
+ const access = adminAccess(request, "workers:tokens", 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) : "";
diff --git a/src/app/api/auth/sessions/route.ts b/src/app/api/auth/sessions/route.ts
index 03eb0c95..ff6864fb 100644
--- a/src/app/api/auth/sessions/route.ts
+++ b/src/app/api/auth/sessions/route.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { revokeAllAdminTokens } from "@/server/admin-tokens";
+import { audit, revokeAllAdminTokens } from "@/server/admin-tokens";
import { authEnabled, SESSION_COOKIE, sessionCookieOf, signOutEveryone, validSession } from "@/server/auth";
/**
@@ -14,7 +14,10 @@ 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();
+ if (tokensRevoked) {
+ const n = revokeAllAdminTokens();
+ if (n) audit({ kind: "owner" }, "token.revoke_all", null, { count: n }, 200);
+ }
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.tsx
index 192ee684..22579a41 100644
--- a/src/components/admin-tokens.tsx
+++ b/src/components/admin-tokens.tsx
@@ -44,6 +44,7 @@ interface AuditRow {
token: { id: string; name: string } | null;
action: string;
target: string | null;
+ detail: Record<string, unknown> | null;
status: number;
}
@@ -72,6 +73,7 @@ const ACTION_WORDS: Record<string, string> = {
"worker.revoke": "Revoked a worker",
"token.create": "Made an admin token",
"token.revoke": "Revoked an admin token",
+ "token.revoke_all": "Revoked every admin token",
"accounts.list": "Read the accounts",
"accounts.csv": "Downloaded the accounts",
"account.read": "Read an account",
@@ -85,6 +87,18 @@ const ACTION_WORDS: Record<string, string> = {
export const ADMIN_TOKENS_KEY = ["admin-tokens"];
+/** What a log row was about, in short: a name the action kept, the results it named, or its target. */
+function rowSubject(r: AuditRow): string | null {
+ const d = r.detail ?? {};
+ if (typeof d.name === "string" && d.name) return d.name;
+ if (typeof d.count === "number") return String(d.count);
+ if (Array.isArray(d.ids) && d.ids.length) {
+ const ids = d.ids.filter((x): x is string => typeof x === "string");
+ return ids.length > 3 ? `${ids.slice(0, 3).join(", ")} +${ids.length - 3}` : ids.join(", ");
+ }
+ return r.target;
+}
+
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;
@@ -105,7 +119,7 @@ function expiryText(t: AdminTokenRow, now = Date.now()): string {
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 }) {
+function CreateForm({ scopes, onMade, onCancel }: { scopes: AdminTokensAnswer["scopes"]; onMade: (made: { id: string; token: string }) => void; onCancel: () => void }) {
const id = useId();
const [name, setName] = useState("");
const [picked, setPicked] = useState<Set<string>>(() => new Set(READ_ONLY));
@@ -116,9 +130,9 @@ function CreateForm({ scopes, onMade, onCancel }: { scopes: AdminTokensAnswer["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) });
+ const r = await call<{ token: string; info: { id: string } }>("/api/admin/tokens", "POST", { name: name.trim(), scopes: [...picked], expiresInDays: expiry === "never" ? null : Number(expiry) });
setName("");
- onMade(r.token);
+ onMade({ id: r.info.id, token: r.token });
} catch (e) {
toastError(e);
} finally {
@@ -129,7 +143,7 @@ function CreateForm({ scopes, onMade, onCancel }: { scopes: AdminTokensAnswer["s
<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)} />
+ <Input id={`${id}-name`} placeholder="What it's for, e.g. “Moderation script”" 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">
@@ -222,22 +236,33 @@ function TokenItem({ t, onRevoke }: { t: AdminTokenRow; onRevoke: () => void })
/** The admin log, newest first: what the admin API changed, and what tokens read. */
function AdminLog() {
+ const [changes, setChanges] = useState(true);
const q = useInfiniteQuery({
- queryKey: ["admin-audit"],
+ queryKey: ["admin-audit", changes],
initialPageParam: "",
- queryFn: ({ pageParam }) => call<{ items: AuditRow[]; next: string | null }>(`/api/admin/audit?limit=20${pageParam ? `&before=${pageParam}` : ""}`),
+ queryFn: ({ pageParam }) => call<{ items: AuditRow[]; next: string | null }>(`/api/admin/audit?limit=20${changes ? "&changes=1" : ""}${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>
+ <div className="flex flex-wrap items-center gap-2">
+ <h4 className="flex-1 text-[12px] font-medium">Admin log</h4>
+ <div role="group" aria-label="Show" className="flex gap-1">
+ <Button size="sm" variant={changes ? "secondary" : "ghost"} className="h-7" aria-pressed={changes} onClick={() => setChanges(true)}>
+ Changes
+ </Button>
+ <Button size="sm" variant={changes ? "ghost" : "secondary"} className="h-7" aria-pressed={!changes} onClick={() => setChanges(false)}>
+ Everything
+ </Button>
+ </div>
+ </div>
{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>
+ <p className="text-[12px] text-muted-foreground">{changes ? "No changes yet. What the admin API changes shows here." : "Nothing yet. Changes made through the admin API, and what tokens read, show here."}</p>
) : (
<>
<ul className="divide-y rounded-xl border text-[12px]">
@@ -245,7 +270,7 @@ function AdminLog() {
<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>}
+ {rowSubject(r) && <span className="ml-1.5 font-mono text-[11px] break-all text-muted-foreground">{rowSubject(r)}</span>}
{r.status >= 400 && <span className="ml-1.5 text-[11px] text-destructive">{r.status}</span>}
</span>
<span className="text-[11px] text-muted-foreground">
@@ -273,7 +298,7 @@ function AdminLog() {
export function AdminTokens() {
const qc = useQueryClient();
const q = useQuery({ queryKey: ADMIN_TOKENS_KEY, queryFn: fetchAdminTokens });
- const [fresh, setFresh] = useState<string | null>(null);
+ const [fresh, setFresh] = useState<{ id: string; token: string } | null>(null);
const [making, setMaking] = useState(false);
const [revoking, setRevoking] = useState<AdminTokenRow | null>(null);
const refresh = () => {
@@ -284,6 +309,8 @@ export function AdminTokens() {
const revoke = async (t: AdminTokenRow) => {
try {
await call(`/api/admin/tokens?id=${encodeURIComponent(t.id)}`, "DELETE");
+ // A token shown once and revoked since is no use to copy.
+ setFresh((f) => (f?.id === t.id ? null : f));
toast.success(`Revoked ${t.name}`);
} catch (e) {
toastError(e);
@@ -310,21 +337,26 @@ export function AdminTokens() {
<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&apos;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 aria-label="New admin token" className="ph-no-capture min-w-0 flex-1 rounded-md bg-background px-2 py-1.5 font-mono text-[12px] break-all select-all">
+ {fresh.token}
</code>
- <Button size="sm" variant="secondary" className="shrink-0" onClick={() => void copyWithToast(fresh)}>
+ <Button size="sm" variant="secondary" className="shrink-0" onClick={() => void copyWithToast(fresh.token)}>
<Copy /> Copy
</Button>
</div>
+ <div className="mt-2 flex justify-end">
+ <Button size="sm" variant="ghost" className="h-7" onClick={() => setFresh(null)}>
+ Done
+ </Button>
+ </div>
</div>
)}
{making && q.data && (
<CreateForm
scopes={q.data.scopes}
onCancel={() => setMaking(false)}
- onMade={(token) => {
- setFresh(token);
+ onMade={(made) => {
+ setFresh(made);
setMaking(false);
refresh();
}}
diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsx
index 4f75d560..b3acfd01 100644
--- a/src/components/security-settings.tsx
+++ b/src/components/security-settings.tsx
@@ -155,7 +155,7 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => void
<p className="text-[12px] font-medium">Copy this token now — it won&apos;t be shown again.</p>
<div className="mt-2 flex items-center gap-2">
{/* The whole token, wrapped (a phone can't show it on one line); one tap selects it all. */}
- <code aria-label="New API token" className="min-w-0 flex-1 rounded-md bg-background px-2 py-1.5 font-mono text-[12px] break-all select-all">
+ <code aria-label="New API token" className="ph-no-capture 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)}>
diff --git a/src/server/account-admin.ts b/src/server/account-admin.ts
index ca690d18..83600f73 100644
--- a/src/server/account-admin.ts
+++ b/src/server/account-admin.ts
@@ -1,5 +1,6 @@
import "server-only";
-import type { Generation } from "@/lib/catalog/types";
+import path from "node:path";
+import type { Generation, OutputFile } from "@/lib/catalog/types";
import { accountsMaxBytes, accountTotalBytes } from "./account-files";
import { listAccounts, type AccountInfo } from "./auth";
import { db } from "./db";
@@ -122,8 +123,26 @@ export function accountRunOptions(sp: URLSearchParams): ListOptions | { error: s
};
}
-/** An account's run as the owner sees it: whose it is (null email: the account was deleted). */
-export type AccountRun = Generation & { account: { id: string; email: string | null } };
+/**
+ * Where a result stands: `shown` (served as usual), `held` (hidden, or waiting for its check: served to no account and
+ * by no link) or `removed` (its file is gone).
+ */
+export type OutputState = "shown" | "held" | "removed";
+
+/** An account's run as the owner sees it: whose it is (null email: the account was deleted), and each result's state. */
+export type AccountRun = Omit<Generation, "outputs"> & { outputs: (OutputFile & { state: OutputState })[]; account: { id: string; email: string | null } };
+
+/** Each result's state, read from its stored file (its asset row; none: removed). An output that isn't a stored file is shown. */
+function withStates(outputs: OutputFile[]): (OutputFile & { state: OutputState })[] {
+ const byId = db().prepare("SELECT held FROM assets WHERE id = ?");
+ const byPath = db().prepare("SELECT held FROM assets WHERE rel_path IN (?, ?) LIMIT 1");
+ return outputs.map((o) => {
+ const rel = o.url.startsWith("/api/files/") ? o.url.slice("/api/files/".length) : null;
+ if (!o.assetId && !rel) return { ...o, state: "shown" };
+ const row = (o.assetId ? byId.get(o.assetId) : byPath.get(rel, rel!.split("/").join(path.sep))) as { held: number } | undefined;
+ return { ...o, state: !row ? "removed" : row.held ? "held" : "shown" };
+ });
+}
/** One page of accounts' runs, newest first, and the cursor of the next (null on the last page). Never the owner's. */
export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: string | null } {
@@ -134,7 +153,7 @@ export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: st
const found = listGenerations(opts).filter((g) => g.request.account);
const last = found.at(-1);
return {
- items: found.map((g) => ({ ...g, account: { id: g.request.account!, email: emails.get(g.request.account!) ?? null } })),
+ items: found.map((g) => ({ ...g, outputs: withStates(g.outputs), account: { id: g.request.account!, email: emails.get(g.request.account!) ?? null } })),
next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,
};
}
diff --git a/src/server/account-library.ts b/src/server/account-library.ts
index d142e9de..184d2a55 100644
--- a/src/server/account-library.ts
+++ b/src/server/account-library.ts
@@ -24,6 +24,14 @@ export function generationAccount(id: string): string | null | undefined {
export const HELD_FILE = "\u0000held";
export function fileAccount(rel: string): string | null | undefined {
+ const row = fileRecord(rel);
+ // A result held for the moderation service's check (output-checks.ts) is nobody's to read until it passes.
+ if (row?.held) return HELD_FILE;
+ return row ? row.account : undefined;
+}
+
+/** A stored file's account (null: the owner's) and whether it is held; undefined when no asset has this path. */
+export function fileRecord(rel: string): { account: string | null; held: boolean } | undefined {
// Rows store the platform's separator (backslashes on Windows); a URL always has /.
const native = rel.split("/").join(path.sep);
const row = db()
@@ -32,9 +40,7 @@ export function fileAccount(rel: string): string | null | undefined {
FROM assets a LEFT JOIN generations g ON g.id = a.generation_id WHERE a.rel_path IN (?, ?) LIMIT 1`,
)
.get(rel, native) as { account: string | null; held: number | null } | undefined;
- // A result held for the moderation service's check (output-checks.ts) is nobody's to read until it passes.
- if (row?.held) return HELD_FILE;
- return row ? (row.account ?? null) : undefined;
+ return row ? { account: row.account ?? null, held: !!row.held } : undefined;
}
/** A stored file that is held (hidden, or waiting for its check): served to no account and by no link. */
diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.ts
index cdc5ca62..1596c52d 100644
--- a/src/server/admin-tokens.ts
+++ b/src/server/admin-tokens.ts
@@ -2,14 +2,14 @@ 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";
+import { hit } 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
+ * page, change settings or make tokens. A request that carries one is checked 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
@@ -29,6 +29,7 @@ export const SCOPES = [
"reports:read",
"workers:read",
"workers:write",
+ "workers:tokens",
"queue:read",
"audit:read",
] as const;
@@ -47,7 +48,8 @@ export const SCOPE_LABELS: Record<Scope, string> = {
"outputs:moderate": "Hide, show again and remove results",
"reports:read": "See reports",
"workers:read": "See workers",
- "workers:write": "Add and change workers",
+ "workers:write": "Pause, resume, change and revoke workers",
+ "workers:tokens": "Add workers and give them new tokens (a worker runs accounts' queued jobs, with their files)",
"queue:read": "See the queue",
"audit:read": "See the admin log",
};
@@ -61,9 +63,10 @@ const SHAPE = /^fuobe_adm_[A-Za-z0-9_-]{43}$/;
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. */
+/** What a token may send a minute: reads, changes and file views, each counted on its own. */
export const TOKEN_PER_MINUTE = 120;
export const TOKEN_CHANGES_PER_MINUTE = 30;
+export const FILE_VIEWS_PER_MINUTE = 600;
/** 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;
@@ -241,15 +244,14 @@ export function tokenActor(request: Request, now = Date.now()): Extract<Actor, {
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);
+ // Reads, changes and file views each have their own budget: a page of previews never uses up the next change.
+ const kind = isChange(request.method) ? "change" : new URL(request.url).pathname.startsWith("/api/admin/files/") ? "file" : "read";
+ const budget = { change: TOKEN_CHANGES_PER_MINUTE, file: FILE_VIEWS_PER_MINUTE, read: TOKEN_PER_MINUTE }[kind];
+ const r = hit(`admin-${kind}:${row.id}`, budget, MINUTE, now);
+ if (!r.ok) {
+ auditOnce(`rate:${row.id}:${kind}`, MINUTE, actor, "rate.limited", null, { kind }, 429, now);
+ return tooMany(r.retryAfterS);
}
- if (change) hit(`admin-change:${row.id}`, TOKEN_CHANGES_PER_MINUTE, MINUTE, now);
touch(row.id, now);
return actor;
}
@@ -262,17 +264,24 @@ export function adminAccess(request: Request, scopes: Scope | Scope[], denied: s
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 };
+ return lacksScope(t, scopes, request) ?? { actor: t };
}
if (isOwnerRequest(request, sessionCookieOf(request))) return { actor: { kind: "owner" } };
return json({ error: denied }, 403);
}
+/**
+ * The 403 for a token that has none of `scopes` (logged once a minute per token, scope and method), or null when it has
+ * one. The owner always may. For a need that depends on the body (a worker's new token), call it after adminAccess.
+ */
+export function lacksScope(actor: Actor, scopes: Scope | Scope[], request: Request): Response | null {
+ if (actor.kind !== "token") return null;
+ const wanted = Array.isArray(scopes) ? scopes : [scopes];
+ if (wanted.some((s) => actor.scopes.includes(s))) return null;
+ auditOnce(`scope:${actor.id}:${wanted[0]}:${request.method}`, MINUTE, actor, "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);
+}
+
/**
* 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.
@@ -318,15 +327,23 @@ export function audit(actor: Actor, action: string, target: string | null, detai
}
}
+const SEEN_MAX = 5000;
+const SEEN_KEEP = 4000;
+
/** 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;
+ // In the order last written: past SEEN_MAX keys, the oldest go (a key that comes back only writes one more row).
+ seen.delete(key);
seen.set(key, now);
- if (seen.size > 5000) for (const [k, t] of seen) if (now - t > DAY) seen.delete(k);
+ if (seen.size > SEEN_MAX) for (const k of [...seen.keys()].slice(0, seen.size - SEEN_KEEP)) seen.delete(k);
audit(actor, action, target, detail, status, now);
}
+/** Actions that change nothing: a token's reads, its file views and refusals (the log's "only changes" leaves them out). */
+export const READ_ACTIONS = ["accounts.list", "accounts.csv", "account.read", "runs.list", "reports.list", "audit.read", "file.view", "scope.denied", "rate.limited"];
+
/** 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;
@@ -334,9 +351,9 @@ export function auditRead(actor: Actor, action: string, detail: Record<string, u
}
/** A token opened a stored file: one row per token and file every hour. */
-export function auditFileView(actor: Actor, path: string, account: string): void {
+export function auditFileView(actor: Actor, path: string, account: string, held = false): void {
if (actor.kind !== "token") return;
- auditOnce(`file:${actor.id}:${path}`, 60 * MINUTE, actor, "file.view", path, { account }, 200);
+ auditOnce(`file:${actor.id}:${path}`, 60 * MINUTE, actor, "file.view", path, { account, ...(held && { held: true }) }, 200);
}
export interface AuditQuery {
@@ -345,6 +362,8 @@ export interface AuditQuery {
actor?: "owner" | "token";
token?: string;
action?: string;
+ /** Changes only: no reads, file views or refusals. */
+ changes?: boolean;
}
/** GET /api/admin/audit's query, or the reason it's wrong. */
@@ -359,8 +378,10 @@ export function auditQueryFrom(sp: URLSearchParams): AuditQuery | { error: strin
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 }) };
+ if (action !== null && !/^[a-z_.]{1,40}$/.test(action)) return { error: "Unknown action" };
+ const changes = sp.get("changes");
+ if (changes !== null && changes !== "1") return { error: "changes is 1" };
+ return { limit, ...(before !== null && { before: Number(before) }), ...(actor && { actor }), ...(token && { token }), ...(action && { action }), ...(changes && { changes: true }) };
}
/** The log, newest first; `next` is the last row's id (pass it as `before`), null on the last page. */
@@ -373,7 +394,11 @@ export function listAudit(q: AuditQuery): { items: AuditRow[]; next: string | nu
];
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 args: (string | number)[] = used.map((f) => f[1]);
+ if (q.changes) {
+ where.push(`action NOT IN (${READ_ACTIONS.map(() => "?").join(", ")})`);
+ args.push(...READ_ACTIONS);
+ }
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 }[];
diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.ts
index 4a0f93a2..ff37527d 100644
--- a/src/server/computer/workers.ts
+++ b/src/server/computer/workers.ts
@@ -170,6 +170,13 @@ export function unpair(principal: Principal, id: string): boolean {
return revokeWorker(id);
}
+/** Every paired ComfyUI of a principal stops at once, and a pairing it was in the middle of is dropped (signed out everywhere). How many were revoked. */
+export function revokeWorkersOf(principal: Principal, now = Date.now()): number {
+ const n = db().prepare("UPDATE relay_workers SET revoked_at = ? WHERE kind = 'personal' AND principal = ? AND revoked_at IS NULL").run(now, principal).changes;
+ db().prepare("DELETE FROM relay_pairings WHERE principal = ?").run(principal);
+ return n;
+}
+
/** Every paired ComfyUI of a principal goes (its account was deleted). */
export function forgetWorkersOf(principal: Principal): void {
db().prepare("DELETE FROM relay_workers WHERE kind = 'personal' AND principal = ?").run(principal);
diff --git a/src/server/takedown.ts b/src/server/takedown.ts
index 96a32ea7..1421bb25 100644
--- a/src/server/takedown.ts
+++ b/src/server/takedown.ts
@@ -67,7 +67,7 @@ export function removeOutputs(t: Targets, evidence: boolean): number {
if (a.generationId) {
const r = db().prepare("SELECT outputs_json FROM generations WHERE id = ?").get(a.generationId) as { outputs_json: string } | undefined;
if (r) {
- const left = (JSON.parse(r.outputs_json) as OutputFile[]).filter((o) => o.assetId !== id);
+ const left = (JSON.parse(r.outputs_json) as OutputFile[]).filter((o) => o.assetId !== id && o.url !== a.url);
db().prepare("UPDATE generations SET outputs_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(left), Date.now(), a.generationId);
}
}
diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.ts
index c527fbca..0154de2f 100644
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@ -21,6 +21,7 @@ const { db } = await import("@/server/db");
const { resetRates } = await import("@/server/rate");
const { saveFile } = await import("@/server/storage");
const { proxy } = await import("@/proxy");
+const workers = await import("@/server/computer/workers");
const routes = {
accounts: await import("@/app/api/admin/accounts/route"),
account: await import("@/app/api/admin/accounts/[id]/route"),
@@ -173,7 +174,7 @@ describe("admin tokens: never the owner, only the admin API", () => {
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.
+ // Even a made-up one: the route checks it.
expect(proxy(req("/api/admin/queue", { token: `fuobe_adm_${"x".repeat(43)}` })).headers.get("x-middleware-next")).toBe("1");
});
@@ -209,7 +210,7 @@ describe("admin tokens: never the owner, only the admin API", () => {
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 } }));
+ const made = await routes.tokens.POST(req("/api/admin/tokens", { cookie: ownerCookie, method: "POST", body: { name: "Tool", 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_/);
@@ -250,8 +251,9 @@ describe("admin tokens: every admin route asks for its scope", () => {
{ 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: "POST workers", scope: "workers:tokens", 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: "PATCH worker rotate", scope: "workers:tokens", run: (o) => routes.worker.PATCH(req("/api/admin/workers/nope", { ...o, method: "PATCH", body: { rotate: 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)) },
];
@@ -275,7 +277,7 @@ describe("admin tokens: every admin route asks for its scope", () => {
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 own = make(c.name === "PATCH worker rotate" ? ["workers:write", c.scope] : [c.scope]);
const ok = await c.run({ token: own.token });
expect([200, 201, 204, 404], c.name).toContain(ok.status);
admin.revokeAllAdminTokens();
@@ -298,7 +300,7 @@ describe("admin tokens: every admin route asks for its scope", () => {
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 () => {
+ it("checks 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);
@@ -323,21 +325,35 @@ describe("admin tokens: every admin route asks for its scope", () => {
});
describe("admin tokens: limits", () => {
- it("allows 120 requests a minute per token, 30 of them changes", () => {
+ it("counts a token's reads (120), changes (30) and file views (600) a minute, each on its own", () => {
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.
+ const ok = (r: Request) => expect(admin.tokenActor(r, now)).toMatchObject({ kind: "token" });
+ const limited = (r: Request) => {
+ const res = admin.tokenActor(r, now) as Response;
+ expect(res.status).toBe(429);
+ expect(res.headers.get("retry-after")).toBeTruthy();
+ };
+ // A page of previews: file views don't touch the reads or the changes.
+ for (let i = 0; i < admin.FILE_VIEWS_PER_MINUTE; i++) ok(req(`/api/admin/files/outputs/${i}.png`, { token }));
+ limited(req("/api/admin/files/outputs/more.png", { token }));
+ for (let i = 0; i < admin.TOKEN_PER_MINUTE; i++) ok(req("/api/admin/workers", { token }));
+ limited(req("/api/admin/workers", { token }));
+ // Reads used up: a change still goes through.
+ for (let i = 0; i < admin.TOKEN_CHANGES_PER_MINUTE; i++) ok(req("/api/admin/workers/x", { token, method: "PATCH" }));
+ limited(req("/api/admin/workers/x", { token, method: "PATCH" }));
+ const rows = auditRows().filter((r) => r.action === "rate.limited" && r.token_id === info.id);
+ expect(rows.map((r) => JSON.parse(r.detail_json!).kind).sort()).toEqual(["change", "file", "read"]);
+ // A minute later each works again.
expect(admin.tokenActor(req("/api/admin/workers", { token }), now + 61_000)).toMatchObject({ kind: "token" });
});
+ it("logs a token's refusals once per scope and method, whatever the path", async () => {
+ const { token, info } = make(["queue:read"]);
+ for (let i = 0; i < 50; i++) await routes.account.GET(req(`/api/admin/accounts/x${i}`, { token }), ctx({ id: `x${i}` }));
+ expect(auditRows().filter((r) => r.action === "scope.denied" && r.token_id === info.id)).toHaveLength(1);
+ });
+
it("slows down wrong tokens without ever blocking a valid one", async () => {
const { token } = make(["queue:read"]);
const statuses: number[] = [];
@@ -407,10 +423,16 @@ describe("admin tokens: accounts and files", () => {
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 paired = workers.createWorker({ name: "Studio PC", kind: "personal", principal: `acct:${a.id}` });
+ expect(workers.workerFromAuth(`Bearer ${paired.token}`)?.id).toBe(paired.id);
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();
+ // Its paired ComfyUI stops too: a worker token is no sign-in, so it is revoked.
+ expect(workers.workerFromAuth(`Bearer ${paired.token}`)).toBeNull();
+ expect(workers.pairedOf(`acct:${a.id}`)).toEqual([]);
+ expect(JSON.parse(auditRows().at(-1)!.detail_json!)).toEqual({ computers: 1 });
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 });
@@ -424,7 +446,8 @@ describe("admin tokens: accounts and files", () => {
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 mineHeld = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload" });
+ db().prepare("UPDATE assets SET held = 1 WHERE id IN (?, ?)").run(held.id, mineHeld.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("/") }));
@@ -435,9 +458,10 @@ describe("admin tokens: accounts and files", () => {
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(mineHeld.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" }]);
+ expect(views.map((v) => JSON.parse(v.detail_json!))).toEqual([{ account: a.id }, { account: a.id, held: true }]);
// 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);
@@ -450,6 +474,67 @@ describe("admin tokens: accounts and files", () => {
expect(res.status).toBe(200);
expect((await routes.queue.GET(req("/api/admin/queue", { token }))).status).toBe(401);
expect(admin.liveAdminTokenCount()).toBe(0);
+ expect(auditRows().at(-1)).toMatchObject({ actor: "owner", action: "token.revoke_all", status: 200 });
+ expect(JSON.parse(auditRows().at(-1)!.detail_json!).count).toBeGreaterThanOrEqual(1);
ownerCookie = auth.createSession().value;
});
});
+
+describe("admin tokens: runs, the log's changes and every admin route", () => {
+ it("says whether each of an account's results is shown, held or removed", async () => {
+ const { token } = make(["runs:read", "outputs:moderate"]);
+ const a = auth.createAccount(`runs-${++n}@example.com`, "long enough");
+ const id = `run-state-${++n}`;
+ db()
+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'succeeded', ?, '[]', ?, ?)")
+ .run(id, JSON.stringify({ feature: "image", modelId: "m", prompt: "p", account: a.id }), Date.now(), Date.now());
+ const files = [0, 1, 2].map(() => saveFile({ data: TINY_PNG, contentType: "image/png", source: "generation", generationId: id }));
+ // The last one is listed by its url only.
+ db()
+ .prepare("UPDATE generations SET outputs_json = ? WHERE id = ?")
+ .run(JSON.stringify(files.map((f, i) => ({ url: f.url, kind: "image", ...(i < 2 && { assetId: f.id }) }))), id);
+ const states = async () => {
+ const page = (await (await routes.runs.GET(req(`/api/admin/generations?account=${a.id}`, { token }))).json()) as { items: { id: string; outputs: { url: string; state: string }[] }[] };
+ return page.items.find((r) => r.id === id)!.outputs.map((o) => o.state);
+ };
+ expect(await states()).toEqual(["shown", "shown", "shown"]);
+ const body = (assetIds: string[]) => ({ token, method: "POST", body: { assetIds } });
+ await routes.outputs.POST(req("/api/admin/outputs/hide", body([files[1].id])), ctx({ action: "hide" }));
+ expect(await states()).toEqual(["shown", "held", "shown"]);
+ // Removing a result listed by url only takes it off the run too.
+ await routes.outputs.POST(req("/api/admin/outputs/remove", body([files[2].id])), ctx({ action: "remove" }));
+ expect(await states()).toEqual(["shown", "held"]);
+ db().prepare("DELETE FROM assets WHERE id = ?").run(files[0].id);
+ expect(await states()).toEqual(["removed", "held"]);
+ });
+
+ it("filters the log to changes", async () => {
+ const { token } = make(["audit:read", "queue:read"]);
+ await routes.accounts.GET(req("/api/admin/accounts", { token }));
+ const page = (await (await routes.audit.GET(req("/api/admin/audit?changes=1&limit=200", { token }))).json()) as { items: { action: string }[] };
+ expect(page.items.length).toBeGreaterThan(0);
+ expect(page.items.some((r) => admin.READ_ACTIONS.includes(r.action))).toBe(false);
+ expect((await routes.audit.GET(req("/api/admin/audit?changes=yes", { token }))).status).toBe(400);
+ });
+
+ it("every admin route checks who asks itself (the proxy lets any admin token through to them)", () => {
+ const root = path.join(process.cwd(), "src", "app", "api", "admin");
+ const found: string[] = [];
+ const walk = (d: string) => {
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.name === "route.ts") found.push(p);
+ }
+ };
+ walk(root);
+ expect(found.length).toBeGreaterThanOrEqual(14);
+ for (const f of found) {
+ const src = fs.readFileSync(f, "utf8");
+ const handlers = src.match(/export async function (GET|POST|PUT|PATCH|DELETE)\b/g) ?? [];
+ const checks = src.match(/\b(adminAccess|ownerBrowser|tokenActor)\(/g) ?? [];
+ expect(handlers.length, f).toBeGreaterThan(0);
+ expect(checks.length, f).toBeGreaterThanOrEqual(handlers.length);
+ }
+ });
+});