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 API: accounts' content and emails need their own scopes, every content read is logged, and links never show an account's run

Adarsh3c5c48a6a744
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 5176e837..f5543c03 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -339,7 +339,7 @@ Notifications (round 4): `src/components/job-notifications.tsx`, with the decisi
## Share links and Publish (`src/lib/share.ts`, `src/server/share-access.ts`, `src/server/shares.ts`)
-Round 4 part 4. A share link is an unguessable token that opens one public, read-only page and the files that page shows, nothing else. It names a result, a Library folder (with its subfolders), a Cinema project or a published selection (`ShareKind`), never files, so the page shows what still exists.
+Round 4 part 4. A share link is an unguessable token that opens one public, read-only page and the files that page shows, nothing else. It names a result, a Library folder (with its subfolders), a Cinema project or a published selection (`ShareKind`), never files, so the page shows what still exists. It only ever shows the owner's own results: an account's run is never on a link, as a result, in a selection or in a folder (`SHOWN` and the result `TARGET` check that the run has no account).
- **Tokens** (`src/server/share-access.ts`). `newToken()` makes a 12-character id (the row's key, for the lookup) and a 32-character secret, base64url, 44 characters in all. Only the SHA-256 of the whole token is stored (`shares.token_hash`); `findShare` compares in constant time (against a dummy hash when the id is unknown) and refuses an expired link, and revoking deletes the row. The owner gets the token once, in the answer to `POST /api/shares`; the browser that made it keeps the URL in localStorage (`fuobe.shareLinks`), so only that browser can copy it again. `shareTargetExists` checks with one lookup that the result (succeeded, not in the Trash), folder or project is still there.
- **The proxy's share routes** (`openShare` in `src/proxy.ts`). After the host allowlist and the cross-site check, and before sign-in, a GET or HEAD on exactly `/s/<token>` or `/s/<token>/f/<path>` (`shareRoute`: a 44-character token, a stored path with no dot segments, at most 300 characters) passes without a session, password or not. An unknown, expired or revoked token, or a target that is gone, is rewritten to `/s/gone` with a 404. Wrong tokens count against `ShareGuard`: once per token per window; past a global budget of 100 a minute they get 429; only a client the server can tell apart (the last `X-Forwarded-For` hop with `FUOBE_TRUST_PROXY=1`) is locked out, for 60 s after 20 wrong tokens in a minute, its own working links included. Everyone else's live links keep opening, and the signed-in owner is never limited. Only the proxy decides what counts as a view (`countsAsView`: a browser's GET of the page, not a HEAD, a prefetch, an RSC request or a link-preview bot); it passes that on in the `x-fuobe-share-view` header, after deleting any copy the client sent, and the page records it (`recordView`). Share responses carry `X-Robots-Tag: noindex, nofollow, noarchive` and `Referrer-Policy: no-referrer`.
diff --git a/docs/admin-api.md b/docs/admin-api.md
index 75bced2f..048f79f5 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -37,12 +37,12 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz
| `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 }` (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:read` | `GET /api/admin/generations`: accounts' runs, each one's facts only (when, which model and app, how it ended, how many results). 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, held ones too (never the owner's own). 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. With `runs:read`, the runs' prompts, inputs and results too |
| `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) |
+| `reports:read` | `GET /api/admin/reports` (reporters' emails only with `accounts:read`) |
| `workers:read` | `GET /api/admin/workers`, `GET /api/admin/workers/jobs`, `GET /api/admin/workers/download` |
| `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 |
@@ -50,6 +50,9 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz
| `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share and the pick allowance |
| `audit:read` | `GET /api/admin/audit` |
+The read-only preset in Settings ticks `runs:read`, `reports:read`, `workers:read`, `queue:read` and `audit:read`:
+no emails, no prompts and no results. With `runs:read`, an account's email in a run needs `accounts:read`.
+
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.
@@ -123,10 +126,11 @@ A log row is `{ id, at, actor: "owner" | "token" | "system", token: { id, name }
`worker.rotate`, `worker.revoke`, `queue.settings` (with the values before and after), `token.create`, `token.revoke`,
`token.revoke_all`, `settings.comfy_where` (where ComfyUI runs, with the values before and after); 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); refusals `scope.denied` and `rate.limited`;
-and the studio's own alerts `worker.alert` (actor `system`: a worker's token used from a new country, a new network,
-or two networks at once; [gpu-workers.md](gpu-workers.md#the-protocol)). The owner's own reads in the browser aren't
-logged. Rows go after a year. `actor` can be `system`, and the `actor` filter
+every 10 minutes); reads of accounts' content by a token or the owner: `runs.content` (one row per reader and account
+every 10 minutes, the account as its target) and `file.view` (one row per reader and file every hour); refusals
+`scope.denied` and `rate.limited`; and the studio's own alerts `worker.alert` (actor `system`: a worker's token used
+from a new country, a new network, or two networks at once; [gpu-workers.md](gpu-workers.md#the-protocol)). The
+owner's other reads in the browser aren't logged. Rows go after a year. `actor` can be `system`, and the `actor` filter
takes it.
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
diff --git a/src/app/api/admin/generations/route.ts b/src/app/api/admin/generations/route.ts
index 53e3cc55..a26d1f5f 100644
--- a/src/app/api/admin/generations/route.ts
+++ b/src/app/api/admin/generations/route.ts
@@ -1,6 +1,6 @@
import { connection } from "next/server";
import { accountRunOptions, listAccountRuns } from "@/server/account-admin";
-import { adminAccess, auditRead } from "@/server/admin-tokens";
+import { actorHas, adminAccess, auditContentRead, auditRead } from "@/server/admin-tokens";
const NO_STORE = { "Cache-Control": "no-store" };
@@ -8,6 +8,10 @@ const NO_STORE = { "Cache-Control": "no-store" };
* 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.
+ *
+ * A token with runs:read alone gets each run's facts (when, which model, how it ended); its prompt, inputs and results
+ * need outputs:view, and the accounts' emails need accounts:read. Every read of runs' content, the owner's too, is in
+ * the admin log, once per account every 10 minutes, with the account as its target.
*/
export async function GET(request: Request) {
await connection();
@@ -16,6 +20,10 @@ export async function GET(request: Request) {
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 });
+ const show = { content: actorHas(access.actor, "outputs:view"), emails: actorHas(access.actor, "accounts:read") };
+ const page = listAccountRuns(o, show);
+ const filters = { ...(o.account && { account: o.account }), ...(sp.get("status") && { status: sp.get("status") }), ...(o.kind && { kind: o.kind }) };
+ auditRead(access.actor, "runs.list", filters);
+ if (show.content) auditContentRead(access.actor, "runs.content", page.items.map((r) => r.account.id), filters);
+ return Response.json(page, { headers: NO_STORE });
}
diff --git a/src/app/api/admin/reports/route.ts b/src/app/api/admin/reports/route.ts
index 8b633634..e8230020 100644
--- a/src/app/api/admin/reports/route.ts
+++ b/src/app/api/admin/reports/route.ts
@@ -1,5 +1,5 @@
import { connection } from "next/server";
-import { adminAccess, auditRead } from "@/server/admin-tokens";
+import { actorHas, adminAccess, auditRead } from "@/server/admin-tokens";
import { listReports } from "@/server/moderation";
const NO_STORE = { "Cache-Control": "no-store" };
@@ -16,5 +16,8 @@ export async function GET(request: Request) {
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 });
+ // Reporters' emails only with accounts:read (the owner always).
+ const emails = actorHas(access.actor, "accounts:read");
+ const items = listReports(limit).map((r) => (emails ? r : { ...r, reporter: { ...r.reporter, email: null } }));
+ return Response.json({ items }, { headers: NO_STORE });
}
diff --git a/src/components/admin-tokens.tsx b/src/components/admin-tokens.tsx
index 19ae7764..d32e1773 100644
--- a/src/components/admin-tokens.tsx
+++ b/src/components/admin-tokens.tsx
@@ -74,6 +74,7 @@ const ACTION_WORDS: Record<string, string> = {
"worker.alert": "A worker's token was used from somewhere new",
"queue.settings": "Changed the queue's settings",
"settings.comfy_where": "Changed where ComfyUI runs",
+ "runs.content": "Read an account's prompts and results",
"token.create": "Made an admin token",
"token.revoke": "Revoked an admin token",
"token.revoke_all": "Revoked every admin token",
diff --git a/src/server/account-admin.ts b/src/server/account-admin.ts
index 2b26d203..f657746f 100644
--- a/src/server/account-admin.ts
+++ b/src/server/account-admin.ts
@@ -148,8 +148,47 @@ function withStates(outputs: OutputFile[]): (OutputFile & { state: OutputState }
});
}
-/** 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 } {
+/**
+ * A run with its content left out (what a reader without outputs:view gets): when, which model and app, how it ended and
+ * how many results, never its prompt, its inputs, its results' files or words, or its technical reason.
+ */
+export type AccountRunFacts = Pick<
+ AccountRun,
+ "id" | "batchId" | "feature" | "presetId" | "presetName" | "modelId" | "modelName" | "engine" | "provider" | "op" | "kind" | "status" | "progress" | "costUsd" | "createdAt" | "updatedAt" | "completedAt" | "place" | "account"
+> & { outputs: { kind: OutputFile["kind"]; state: OutputState }[] };
+
+function factsOnly(r: AccountRun): AccountRunFacts {
+ return {
+ id: r.id,
+ batchId: r.batchId,
+ feature: r.feature,
+ presetId: r.presetId,
+ presetName: r.presetName,
+ modelId: r.modelId,
+ modelName: r.modelName,
+ engine: r.engine,
+ provider: r.provider,
+ op: r.op,
+ kind: r.kind,
+ status: r.status,
+ progress: r.progress,
+ costUsd: r.costUsd,
+ createdAt: r.createdAt,
+ updatedAt: r.updatedAt,
+ completedAt: r.completedAt,
+ ...(r.place && { place: r.place }),
+ account: r.account,
+ outputs: r.outputs.map((x) => ({ kind: x.kind, state: x.state })),
+ };
+}
+
+/**
+ * One page of accounts' runs, newest first, and the cursor of the next (null on the last page). Never the owner's.
+ * `show.content` false: each run's facts only (factsOnly); `show.emails` false: no account's email.
+ */
+export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: string | null };
+export function listAccountRuns(o: ListOptions, show: { content: boolean; emails: boolean }): { items: (AccountRun | AccountRunFacts)[]; next: string | null };
+export function listAccountRuns(o: ListOptions, show: { content: boolean; emails: boolean } = { content: true, emails: true }): { items: (AccountRun | AccountRunFacts)[]; next: string | null } {
const limit = o.limit ?? RUNS_PAGE;
const opts: ListOptions = o.account ? { ...o, accounts: undefined, limit } : { ...o, account: undefined, accounts: true, limit };
const emails = new Map(listAccounts().map((a) => [a.id, a.email]));
@@ -163,7 +202,10 @@ export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: st
return e && e !== g.error ? { detail: e } : {};
};
return {
- items: found.map((g) => ({ ...g, outputs: withStates(g.outputs), account: { id: g.request.account!, email: emails.get(g.request.account!) ?? null }, ...detail(g) })),
+ items: found.map((g) => {
+ const run: AccountRun = { ...g, outputs: withStates(g.outputs), account: { id: g.request.account!, email: show.emails ? (emails.get(g.request.account!) ?? null) : null }, ...detail(g) };
+ return show.content ? run : factsOnly(run);
+ }),
next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,
};
}
diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.ts
index d27e3058..3c57b08b 100644
--- a/src/server/admin-tokens.ts
+++ b/src/server/admin-tokens.ts
@@ -42,12 +42,12 @@ 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:read": "See accounts' runs: when, which model and how they ended (their prompts and results need Open accounts' files; emails need See accounts)",
"runs:delete": "Delete accounts' runs",
- "outputs:view": "Open accounts' files",
+ "outputs:view": "Open accounts' files, and read their runs' prompts and results",
"outputs:hide": "Hide results",
"outputs:moderate": "Hide, show again and remove results",
- "reports:read": "See reports",
+ "reports:read": "See reports (reporters' emails need See accounts)",
"workers:read": "See 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)",
@@ -56,8 +56,8 @@ export const SCOPE_LABELS: Record<Scope, string> = {
"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"];
+/** The Settings preset that only reads: no emails, no prompts and no results (those need their own scopes). */
+export const READ_ONLY_SCOPES: Scope[] = ["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}$/;
@@ -345,7 +345,7 @@ function auditOnce(key: string, windowMs: number, actor: Actor, action: string,
}
/** 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"];
+export const READ_ACTIONS = ["accounts.list", "accounts.csv", "account.read", "runs.list", "runs.content", "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 {
@@ -353,10 +353,22 @@ export function auditRead(actor: Actor, action: string, detail: Record<string, u
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. */
+/** May this actor do what `scope` allows (the owner may do everything)? */
+export const actorHas = (actor: Actor, scope: Scope): boolean => actor.kind === "owner" || actor.scopes.includes(scope);
+
+/**
+ * A read of accounts' content (their runs' prompts and results), by the owner or a token: one row per reader, action and
+ * account every 10 minutes, with the account as the row's target, so the log says whose content was read.
+ */
+export function auditContentRead(actor: Actor, action: string, accounts: Iterable<string>, detail: Record<string, unknown> | null = null): void {
+ const who = actor.kind === "token" ? actor.id : "owner";
+ for (const account of new Set(accounts)) auditOnce(`content:${who}:${action}:${account}`, 10 * MINUTE, actor, action, account, detail, 200);
+}
+
+/** A stored file of an account's was opened (by a token or the owner): one row per reader and file every hour. */
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, ...(held && { held: true }) }, 200);
+ const who = actor.kind === "token" ? actor.id : "owner";
+ auditOnce(`file:${who}:${path}`, 60 * MINUTE, actor, "file.view", path, { account, ...(held && { held: true }) }, 200);
}
export interface AuditQuery {
diff --git a/src/server/share-access.ts b/src/server/share-access.ts
index fdf36c35..864385f7 100644
--- a/src/server/share-access.ts
+++ b/src/server/share-access.ts
@@ -95,7 +95,8 @@ export function findShare(token: string, now = Date.now()): ShareRow | null {
export const NOT_TRASHED = "NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = g.id)";
const TARGET: Record<ShareKind, string | null> = {
- result: `SELECT 1 FROM generations g WHERE g.id = ? AND g.status = 'succeeded' AND ${NOT_TRASHED}`,
+ // The owner's own results only: an account's run is never shared, whoever asks.
+ result: `SELECT 1 FROM generations g WHERE g.id = ? AND g.status = 'succeeded' AND ${NOT_TRASHED} AND json_extract(g.request_json, '$.account') IS NULL`,
folder: "SELECT 1 FROM folders WHERE id = ?",
cinema: "SELECT 1 FROM cinema_projects WHERE id = ?",
publish: null,
diff --git a/src/server/shares.ts b/src/server/shares.ts
index 521d438b..1cfaff0d 100644
--- a/src/server/shares.ts
+++ b/src/server/shares.ts
@@ -52,7 +52,8 @@ const MAX_TITLE = 120;
const MAX_DESCRIPTION = 1000;
const HELPER_SQL = `(g.feature LIKE '%${HELPER_SUFFIX}' OR g.feature IN (${HELPER_FEATURES.map((f) => `'${f}'`).join(", ")}))`;
-const SHOWN = `g.status = 'succeeded' AND g.outputs_json != '[]' AND ${NOT_TRASHED}`;
+/** A finished result with outputs, not in the Trash, and the owner's own (an account's run is never on a link). */
+const SHOWN = `g.status = 'succeeded' AND g.outputs_json != '[]' AND ${NOT_TRASHED} AND json_extract(g.request_json, '$.account') IS NULL`;
const COLUMNS = "g.*, NULL AS deleted_at, NULL AS folder_id";
type GenRow = Parameters<typeof toGeneration>[0];
diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.ts
index b0debc60..0671de9a 100644
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@ -538,3 +538,79 @@ describe("admin tokens: runs, the log's changes and every admin route", () => {
}
});
});
+
+describe("admin tokens: accounts' content needs its own scopes", () => {
+ /** An account's finished run with a prompt and a stored result, and a report from it. */
+ function accountRun() {
+ const a = auth.createAccount(`content-${++n}@example.com`, "long enough");
+ const file = saveFile({ data: TINY_PNG, contentType: "image/png", source: "generation", accountId: a.id });
+ const id = `content-run-${n}`;
+ const now = Date.now();
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, prompt, request_json, outputs_json, created_at, updated_at, completed_at) VALUES (?, 'image', 'oss-z-image-turbo', 'open', 'comfyui', 't2i', 'image', 'succeeded', ?, ?, ?, ?, ?, ?)",
+ )
+ .run(id, "a private prompt", JSON.stringify({ account: a.id, feature: "image", modelId: "oss-z-image-turbo", prompt: "a private prompt" }), JSON.stringify([{ url: file.url, kind: "image", contentType: "image/png" }]), now, now, now);
+ return { account: a, id };
+ }
+ type Page = { items: { id: string; prompt?: string; request?: unknown; outputs: { url?: string; state: string }[]; account: { id: string; email: string | null } }[] };
+ const runsOf = async (token?: string, cookie?: string) => (await (await routes.runs.GET(req("/api/admin/generations?limit=100", { token, cookie }))).json()) as Page;
+
+ it("runs:read alone gets each run's facts: no prompt, no request, no result file, no email", async () => {
+ const r = accountRun();
+ const page = await runsOf(make(["runs:read"]).token);
+ const run = page.items.find((x) => x.id === r.id)!;
+ expect(run).toBeDefined();
+ expect(run.prompt).toBeUndefined();
+ expect(run.request).toBeUndefined();
+ expect(run.outputs).toEqual([{ kind: "image", state: "shown" }]);
+ expect(run.account).toEqual({ id: r.account.id, email: null });
+ expect(JSON.stringify(page)).not.toContain("a private prompt");
+ });
+
+ it("outputs:view adds the content and accounts:read the email; the owner sees both", async () => {
+ const r = accountRun();
+ const withContent = (await runsOf(make(["runs:read", "outputs:view"]).token)).items.find((x) => x.id === r.id)!;
+ expect(withContent.prompt).toBe("a private prompt");
+ expect(withContent.outputs[0].url).toMatch(/^\/api\/files\//);
+ expect(withContent.account.email).toBeNull();
+ const withEmail = (await runsOf(make(["runs:read", "accounts:read"]).token)).items.find((x) => x.id === r.id)!;
+ expect(withEmail.account.email).toBe(r.account.email);
+ expect(withEmail.prompt).toBeUndefined();
+ const owner = (await runsOf(undefined, ownerCookie)).items.find((x) => x.id === r.id)!;
+ expect(owner.prompt).toBe("a private prompt");
+ expect(owner.account.email).toBe(r.account.email);
+ });
+
+ it("every read of an account's content is logged with the account as its target, the owner's reads too", async () => {
+ const r = accountRun();
+ const before = auditRows().length;
+ await runsOf(undefined, ownerCookie);
+ const rows = auditRows().slice(before);
+ expect(rows.some((x) => x.action === "runs.content" && x.actor === "owner" && x.target === r.account.id)).toBe(true);
+ // Facts only: no content read to log.
+ const facts = make(["runs:read"]);
+ const mark = auditRows().length;
+ await runsOf(facts.token);
+ expect(auditRows().slice(mark).some((x) => x.action === "runs.content")).toBe(false);
+ // The owner opening an account's file is logged too.
+ const file = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", accountId: r.account.id });
+ const rel = file.url.replace(/^\/api\/files\//, "");
+ const res = await routes.files.GET(req(`/api/admin/files/${rel}`, { cookie: ownerCookie }), ctx({ path: rel.split("/") }));
+ expect(res.status).toBe(200);
+ await res.arrayBuffer();
+ expect(auditRows().some((x) => x.action === "file.view" && x.actor === "owner" && JSON.parse(x.detail_json!).account === r.account.id)).toBe(true);
+ });
+
+ it("reporters' emails need accounts:read, and the read-only preset holds no email or content scope", async () => {
+ db()
+ .prepare("INSERT INTO reports_inbox (id, target_json, category, text, reporter, created_at) VALUES (?, ?, 'other', 'words', ?, ?)")
+ .run(`rep-${++n}`, JSON.stringify({ kind: "share", id: "x" }), JSON.stringify({ account: "acct-x", email: "[email protected]" }), Date.now());
+ const plain = (await (await routes.reports.GET(req("/api/admin/reports", { token: make(["reports:read"]).token }))).json()) as { items: { reporter: { email: string | null } }[] };
+ expect(plain.items[0].reporter.email).toBeNull();
+ const withEmail = (await (await routes.reports.GET(req("/api/admin/reports", { token: make(["reports:read", "accounts:read"]).token }))).json()) as { items: { reporter: { email: string | null } }[] };
+ expect(withEmail.items[0].reporter.email).toBe("[email protected]");
+ expect(admin.READ_ONLY_SCOPES).not.toContain("accounts:read");
+ expect(admin.READ_ONLY_SCOPES).not.toContain("outputs:view");
+ });
+});
diff --git a/tests/share-links.test.ts b/tests/share-links.test.ts
index 892956f7..88703020 100644
--- a/tests/share-links.test.ts
+++ b/tests/share-links.test.ts
@@ -295,6 +295,19 @@ describe("what a token serves", () => {
expect((await serve(S3.token, r3.rel)).status).toBe(200);
});
+ it("never puts an account's run on a link: not as a result, not in a selection, not in a folder", async () => {
+ const theirs = made("an account's harbour");
+ db().prepare("UPDATE generations SET request_json = json_set(request_json, '$.account', 'acct-someone') WHERE id = ?").run(theirs.g.id);
+ expect(() => shares.createShare({ kind: "result", targetId: theirs.g.id })).toThrow();
+ expect(() => shares.createShare({ kind: "publish", items: [theirs.g.id] })).toThrow();
+ const folder = lib.createFolder({ name: "Mixed" });
+ const mine = made("the owner's harbour");
+ lib.moveToFolder([theirs.g.id, mine.g.id], folder.id);
+ const S = shares.createShare({ kind: "folder", targetId: folder.id });
+ expect((await serve(S.token, mine.rel)).status).toBe(200);
+ expect((await serve(S.token, theirs.rel)).status).toBe(404);
+ });
+
it("shares a folder with its subfolders, without the Trash or helper steps", async () => {
const top = lib.createFolder({ name: "Shared top" });
const sub = lib.createFolder({ name: "Shared sub", parentId: top.id });