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.

Workers: token lifetime with the next token in the beat answer, alerts on where a token is used

Adarshfe47b6ca5277
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.md
index 6f140447..3403cdfa 100644
--- a/docs/SELF-HOSTING.md
+++ b/docs/SELF-HOSTING.md
@@ -117,6 +117,7 @@ Don't copy `auth.json.migrated-<…>` back instead. It lacks the accounts made s
| `FUOBE_HOSTED_RUNS=1` | With public sign-up: accounts with no GPU of their own may run on this install's GPUs: its workers, or its own ComfyUI when that is on this machine ([Hosted runs](public-signup.md#hosted-runs)). Off by default. A billing service or `FUOBE_HOSTED_FREE=1` must answer for these runs |
| `FUOBE_HOSTED_FREE=1` | With no billing service: hosted runs are free for every account, within the install's own limits. Without it (and without a billing service) hosted runs stay closed |
| `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line before a GPU first takes it, in minutes (default `30`) |
+| `FUOBE_WORKER_TOKEN_DAYS` | How many days a pool worker's token lasts; the worker gets its next one in a beat answer ([gpu-workers.md](gpu-workers.md#the-protocol)). Unset or `0`: tokens never expire |
| `FUOBE_BILLING_URL`, `FUOBE_BILLING_TOKEN` | An optional external billing service for hosted runs ([billing-hook.md](billing-hook.md)). None: hosted runs are closed, or free with `FUOBE_HOSTED_FREE=1` |
| `FUOBE_MODERATION_URL`, `FUOBE_MODERATION_TOKEN`, `FUOBE_MODERATION_MAX_WAIT_H` | An optional external moderation service ([moderation-hook.md](moderation-hook.md)). None: nothing is checked |
diff --git a/docs/admin-api.md b/docs/admin-api.md
index d3c4ecfd..75bced2f 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -117,14 +117,17 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `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 }`.
+A log row is `{ id, at, actor: "owner" | "token" | "system", 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`, `queue.settings` (with the values before and after), `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.
+`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
+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
the server's own log notes the missing row.
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index ccce1c40..514f9bb2 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -35,7 +35,9 @@ You do not need a start flag or a guard file. In the studio, **Connect your GPU*
gets a worker token (`fuobe_wkr_…`). The studio makes the token at that moment and keeps only its SHA-256 hash.
The token acts only as that person's own computer. The ComfyUI gets that person's jobs, and nobody else's. The jobs
-run with no Fuobe tab open. The person can disconnect the ComfyUI in Settings → Your GPU (`DELETE /api/gpu/paired/<id>`)
+run with no Fuobe tab open. The owner's pairing never changes where the studio's ComfyUI jobs run: the paired
+ComfyUI takes the owner's jobs once the owner chooses the computer in Settings → ComfyUI. Every change of that setting
+is in the admin log (`settings.comfy_where`, with the value before and after). The person can disconnect the ComfyUI in Settings → Your GPU (`DELETE /api/gpu/paired/<id>`)
or press Disconnect in ComfyUI (`POST /api/gpu/computer/unpair`). A disconnected token gets 401 at its next call.
## Workers (the owner's shared GPUs)
@@ -201,9 +203,23 @@ Every worker call carries `Authorization: Bearer fuobe_wkr_…`. A worker token
gets 403 everywhere else. It is never the owner, and an owner API token can never act as a worker. The studio reads the
token on every call, so a revoked token stops at once.
+**A token's lifetime.** With `FUOBE_WORKER_TOKEN_DAYS` set (unset or 0: a token never expires, as before), a pool
+worker's token lasts that many days. Once half of it is gone, the beat answer of a worker that speaks protocol 2 gives
+it the next token (`worker.token: { value, expiresAt }`). The worker saves it and uses it from its next call on. The old
+token stops at the new one's first use. A next token that is never used is given again, as a new one, after 10
+minutes. A paired ComfyUI's token keeps no lifetime. Set the lifetime only once every worker speaks protocol 2: an
+older worker's token would simply expire.
+
+**Where a token is used from.** For a pool worker, the studio remembers the countries (Cloudflare's `cf-ipcountry`)
+and the networks (an IPv4 address's /24 or an IPv6 address's /64, read only with `FUOBE_TRUST_PROXY=1`) its token was
+used from, as short hashes, never as addresses. A call from a new country or a new network, and calls from two networks
+within 10 minutes of each other, each write an alert to the admin log (`worker.alert`, actor `system`, the worker as
+its target), at most once an hour each.
+
- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, local: { paused, why, until }, gpu: {
otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,
- insideHours, nextChangeAt, lanes, minProtocol, sendInventory }` and `claimableNow`: how many people's jobs (an
+ insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token? }` (`token`: the next token, above) and
+ `claimableNow`: how many people's jobs (an
account's, never the owner's) this worker may claim right now by its lanes, files, VRAM and hours, its own pause aside.
- `PUT /api/gpu/computer/inventory`: `{ files: [{ folder, name, size, sha256 }], nodePacks: [{ name, commit }] }` →
`{ lanes, workflows, missing }`.
diff --git a/src/app/api/gpu/pair/route.ts b/src/app/api/gpu/pair/route.ts
index 09c3f0a2..0ef1deb7 100644
--- a/src/app/api/gpu/pair/route.ts
+++ b/src/app/api/gpu/pair/route.ts
@@ -2,6 +2,7 @@ import { connection } from "next/server";
import { pairingPrincipal, runOnComputer } from "@/server/computer/pairing-http";
import { approvePairing, denyPairing, normaliseCode, pairingByCode } from "@/server/computer/workers";
import { hit } from "@/server/rate";
+import { getSetting } from "@/server/settings";
/** Codes a person may look up or answer in 10 minutes (a code is 8 characters from 31: guessing one is hopeless). */
const LOOKUPS = 30;
@@ -43,5 +44,7 @@ export async function POST(request: Request) {
const a = approvePairing(String(body?.code ?? ""), principal);
if (!a) return Response.json({ error: GONE }, { status: 404, headers: { "Cache-Control": "no-store" } });
runOnComputer(principal);
- return Response.json({ ok: true, worker: { id: a.workerId, name: a.name } }, { headers: { "Cache-Control": "no-store" } });
+ // The owner's pairing never moves the studio's jobs: the owner chooses the computer in Settings.
+ const settingsNeeded = principal === "owner" && getSetting("comfyWhere") !== "computer";
+ return Response.json({ ok: true, worker: { id: a.workerId, name: a.name }, ...(settingsNeeded && { settingsNeeded: true }) }, { headers: { "Cache-Control": "no-store" } });
}
diff --git a/src/components/admin-tokens.tsx b/src/components/admin-tokens.tsx
index 22579a41..19ae7764 100644
--- a/src/components/admin-tokens.tsx
+++ b/src/components/admin-tokens.tsx
@@ -40,7 +40,7 @@ interface AdminTokensAnswer {
interface AuditRow {
id: number;
at: number;
- actor: "owner" | "token";
+ actor: "owner" | "token" | "system";
token: { id: string; name: string } | null;
action: string;
target: string | null;
@@ -71,6 +71,9 @@ const ACTION_WORDS: Record<string, string> = {
"worker.change": "Changed a worker",
"worker.rotate": "Gave a worker a new token",
"worker.revoke": "Revoked a worker",
+ "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",
"token.create": "Made an admin token",
"token.revoke": "Revoked an admin token",
"token.revoke_all": "Revoked every admin token",
@@ -274,7 +277,7 @@ function AdminLog() {
{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)}
+ {r.actor === "token" ? (r.token?.name ?? "A token") : r.actor === "system" ? "The studio" : "You"} · {timeAgo(r.at)}
</span>
</li>
))}
diff --git a/src/components/gpu/fuobe-connect.tsx b/src/components/gpu/fuobe-connect.tsx
index b0fdcc13..a6d87bb9 100644
--- a/src/components/gpu/fuobe-connect.tsx
+++ b/src/components/gpu/fuobe-connect.tsx
@@ -92,7 +92,7 @@ export function PairWithCode({ initial, className }: { initial?: string; classNa
const [typed, setTyped] = useState(initial ?? "");
const code = pairCode(typed);
const [found, setFound] = useState<{ code: string; name: string; facts: PairedComfy["facts"] } | null>(null);
- const [approved, setApproved] = useState<{ id: string; name: string } | null>(null);
+ const [approved, setApproved] = useState<{ id: string; name: string; settingsNeeded?: boolean } | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const paired = usePaired(!!approved, !!approved);
@@ -129,8 +129,8 @@ export function PairWithCode({ initial, className }: { initial?: string; classNa
setTyped("");
toast("That code won't work now.");
} else {
- const r = await pairCall<{ worker: { id: string; name: string } }>("POST", "/api/gpu/pair", { code: found.code });
- setApproved(r.worker);
+ const r = await pairCall<{ worker: { id: string; name: string }; settingsNeeded?: boolean }>("POST", "/api/gpu/pair", { code: found.code });
+ setApproved({ ...r.worker, ...(r.settingsNeeded && { settingsNeeded: true }) });
}
} catch (e) {
setError((e as Error).message);
@@ -139,6 +139,15 @@ export function PairWithCode({ initial, className }: { initial?: string; classNa
}
};
+ if (approved?.settingsNeeded)
+ return (
+ <div className={cn("space-y-1 rounded-xl bg-brand-faint p-3 text-[13px]", className)}>
+ <p className="flex items-center gap-2 font-medium">
+ <Check className="size-4 text-brand-text" /> {approved.name} is paired.
+ </p>
+ <p className="text-muted-foreground">To run the studio&apos;s ComfyUI jobs there, choose your computer in Settings → ComfyUI.</p>
+ </div>
+ );
if (approved)
return (
<div className={cn("space-y-1 rounded-xl bg-brand-faint p-3 text-[13px]", className)}>
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index 99a3148c..8edd5961 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -174,6 +174,11 @@ export interface WorkerAnswer {
minProtocol: number;
/** Its inventory is unknown or changed: send it (PUT /api/gpu/computer/inventory). */
sendInventory: boolean;
+ /**
+ * Its next token (protocol 2), when its token has a lifetime and half of it is gone: save it and use it from the next
+ * call on. The old token stops at the new one's first use. Given again after 10 minutes if it was never used.
+ */
+ token?: { value: string; expiresAt: number };
}
/** What a worker says in its beat, on top of a browser's. */
diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.ts
index 172659a3..d27e3058 100644
--- a/src/server/admin-tokens.ts
+++ b/src/server/admin-tokens.ts
@@ -299,7 +299,8 @@ export function ownerBrowser(request: Request): boolean {
export interface AuditRow {
id: number;
at: number;
- actor: "owner" | "token";
+ /** "system": the studio itself (an alert about a worker's token). */
+ actor: "owner" | "token" | "system";
token: { id: string; name: string } | null;
action: string;
target: string | null;
@@ -361,7 +362,7 @@ export function auditFileView(actor: Actor, path: string, account: string, held
export interface AuditQuery {
before?: number;
limit: number;
- actor?: "owner" | "token";
+ actor?: "owner" | "token" | "system";
token?: string;
action?: string;
/** Changes only: no reads, file views or refusals. */
@@ -376,7 +377,7 @@ export function auditQueryFrom(sp: URLSearchParams): AuditQuery | { error: strin
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" };
+ if (actor !== null && actor !== "owner" && actor !== "token" && actor !== "system") return { error: "actor is owner, token or system" };
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");
@@ -407,7 +408,7 @@ export function listAudit(q: AuditQuery): { items: AuditRow[]; next: string | nu
const items = rows.map((r) => ({
id: r.id,
at: r.at,
- actor: r.actor === "token" ? ("token" as const) : ("owner" as const),
+ actor: r.actor === "token" ? ("token" as const) : r.actor === "system" ? ("system" as const) : ("owner" as const),
token: r.token_id ? { id: r.token_id, name: r.token_name ?? "" } : null,
action: r.action,
target: r.target,
diff --git a/src/server/computer/http.ts b/src/server/computer/http.ts
index 0e3142e1..8855649c 100644
--- a/src/server/computer/http.ts
+++ b/src/server/computer/http.ts
@@ -3,7 +3,7 @@ import fs from "node:fs";
import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE, GUEST_HEADER, GUEST_RUN_MESSAGE } from "@/lib/guest-access";
import type { WantedFile } from "@/lib/relay";
import { sniffMedia } from "@/lib/sniff";
-import { accountById, accountGpu, authEnabled, crossSite, hostAllowed, publicSignup, requestViewer, validToken } from "../auth";
+import { accountById, accountGpu, authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, requestViewer, validToken } from "../auth";
import { hit } from "../rate";
import { getSetting } from "../settings";
import { RelayError, type Principal } from "./tasks";
@@ -44,7 +44,7 @@ export function principalOf(request: Request): Principal | Response {
* request can't change that.
*/
function workerPrincipal(request: Request, auth: string, no: (status: number, error: string, extra?: Record<string, unknown>) => Response): Principal | Response {
- const w = workerFromAuth(auth, request.headers.get("cf-ipcountry"));
+ const w = workerFromAuth(auth, { country: request.headers.get("cf-ipcountry"), network: callNetwork(request) });
if (!w) return no(401, "This ComfyUI isn't paired with this studio any more. Pair it again from Fuobe Connect.", { code: "worker-token" });
const host = request.headers.get("host") ?? new URL(request.url).host;
if (!authEnabled() && !hostAllowed(host)) return no(403, "Blocked a request for an address this studio isn't reached at.");
@@ -64,6 +64,17 @@ function workerPrincipal(request: Request, auth: string, no: (status: number, er
return w.principal as Principal;
}
+/**
+ * The network a call came from (an IPv4 address's /24, an IPv6 address's /64), or null when the proxy isn't trusted and
+ * every client looks the same.
+ */
+export function callNetwork(request: Request): string | null {
+ const key = LoginGuard.clientKey(request.headers);
+ if (key === LoginGuard.DIRECT) return null;
+ const v4 = key.split(".");
+ return v4.length === 4 ? `${v4.slice(0, 3).join(".")}.0/24` : key;
+}
+
/** The worker that made a request, once principalOf has read it (null: a browser). */
const workerOfRequest = new WeakMap<Request, WorkerRow>();
export const requestWorker = (request: Request): WorkerRow | null => workerOfRequest.get(request) ?? null;
diff --git a/src/server/computer/pairing-http.ts b/src/server/computer/pairing-http.ts
index 22448dc8..de73a452 100644
--- a/src/server/computer/pairing-http.ts
+++ b/src/server/computer/pairing-http.ts
@@ -2,7 +2,6 @@ import "server-only";
import { clearAccountLoras } from "../account-loras";
import { accountGpu, requestViewer, setAccountGpu } from "../auth";
import { dropSnapshots } from "../gpu/snapshots";
-import { getSetting, setSetting } from "../settings";
import type { Principal } from "./tasks";
const no = (status: number, error: string) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } });
@@ -21,13 +20,11 @@ export function pairingPrincipal(request: Request): Principal | Response {
/**
* A paired ComfyUI runs the person's jobs as their own computer does: an account's GPU becomes "this computer" (as when
- * its browser connects), and the owner's ComfyUI runs on the owner's computer.
+ * its browser connects). The owner's pairing changes nothing of where the studio's ComfyUI jobs run: that stays the
+ * owner's choice in Settings (a pairing link anyone can start must never move the studio's jobs).
*/
export function runOnComputer(principal: Principal): void {
- if (principal === "owner") {
- if (getSetting("comfyWhere") !== "computer") setSetting("comfyWhere", "computer");
- return;
- }
+ if (principal === "owner") return;
const id = principal.slice(5);
if (accountGpu(id)?.mode !== "computer") {
setAccountGpu(id, { mode: "computer" });
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 67f30caa..69fcedc5 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -7,7 +7,7 @@ import { db } from "../db";
import { loadIndex } from "../gpu/index-file";
import { cleanFacts, endTask, json, logWorkerJob, noteProgress, setPoolClocks, setTask, takeTask, taskById, type TaskRow } from "./tasks";
import { queueSettings, runCeilingMs } from "../queue-settings";
-import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
+import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
/**
* Workers (docs/gpu-workers.md): the owner's GPUs on other machines, each running `fuobe worker`, which pulls jobs from
@@ -179,6 +179,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
}
const state = workerState(fresh, now);
d.prepare("UPDATE relay_workers SET state = ? WHERE id = ?").run(state.state, w.id);
+ // A worker that can save a new token (protocol 2) gets its next one when half its token's life is gone.
+ const nextToken = b.protocol >= 2 ? offerNextToken(fresh, now) : null;
const h = hoursAt(hoursOf(fresh), now);
// Pool names are validated at creation (/^[a-z0-9-]{1,32}$/), so they never contain commas. INSTR on the
// CSV avoids the LIKE-wildcard class of risk (%, _) entirely.
@@ -199,6 +201,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
lanes: Object.keys(allowOf(fresh)),
minProtocol: MIN_PROTOCOL,
sendInventory: !fresh.inventory_hash || fresh.inventory_hash !== b.inventoryHash,
+ ...(nextToken && { token: nextToken }),
},
};
})();
diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.ts
index ff37527d..7b86c08b 100644
--- a/src/server/computer/workers.ts
+++ b/src/server/computer/workers.ts
@@ -60,6 +60,15 @@ export interface WorkerRow {
switch_after_ms: number;
state: string;
seen_at: number | null;
+ /** A pool worker's next token (its SHA-256), offered in a beat answer and not used yet; its expiry; when it was made. */
+ next_token_hash?: string | null;
+ next_expires_at?: number | null;
+ next_token_at?: number | null;
+ /** The countries and networks (as short hashes) a pool worker's token was used from. */
+ seen_json?: string | null;
+ /** The network (a short hash) of its last call, and when. */
+ last_network?: string | null;
+ last_net_at?: number | null;
}
const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
@@ -73,22 +82,126 @@ export const isWorkerAuth = (header: string | null | undefined): boolean => !!he
const touched = new Map<string, number>();
/**
- * The worker behind an Authorization header, read now: null when the token is unknown, revoked or expired. Records
- * when it was last used (at most every 30 s) and Cloudflare's country header.
+ * How long a pool worker's token lasts (FUOBE_WORKER_TOKEN_DAYS; unset or 0: it never expires, as before). With a
+ * lifetime, the beat answer gives a worker that speaks protocol 2 its next token once half of it is gone, and the old
+ * token stops the moment the new one is first used.
*/
-export function workerFromAuth(header: string | null | undefined, country?: string | null, now = Date.now()): WorkerRow | null {
+export function poolTokenMs(): number {
+ const days = Number(process.env.FUOBE_WORKER_TOKEN_DAYS);
+ return Number.isFinite(days) && days > 0 ? Math.min(days, 3650) * 24 * 60 * 60_000 : 0;
+}
+
+/** A next token not used this long after it was offered is offered again (a beat answer that never arrived). */
+const NEXT_TOKEN_RETRY_MS = 10 * 60_000;
+/** Calls from two networks this close together are "two sources". */
+const TWO_SOURCES_MS = 10 * 60_000;
+/** Countries and networks remembered per worker. */
+const SEEN_MAX = 16;
+
+/** Where a call came from: Cloudflare's country header and the client's network (when the proxy is trusted). */
+export interface CallSource {
+ country?: string | null;
+ network?: string | null;
+}
+
+/**
+ * The worker behind an Authorization header, read now: null when the token is unknown, revoked or expired. A pool
+ * worker's next token (offered in a beat answer) works too, and its first use makes it the token: the old one stops.
+ * Records when it was last used (at most every 30 s) and Cloudflare's country header. For a pool worker, a call from a
+ * country or a network its token never came from before, or from a second network within minutes of another, writes an
+ * alert to the admin log.
+ */
+export function workerFromAuth(header: string | null | undefined, from: CallSource | string | null = null, now = Date.now()): WorkerRow | null {
const m = BEARER_WORKER.exec((header ?? "").trim());
if (!m || !WORKER_TOKEN.test(m[1])) return null;
- const row = db().prepare("SELECT * FROM relay_workers WHERE token_hash = ?").get(sha(m[1])) as WorkerRow | undefined;
+ const source: CallSource = typeof from === "string" ? { country: from } : (from ?? {});
+ const hash = sha(m[1]);
+ let row = db().prepare("SELECT * FROM relay_workers WHERE token_hash = ?").get(hash) as WorkerRow | undefined;
+ if (!row) row = promoteNextToken(hash, now);
if (!row || row.revoked_at || (row.expires_at && row.expires_at <= now)) return null;
+ const country = source.country && /^[A-Z]{2}$/.test(source.country) ? source.country : null;
+ if (row.kind === "pool") noteSource(row, country, source.network ?? null, now);
if (now - (touched.get(row.id) ?? 0) > 30_000) {
touched.set(row.id, now);
- const c = country && /^[A-Z]{2}$/.test(country) ? country : null;
- db().prepare("UPDATE relay_workers SET last_used_at = ?, last_country = COALESCE(?, last_country) WHERE id = ?").run(now, c, row.id);
+ db().prepare("UPDATE relay_workers SET last_used_at = ?, last_country = COALESCE(?, last_country) WHERE id = ?").run(now, country, row.id);
}
return row;
}
+/** A pool worker's next token, used for the first time: it becomes the token, with its own expiry. */
+function promoteNextToken(hash: string, now: number): WorkerRow | undefined {
+ const d = db();
+ return d.transaction(() => {
+ const w = d.prepare("SELECT * FROM relay_workers WHERE next_token_hash = ? AND kind = 'pool' AND revoked_at IS NULL").get(hash) as WorkerRow | undefined;
+ if (!w || (w.next_expires_at && w.next_expires_at <= now)) return undefined;
+ d.prepare("UPDATE relay_workers SET token_hash = next_token_hash, expires_at = next_expires_at, next_token_hash = NULL, next_expires_at = NULL, next_token_at = NULL WHERE id = ?").run(w.id);
+ return d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+ })();
+}
+
+/**
+ * A pool worker's next token for its beat answer, when its token has a lifetime and half of it is gone (made now; only its
+ * hash is kept). Null otherwise, and while one offered in the last 10 minutes waits for its first use.
+ */
+export function offerNextToken(w: WorkerRow, now = Date.now()): { value: string; expiresAt: number } | null {
+ const life = poolTokenMs();
+ if (w.kind !== "pool" || w.revoked_at || !life || !w.expires_at) return null;
+ if (w.expires_at - now > life / 2) return null;
+ if (w.next_token_hash && w.next_token_at && now - w.next_token_at < NEXT_TOKEN_RETRY_MS) return null;
+ const value = newWorkerToken();
+ const expiresAt = now + life;
+ db().prepare("UPDATE relay_workers SET next_token_hash = ?, next_expires_at = ?, next_token_at = ? WHERE id = ? AND revoked_at IS NULL").run(sha(value), expiresAt, now, w.id);
+ return { value, expiresAt };
+}
+
+/** A short hash of a network, so the admin log and the worker's row never hold an address. */
+const netHash = (network: string) => sha(`network:${network}`).slice(0, 16);
+
+/** One alert per worker and kind an hour (a worker that moved keeps calling from its new place). */
+const alerted = new Map<string, number>();
+
+/** An alert about a worker's token in the admin log (actor "system"). */
+function workerAlert(w: WorkerRow, kind: "new-country" | "new-network" | "two-sources", detail: Record<string, unknown>, now: number): void {
+ const key = `${w.id}:${kind}:${JSON.stringify(detail)}`;
+ if (now - (alerted.get(key) ?? 0) < 60 * 60_000) return;
+ alerted.set(key, now);
+ if (alerted.size > 2000) alerted.delete(alerted.keys().next().value!);
+ try {
+ db()
+ .prepare("INSERT INTO admin_audit (at, actor, token_id, token_name, action, target, detail_json, status) VALUES (?, 'system', NULL, NULL, 'worker.alert', ?, ?, 200)")
+ .run(now, w.id, JSON.stringify({ kind, worker: w.name, ...detail }));
+ } catch (e) {
+ console.warn(`[fuobe] Couldn't write the admin log: ${(e as Error).message}`);
+ }
+ console.warn(`[fuobe] Worker ${w.name}: ${kind}`);
+}
+
+/** Remember where a pool worker's token was used from, and alert on a new country, a new network or two at once. */
+function noteSource(w: WorkerRow, country: string | null, network: string | null, now: number): void {
+ const net = network ? netHash(network) : null;
+ if (!country && !net) return;
+ const seen = json<{ countries: string[]; networks: string[] }>(w.seen_json ?? null, { countries: [], networks: [] });
+ let changed = false;
+ if (country && !seen.countries.includes(country)) {
+ if (seen.countries.length) workerAlert(w, "new-country", { country, known: seen.countries.slice(-4) }, now);
+ seen.countries = [...seen.countries, country].slice(-SEEN_MAX);
+ changed = true;
+ }
+ if (net && !seen.networks.includes(net)) {
+ if (seen.networks.length) workerAlert(w, "new-network", { network: net }, now);
+ seen.networks = [...seen.networks, net].slice(-SEEN_MAX);
+ changed = true;
+ }
+ if (net && w.last_network && w.last_network !== net && w.last_net_at && now - w.last_net_at < TWO_SOURCES_MS) {
+ workerAlert(w, "two-sources", { networks: [w.last_network, net].sort() }, now);
+ }
+ if (changed || (net && (net !== w.last_network || now - (w.last_net_at ?? 0) > 30_000))) {
+ db()
+ .prepare("UPDATE relay_workers SET seen_json = ?, last_network = COALESCE(?, last_network), last_net_at = CASE WHEN ? IS NULL THEN last_net_at ELSE ? END WHERE id = ?")
+ .run(JSON.stringify(seen), net, net, now, w.id);
+ }
+}
+
export function getWorker(id: string): WorkerRow | null {
if (typeof id !== "string" || !/^[A-Za-z0-9_-]{8,32}$/.test(id)) return null;
return (db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(id) as WorkerRow | undefined) ?? null;
@@ -100,8 +213,9 @@ const cleanName = (name: unknown) =>
.trim()
.slice(0, 48) || "ComfyUI";
-/** A new worker and its token (the only time the token exists in the clear). */
+/** A new worker and its token (the only time the token exists in the clear). A pool worker's token lasts poolTokenMs(). */
export function createWorker(w: { name: string; kind: WorkerKind; principal?: Principal; pool?: string; facts?: ComputerFacts; expiresAt?: number }, now = Date.now()): { id: string; token: string } {
+ const life = w.kind === "pool" ? poolTokenMs() : 0;
const id = nanoid(12).replace(/[^A-Za-z0-9_-]/g, "_");
const token = newWorkerToken();
db()
@@ -117,7 +231,7 @@ export function createWorker(w: { name: string; kind: WorkerKind; principal?: Pr
w.pool ?? "pool",
sha(token),
now,
- w.expiresAt ?? null,
+ w.expiresAt ?? (life ? now + life : null),
w.facts ? JSON.stringify(w.facts) : null,
// A personal worker is that person's computer: it follows their own runs, as their tab does. A pool worker starts
// paused in both places.
@@ -133,10 +247,14 @@ export function revokeWorker(id: string, now = Date.now()): boolean {
return db().prepare("UPDATE relay_workers SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").run(now, id).changes > 0;
}
-/** A new token for a worker; the old one stops at once. */
-export function rotateWorker(id: string): string | null {
+/** A new token for a worker; the old one (and a next one offered and not used yet) stops at once. */
+export function rotateWorker(id: string, now = Date.now()): string | null {
const token = newWorkerToken();
- const ok = db().prepare("UPDATE relay_workers SET token_hash = ? WHERE id = ? AND revoked_at IS NULL").run(sha(token), id).changes > 0;
+ const life = poolTokenMs();
+ const ok =
+ db()
+ .prepare("UPDATE relay_workers SET token_hash = ?, next_token_hash = NULL, next_expires_at = NULL, next_token_at = NULL, expires_at = CASE WHEN kind = 'pool' AND ? > 0 THEN ? ELSE expires_at END WHERE id = ? AND revoked_at IS NULL")
+ .run(sha(token), life, now + life, id).changes > 0;
return ok ? token : null;
}
diff --git a/src/server/db.ts b/src/server/db.ts
index 82c73a6d..512ae259 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -996,6 +996,13 @@ const RELAY_COLUMNS: [string, string, string][] = [
["relay_tasks", "worker_id", "TEXT"],
// The class a task waits in: "paid", "free" or "owner" (pool.ts LINE_ORDER).
["relay_tasks", "class", "TEXT"],
+ // A pool worker's next token (workers.ts offerNextToken) and where its token was used from (hashed networks).
+ ["relay_workers", "next_token_hash", "TEXT"],
+ ["relay_workers", "next_expires_at", "INTEGER"],
+ ["relay_workers", "next_token_at", "INTEGER"],
+ ["relay_workers", "seen_json", "TEXT"],
+ ["relay_workers", "last_network", "TEXT"],
+ ["relay_workers", "last_net_at", "INTEGER"],
];
declare global {
diff --git a/src/server/settings.ts b/src/server/settings.ts
index 70cf5ca2..11f144b2 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -225,13 +225,25 @@ export function validateSetting(name: SettingName, value: string, from: "api" |
export function setSetting(name: SettingName, value: string): void {
validateSetting(name, value);
const def = SETTINGS[name];
- if (value === "") {
- db().prepare("DELETE FROM settings WHERE key = ?").run(def.key);
- return;
+ // Where ComfyUI runs decides whose GPUs run every job: each change is in the admin log, with the value before and after.
+ const before = name === "comfyWhere" ? getSetting("comfyWhere") : null;
+ if (value === "") db().prepare("DELETE FROM settings WHERE key = ?").run(def.key);
+ else db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(def.key, value);
+ if (name === "comfyWhere") {
+ const after = getSetting("comfyWhere");
+ if (after !== before) auditSettingChange("settings.comfy_where", { before, after });
+ }
+}
+
+/** A row in the admin log (admin_audit) for a setting the owner changed. Never fails the change. */
+function auditSettingChange(action: string, detail: Record<string, unknown>): void {
+ try {
+ db()
+ .prepare("INSERT INTO admin_audit (at, actor, token_id, token_name, action, target, detail_json, status) VALUES (?, 'owner', NULL, NULL, ?, NULL, ?, 200)")
+ .run(Date.now(), action, JSON.stringify(detail));
+ } catch (e) {
+ console.warn(`[fuobe] Couldn't write the admin log: ${(e as Error).message}`);
}
- db()
- .prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value")
- .run(def.key, value);
}
export function mask(value: string): string {
diff --git a/tests/worker-tokens.test.ts b/tests/worker-tokens.test.ts
new file mode 100644
index 00000000..a527d941
--- /dev/null
+++ b/tests/worker-tokens.test.ts
@@ -0,0 +1,139 @@
+import { afterEach, beforeAll, describe, expect, it } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Pool worker tokens: a lifetime (FUOBE_WORKER_TOKEN_DAYS, off by default) with the next token in the beat answer, the
+ * old token stopping at the new one's first use; and alerts in the admin log when a token is used from a new country, a
+ * new network, or two networks at once. The admin log and the worker's row never hold an address.
+ */
+
+const dir = tempDir("fuobe-worker-tokens-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_WORKER_TOKEN_DAYS;
+delete process.env.FUOBE_TRUST_PROXY;
+
+const { db } = await import("@/server/db");
+const { setSetting } = await import("@/server/settings");
+const pool = await import("@/server/computer/pool");
+const workers = await import("@/server/computer/workers");
+const { callNetwork } = await import("@/server/computer/http");
+
+const DAY = 24 * 60 * 60_000;
+const MIN = 60_000;
+let n = 0;
+
+beforeAll(() => setSetting("comfyWhere", "workers"));
+afterEach(() => {
+ delete process.env.FUOBE_WORKER_TOKEN_DAYS;
+ delete process.env.FUOBE_TRUST_PROXY;
+});
+
+const row = (id: string) => workers.getWorker(id)!;
+const bearer = (token: string) => `Bearer ${token}`;
+const beat = (id: string, protocol: number, now: number) =>
+ pool.workerBeat(row(id), pool.cleanBeat({ device: `wkr-${id}`, protocol, version: "2.0.0", local: { paused: true, why: "here", until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);
+const alerts = (id: string) =>
+ (db().prepare("SELECT actor, target, detail_json FROM admin_audit WHERE action = 'worker.alert' AND target = ? ORDER BY id").all(id) as { actor: string; target: string; detail_json: string }[]).map(
+ (r) => ({ actor: r.actor, ...(JSON.parse(r.detail_json) as { kind: string } & Record<string, unknown>) }),
+ );
+
+describe("a pool worker's token lifetime", () => {
+ it("off by default: no expiry, and no next token in any beat answer", () => {
+ const w = pool.addWorker(`no-expiry-${++n}`);
+ expect(row(w.id).expires_at).toBeNull();
+ expect(beat(w.id, 2, Date.now() + 400 * DAY).worker.token).toBeUndefined();
+ });
+
+ it("with a lifetime: the next token once half is gone, to a worker that speaks protocol 2; the old one stops at its first use", () => {
+ process.env.FUOBE_WORKER_TOKEN_DAYS = "10";
+ const t0 = Date.now();
+ const w = workers.createWorker({ name: `expiring-${++n}`, kind: "pool" }, t0);
+ expect(row(w.id).expires_at).toBe(t0 + 10 * DAY);
+ // More than half left: nothing yet. A worker on protocol 1 never gets one.
+ expect(beat(w.id, 2, t0 + 4 * DAY).worker.token).toBeUndefined();
+ expect(beat(w.id, 1, t0 + 6 * DAY).worker.token).toBeUndefined();
+ const offered = beat(w.id, 2, t0 + 6 * DAY).worker.token!;
+ expect(offered.value).toMatch(/^fuobe_wkr_[A-Za-z0-9_-]{43}$/);
+ expect(offered.expiresAt).toBe(t0 + 16 * DAY);
+ expect(JSON.stringify(row(w.id))).not.toContain(offered.value);
+ // Not offered again while it waits for its first use (within 10 minutes).
+ expect(beat(w.id, 2, t0 + 6 * DAY + MIN).worker.token).toBeUndefined();
+ // The old token still works until the new one is used.
+ expect(workers.workerFromAuth(bearer(w.token), null, t0 + 6 * DAY + 2 * MIN)?.id).toBe(w.id);
+ expect(workers.workerFromAuth(bearer(offered.value), null, t0 + 6 * DAY + 3 * MIN)?.id).toBe(w.id);
+ expect(workers.workerFromAuth(bearer(w.token), null, t0 + 6 * DAY + 4 * MIN)).toBeNull();
+ expect(row(w.id).expires_at).toBe(t0 + 16 * DAY);
+ expect(row(w.id).next_token_hash).toBeNull();
+ // Past its expiry a token stops.
+ expect(workers.workerFromAuth(bearer(offered.value), null, t0 + 16 * DAY + 1)).toBeNull();
+ });
+
+ it("a next token never used is offered again after 10 minutes, and the first one then doesn't work", () => {
+ process.env.FUOBE_WORKER_TOKEN_DAYS = "2";
+ const t0 = Date.now();
+ const w = workers.createWorker({ name: `lost-answer-${++n}`, kind: "pool" }, t0);
+ const first = beat(w.id, 2, t0 + 1.5 * DAY).worker.token!;
+ const second = beat(w.id, 2, t0 + 1.5 * DAY + 11 * MIN).worker.token!;
+ expect(second.value).not.toBe(first.value);
+ expect(workers.workerFromAuth(bearer(first.value), null, t0 + 1.5 * DAY + 12 * MIN)).toBeNull();
+ expect(workers.workerFromAuth(bearer(second.value), null, t0 + 1.5 * DAY + 12 * MIN)?.id).toBe(w.id);
+ });
+
+ it("the owner's new token for a worker drops a next token waiting, and starts a new lifetime", () => {
+ process.env.FUOBE_WORKER_TOKEN_DAYS = "2";
+ const t0 = Date.now();
+ const w = workers.createWorker({ name: `rotated-${++n}`, kind: "pool" }, t0);
+ const waiting = beat(w.id, 2, t0 + 1.5 * DAY).worker.token!;
+ const fresh = workers.rotateWorker(w.id, t0 + 1.5 * DAY + MIN)!;
+ expect(workers.workerFromAuth(bearer(waiting.value), null, t0 + 1.5 * DAY + 2 * MIN)).toBeNull();
+ expect(workers.workerFromAuth(bearer(fresh), null, t0 + 1.5 * DAY + 2 * MIN)?.id).toBe(w.id);
+ expect(row(w.id).expires_at).toBe(t0 + 1.5 * DAY + MIN + 2 * DAY);
+ });
+
+ it("a person's paired ComfyUI keeps its token as before", () => {
+ process.env.FUOBE_WORKER_TOKEN_DAYS = "1";
+ const p = workers.createWorker({ name: `paired-${++n}`, kind: "personal", principal: "owner" });
+ expect(row(p.id).expires_at).toBeNull();
+ expect(workers.offerNextToken(row(p.id), Date.now() + 400 * DAY)).toBeNull();
+ });
+});
+
+describe("where a pool worker's token is used from", () => {
+ it("a new country and a new network are alerts; the first use and the same place again are not", () => {
+ const w = pool.addWorker(`places-${++n}`);
+ const t0 = Date.now();
+ workers.workerFromAuth(bearer(w.token), { country: "IN", network: "203.0.113.0/24" }, t0);
+ workers.workerFromAuth(bearer(w.token), { country: "IN", network: "203.0.113.0/24" }, t0 + 60 * MIN);
+ expect(alerts(w.id)).toEqual([]);
+ workers.workerFromAuth(bearer(w.token), { country: "US", network: "203.0.113.0/24" }, t0 + 120 * MIN);
+ workers.workerFromAuth(bearer(w.token), { country: "US", network: "198.51.100.0/24" }, t0 + 180 * MIN);
+ const got = alerts(w.id);
+ expect(got.map((a) => a.kind)).toEqual(["new-country", "new-network"]);
+ expect(got.every((a) => a.actor === "system")).toBe(true);
+ expect(got[0]).toMatchObject({ country: "US", known: ["IN"] });
+ // Never an address: networks are short hashes, in the log and on the worker's row.
+ const kept = JSON.stringify(got) + JSON.stringify(row(w.id));
+ expect(kept).not.toContain("203.0.113");
+ expect(kept).not.toContain("198.51.100");
+ });
+
+ it("two networks within minutes of each other are an alert, once an hour", () => {
+ const w = pool.addWorker(`two-${++n}`);
+ const t0 = Date.now();
+ workers.workerFromAuth(bearer(w.token), { network: "192.0.2.0/24" }, t0);
+ workers.workerFromAuth(bearer(w.token), { network: "198.18.0.0/24" }, t0 + MIN);
+ workers.workerFromAuth(bearer(w.token), { network: "192.0.2.0/24" }, t0 + 2 * MIN);
+ workers.workerFromAuth(bearer(w.token), { network: "198.18.0.0/24" }, t0 + 3 * MIN);
+ expect(alerts(w.id).filter((a) => a.kind === "two-sources")).toHaveLength(1);
+ });
+
+ it("the network is read only behind a trusted proxy: an IPv4 address's /24", () => {
+ const req = new Request("http://localhost/api/gpu/computer/beat", { headers: { "x-forwarded-for": "203.0.113.9" } });
+ expect(callNetwork(req)).toBeNull();
+ process.env.FUOBE_TRUST_PROXY = "1";
+ expect(callNetwork(req)).toBe("203.0.113.0/24");
+ expect(callNetwork(new Request("http://localhost/", { headers: { "x-forwarded-for": "2001:db8:1:2:3:4:5:6" } }))).toBe("2001:db8:1:2::/64");
+ });
+});
diff --git a/tests/workers-pairing.test.ts b/tests/workers-pairing.test.ts
index d4560eba..b69f569b 100644
--- a/tests/workers-pairing.test.ts
+++ b/tests/workers-pairing.test.ts
@@ -111,14 +111,26 @@ describe("pairing a ComfyUI", () => {
expect(workers.pollPairing(s.id, s.secret).state).toBe("gone");
});
- it("the owner can pair too: ComfyUI then runs on the owner's computer", async () => {
- setSetting("comfyWhere", "server");
+ it("the owner can pair too; where the studio's ComfyUI jobs run stays the owner's choice in Settings", async () => {
+ setSetting("comfyWhere", "workers");
+ const logged = () => db().prepare("SELECT detail_json FROM admin_audit WHERE action = 'settings.comfy_where' ORDER BY id").all() as { detail_json: string }[];
+ const before = logged().length;
const p = await pair("owner");
- expect(getSetting("comfyWhere")).toBe("computer");
+ expect(getSetting("comfyWhere")).toBe("workers");
+ expect(logged().length).toBe(before);
+ // It takes the owner's jobs once the owner moves them to the owner's computer in Settings.
+ expect((principalOf(program("/api/gpu/computer/beat", p.token)) as Response).status).toBe(409);
+ // Every change of it is in the admin log, with the values before and after; setting the same value again is not.
+ setSetting("comfyWhere", "computer");
const req = program("/api/gpu/computer/beat", p.token);
expect(principalOf(req)).toBe("owner");
expect(requestWorker(req)?.id).toBe(p.id);
+ setSetting("comfyWhere", "computer");
setSetting("comfyWhere", "server");
+ expect(logged().slice(before).map((r) => JSON.parse(r.detail_json))).toEqual([
+ { before: "workers", after: "computer" },
+ { before: "computer", after: "server" },
+ ]);
});
it("codes are case- and dash-blind", () => {