The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Your GPU: pair your own ComfyUI with a code, and run your jobs with no tab open
Adarsh1bbedb8d9788
diff --git a/src/app/api/gpu/computer/beat/route.ts b/src/app/api/gpu/computer/beat/route.tsindex 78e74ac2..5ce8bad3 100644--- a/src/app/api/gpu/computer/beat/route.ts+++ b/src/app/api/gpu/computer/beat/route.ts@@ -1,5 +1,6 @@-import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";-import { beat, type BeatInput } from "@/server/computer/tasks";+import { principalOf, rateOf, relayAnswer, requestWorker } from "@/server/computer/http";+import { beat, cleanFacts, type BeatInput } from "@/server/computer/tasks";+import { noteWorkerFacts } from "@/server/computer/workers";/** What a beat may weigh: the facts, with up to 20,000 LoRA names. */const MAX_BYTES = 3 * 2 ** 20;@@ -23,6 +24,13 @@ export async function POST(request: Request) {} catch {return Response.json({ error: "Send JSON" }, { status: 400 });}+ // A paired ComfyUI's facts are kept with it too (the person's list of paired ComfyUIs shows its GPU).+ const worker = requestWorker(request);+ if (worker && body?.facts !== undefined) {+ const facts = cleanFacts(body.facts);+ delete facts.loras;+ noteWorkerFacts(worker.id, facts);+ }try {return Response.json(beat(principal, { device: String(body?.device ?? ""), port: body?.port, facts: body?.facts, running: Array.isArray(body?.running) ? body.running : [], takeover: body?.takeover === true, stopped: Array.isArray(body?.stopped) ? body.stopped : [], ready: body?.ready !== false, ...(body?.why === "setting" && { why: "setting" as const }), listen: body?.listen === true }), {headers: { "Cache-Control": "no-store" },diff --git a/src/app/api/gpu/computer/unpair/route.ts b/src/app/api/gpu/computer/unpair/route.tsnew file mode 100644index 00000000..1c93cb3d--- /dev/null+++ b/src/app/api/gpu/computer/unpair/route.ts@@ -0,0 +1,12 @@+import { revokeWorker, workerFromAuth } from "@/server/computer/workers";++/**+ * A paired ComfyUI disconnects itself (Fuobe Connect's Disconnect): its own token stops. Only with that token, and only+ * for that one worker.+ */+export async function POST(request: Request) {+ const w = workerFromAuth(request.headers.get("authorization"));+ if (!w || w.kind !== "personal") return Response.json({ error: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });+ revokeWorker(w.id);+ return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/gpu/pair/poll/route.ts b/src/app/api/gpu/pair/poll/route.tsnew file mode 100644index 00000000..e97f3a73--- /dev/null+++ b/src/app/api/gpu/pair/poll/route.ts@@ -0,0 +1,15 @@+import { pollPairing } from "@/server/computer/workers";+import { hit } from "@/server/rate";++/**+ * Fuobe Connect asks whether its code was approved, with the secret only it has: "waiting", "approved" with its token+ * (once: the token is made now, and only its hash is kept), or "gone" (denied, expired, or already delivered).+ */+export async function POST(request: Request) {+ const body = (await request.json().catch(() => null)) as { id?: unknown; secret?: unknown } | null;+ const id = typeof body?.id === "string" ? body.id.slice(0, 32) : "";+ const r = hit(`pair-poll:${id}`, 60, 60_000);+ if (!r.ok) return Response.json({ error: "Too many at once" }, { status: 429, headers: { "Retry-After": String(r.retryAfterS) } });+ const a = pollPairing(body?.id, body?.secret);+ return Response.json(a, { status: a.state === "gone" ? 404 : 200, headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/gpu/pair/route.ts b/src/app/api/gpu/pair/route.tsnew file mode 100644index 00000000..09c3f0a2--- /dev/null+++ b/src/app/api/gpu/pair/route.ts@@ -0,0 +1,47 @@+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";++/** 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;++const GONE = "That code isn't waiting any more. Press Connect to Fuobe in ComfyUI again for a new one.";++function limited(principal: string): Response | null {+ const r = hit(`pair-code:${principal}`, LOOKUPS, 10 * 60_000);+ return r.ok ? null : Response.json({ error: "Too many codes. Try again in a few minutes." }, { status: 429, headers: { "Retry-After": String(r.retryAfterS) } });+}++/** The computer behind a code, for the person to check before they approve it: its name and GPU. */+export async function GET(request: Request) {+ await connection();+ const principal = pairingPrincipal(request);+ if (principal instanceof Response) return principal;+ const no = limited(principal);+ if (no) return no;+ const code = new URL(request.url).searchParams.get("code");+ const p = code ? pairingByCode(code) : null;+ if (!p) return Response.json({ error: GONE }, { status: 404, headers: { "Cache-Control": "no-store" } });+ return Response.json({ code: normaliseCode(code), ...p }, { headers: { "Cache-Control": "no-store" } });+}++/**+ * The person approves a code (`{ code }`), or says it isn't theirs (`{ code, deny: true }`). Approved: that ComfyUI runs+ * this person's jobs, and only theirs, from its next poll on.+ */+export async function POST(request: Request) {+ const principal = pairingPrincipal(request);+ if (principal instanceof Response) return principal;+ const no = limited(principal);+ if (no) return no;+ const body = (await request.json().catch(() => null)) as { code?: unknown; deny?: unknown } | null;+ if (body?.deny === true) {+ denyPairing(String(body.code ?? ""));+ return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });+ }+ 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" } });+}diff --git a/src/app/api/gpu/pair/start/route.ts b/src/app/api/gpu/pair/start/route.tsnew file mode 100644index 00000000..5d4ef499--- /dev/null+++ b/src/app/api/gpu/pair/start/route.ts@@ -0,0 +1,47 @@+import { LoginGuard } from "@/server/auth";+import { cleanFacts } from "@/server/computer/tasks";+import { PAIR_MS, startPairing } from "@/server/computer/workers";+import { hit } from "@/server/rate";++/** Codes one address may ask for in 10 minutes, and all addresses together in a minute. */+const PER_CLIENT = 10;+const PER_MINUTE = 120;++/**+ * Fuobe Connect (a ComfyUI custom node, integrations/fuobe-connect) asks to pair a ComfyUI with a person's account. The+ * answer is a short code for the person to approve on this site while signed in, and a secret only this ComfyUI knows,+ * which it polls with (./poll). Nothing else happens until the person approves. Open to anyone (no session): a program+ * calls it, and a code alone gives nothing.+ */+export async function POST(request: Request) {+ const key = LoginGuard.clientKey(request.headers);+ const mine = hit(`pair-start:${key}`, key === LoginGuard.DIRECT ? PER_CLIENT * 10 : PER_CLIENT, 10 * 60_000);+ const all = hit("pair-start", PER_MINUTE, 60_000);+ if (!mine.ok || !all.ok) {+ return Response.json({ error: "Too many codes at once. Try again in a few minutes." }, { status: 429, headers: { "Retry-After": String(Math.max(mine.retryAfterS, all.retryAfterS)) } });+ }+ const text = await request.text().catch(() => "");+ if (text.length > 16 * 1024) return Response.json({ error: "Too much at once" }, { status: 413 });+ let body: { name?: unknown; facts?: unknown } = {};+ try {+ body = text ? (JSON.parse(text) as typeof body) : {};+ } catch {+ return Response.json({ error: "Send JSON" }, { status: 400 });+ }+ const facts = cleanFacts(body?.facts);+ delete facts.loras;+ const p = startPairing({ name: typeof body?.name === "string" ? body.name : "ComfyUI", facts });+ const url = new URL(`/connect?code=${encodeURIComponent(p.code)}`, siteOf(request)).toString();+ return Response.json(+ { id: p.id, secret: p.secret, code: p.code, url, expiresAt: p.expiresAt, expiresInS: PAIR_MS / 1000, pollMs: 2000 },+ { headers: { "Cache-Control": "no-store" } },+ );+}++/** This studio's own address, as the request reached it (behind a proxy: the forwarded host and scheme). */+function siteOf(request: Request): string {+ const u = new URL(request.url);+ const host = request.headers.get("x-forwarded-host")?.split(",")[0].trim() || request.headers.get("host") || u.host;+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0].trim() || u.protocol.replace(":", "");+ return `${proto === "http" ? "http" : "https"}://${host}`;+}diff --git a/src/app/api/gpu/paired/[id]/route.ts b/src/app/api/gpu/paired/[id]/route.tsnew file mode 100644index 00000000..fc05248f--- /dev/null+++ b/src/app/api/gpu/paired/[id]/route.ts@@ -0,0 +1,11 @@+import { pairingPrincipal } from "@/server/computer/pairing-http";+import { unpair } from "@/server/computer/workers";++/** Disconnect one of this person's paired ComfyUIs: its token stops at its next call. */+export async function DELETE(request: Request, ctx: RouteContext<"/api/gpu/paired/[id]">) {+ const principal = pairingPrincipal(request);+ if (principal instanceof Response) return principal;+ const { id } = await ctx.params;+ if (!unpair(principal, id)) return Response.json({ error: "Not found" }, { status: 404 });+ return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/app/api/gpu/paired/route.ts b/src/app/api/gpu/paired/route.tsnew file mode 100644index 00000000..bd0121c4--- /dev/null+++ b/src/app/api/gpu/paired/route.ts@@ -0,0 +1,11 @@+import { connection } from "next/server";+import { pairingPrincipal } from "@/server/computer/pairing-http";+import { pairedOf } from "@/server/computer/workers";++/** The ComfyUIs paired with this person (Fuobe Connect): name, GPU, when each was last heard from. */+export async function GET(request: Request) {+ await connection();+ const principal = pairingPrincipal(request);+ if (principal instanceof Response) return principal;+ return Response.json({ paired: pairedOf(principal) }, { headers: { "Cache-Control": "no-store" } });+}diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex abc924ab..ab575e21 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -165,7 +165,7 @@ export function accountGeneration(method: string, pathname: string): string | un*/export function accountOwnRead(pathname: string): boolean {if (ACCOUNT_LISTS.has(pathname)) return true;- return pathname === "/api/generations" || pathname === "/api/account/gpu" || pathname === "/api/account/keys" || GPU_READS.has(pathname) || COMPUTER_READ.test(pathname);+ return pathname === "/api/generations" || pathname === "/api/account/gpu" || pathname === "/api/account/keys" || GPU_READS.has(pathname) || COMPUTER_READ.test(pathname) || PAIRING_READS.has(pathname);}/** The Library's counts and its Uploads (its stored files): each route answers an account with its own only. */@@ -176,6 +176,8 @@ const ACCOUNT_LISTS = new Set(["/api/generations/facets", "/api/assets"]);* jobs from the session, and only that person's (src/server/computer/http.ts principalOf).*/const COMPUTER_READ = /^\/api\/gpu\/computer\/tasks\/[^/]+\/(inputs|outputs)\/[^/]+$/;+/** Pairing a ComfyUI with Fuobe Connect: the code's computer, and the person's paired ComfyUIs (src/app/api/gpu/pair). */+const PAIRING_READS = new Set(["/api/gpu/pair", "/api/gpu/paired"]);const COMPUTER_CHANGES: [method: string, path: RegExp][] = [["POST", /^\/api\/gpu\/computer\/(beat|claim)$/],["POST", /^\/api\/gpu\/computer\/tasks\/[^/]+\/(report|release)$/],@@ -196,8 +198,9 @@ export function accountMayChange(method: string, pathname: string, search: strinif ((method === "PUT" || method === "DELETE") && /^\/api\/account\/keys\/(fal|replicate)$/.test(pathname)) return true;// GPU pre-flight: checking its own ComfyUI (reads only; the routes check the target and the request themselves).if ((method === "POST" && pathname === "/api/gpu/check") || (method === "PUT" && pathname === "/api/gpu/inventory")) return true;- // Running its own jobs on its own computer.+ // Running its own jobs on its own computer, and pairing (or unpairing) its own ComfyUI.if (COMPUTER_CHANGES.some(([m, p]) => m === method && p.test(pathname))) return true;+ if ((method === "POST" && pathname === "/api/gpu/pair") || (method === "DELETE" && /^\/api\/gpu\/paired\/[^/]+$/.test(pathname))) return true;if (method === "POST" && (pathname === "/api/uploads" || pathname === "/api/media/probe")) return true;// "Report this result", and a click on an offer the billing service sent (each route checks the rest).if (method === "POST" && (pathname === "/api/reports" || pathname === "/api/billing/interest")) return true;diff --git a/src/lib/local-comfy.ts b/src/lib/local-comfy.tsindex b018f482..eb716820 100644--- a/src/lib/local-comfy.ts+++ b/src/lib/local-comfy.ts@@ -50,7 +50,7 @@ export function readPath(path: string): string {if (query) throw new LocalComfyError(`No query on ${p}`);return path;};- if (["/system_stats", "/api/system_stats", "/object_info", "/models", "/embeddings", "/queue", "/api/jobs", "/fuobe/guard", "/fuobe/live"].includes(p)) return noQuery();+ if (["/system_stats", "/api/system_stats", "/object_info", "/models", "/embeddings", "/queue", "/api/jobs", "/fuobe/guard", "/fuobe/live", "/fuobe/connect"].includes(p)) return noQuery();if (p.startsWith("/object_info/") && NODE_CLASS.test(decodeURIComponent(p.slice(13)))) return noQuery();if (p.startsWith("/models/") && MODEL_FOLDER.test(p.slice(8))) return noQuery();if (p.startsWith("/history/") && UUID.test(p.slice(9))) return noQuery();diff --git a/src/proxy.ts b/src/proxy.tsindex 8fe1c6f1..da1d4a1a 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -38,7 +38,14 @@ import { hostedRunsOn } from "@/server/hosted-switch";* Paths that work signed out: the login page and its API (and share links: openShare). Sign-up and* "who am I" answer for themselves whether public sign-up is on.*/-const OPEN = new Set(["/login", "/api/auth/login", "/api/auth/signup", "/api/auth/me"]);+const OPEN = new Set(["/login", "/api/auth/login", "/api/auth/signup", "/api/auth/me", "/api/gpu/pair/start", "/api/gpu/pair/poll"]);++/**+ * A worker's token (src/server/computer/workers.ts) works only on the routes a computer runs jobs through; the route+ * checks the token itself. Anywhere else it is refused, whatever else the request carries.+ */+const WORKER_BEARER = /^Bearer\s+fuobe_wkr_/i;+const workerRoute = (pathname: string) => pathname.startsWith("/api/gpu/computer/");const APP_IDS = new Set(APPS.map((a) => a.id));@@ -336,6 +343,9 @@ export function proxy(request: NextRequest) {}const hub = read && hubModeLink(request);if (hub) return NextResponse.redirect(hub);+ if (WORKER_BEARER.test(request.headers.get("authorization") ?? "")) {+ return workerRoute(pathname) ? NextResponse.next() : NextResponse.json({ error: "A worker's token only runs jobs." }, { status: 403, headers: { "Cache-Control": "no-store" } });+ }if (!authEnabled()) return pass(request);if (OPEN.has(pathname)) return NextResponse.next();const open = publicSignup(request.headers.get("host") ?? request.nextUrl.host);diff --git a/src/server/auth.ts b/src/server/auth.tsindex 2a127c03..23e17ddd 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -780,7 +780,8 @@ const touched = new Map<string, number>();export function validToken(header: string | null): boolean {const m = /^Bearer\s+(fuobe_[\w-]+)$/i.exec(header ?? "");- if (!m) return false;+ // A worker's token (src/server/computer/workers.ts) or a scoped admin token is never the owner.+ if (!m || /^fuobe_(wkr|adm)_/i.test(m[1])) return false;const h = Buffer.from(tokenHash(m[1]));const d = read();const hit = d.tokens.find((t) => same(Buffer.from(t.hash), h));diff --git a/src/server/computer/http.ts b/src/server/computer/http.tsindex 8c3e8350..2643bfd4 100644--- a/src/server/computer/http.ts+++ b/src/server/computer/http.ts@@ -3,10 +3,11 @@ 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 { accountGpu, authEnabled, crossSite, hostAllowed, requestViewer, validToken } from "../auth";+import { accountById, accountGpu, authEnabled, crossSite, hostAllowed, publicSignup, requestViewer, validToken } from "../auth";import { hit } from "../rate";import { getSetting } from "../settings";import { RelayError, type Principal } from "./tasks";+import { isWorkerAuth, workerFromAuth, type WorkerRow } from "./workers";/*** What every "computer" route (src/app/api/gpu/computer) checks first: a person in a browser on this site (no API@@ -17,7 +18,9 @@ import { RelayError, type Principal } from "./tasks";export function principalOf(request: Request): Principal | Response {const no = (status: number, error: string, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}) =>Response.json({ error, ...extra }, { status, headers: { "Cache-Control": "no-store", ...headers } });- if (validToken(request.headers.get("authorization"))) return no(403, "Only Fuobe open in a browser runs jobs on your computer.");+ const auth = request.headers.get("authorization");+ if (isWorkerAuth(auth)) return workerPrincipal(request, auth!, no);+ if (validToken(auth)) return no(403, "Only Fuobe open in a browser runs jobs on your computer.");const host = request.headers.get("host") ?? new URL(request.url).host;if (crossSite(request, host)) return no(403, "Blocked a request from another website.");const site = request.headers.get("sec-fetch-site");@@ -34,6 +37,35 @@ export function principalOf(request: Request): Principal | Response {return `acct:${viewer.account.id}`;}+/**+ * A worker's call (`Authorization: Bearer fuobe_wkr_…`, from a program: no browser checks). A paired ComfyUI acts as its+ * person's own computer, with the same checks their browser gets: the owner while Settings says ComfyUI runs on the+ * owner's computer, an account while sign-up is open and its GPU is "this computer". Its token says whose it is; the+ * 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"));+ if (!w) return no(401, "This ComfyUI isn't paired with this studio any more. Pair it again from Fuobe Connect.", { code: "worker-token" });+ if (w.kind !== "personal" || !w.principal) return no(403, "Shared workers aren't switched on for this studio.", { code: "pool-off" });+ 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.");+ workerOfRequest.set(request, w);+ if (w.principal === "owner") {+ return getSetting("comfyWhere") === "computer" ? "owner" : no(409, "This studio's ComfyUI runs on its server.", { code: "server-mode" });+ }+ const id = w.principal.startsWith("acct:") ? w.principal.slice(5) : "";+ const account = id ? accountById(id) : undefined;+ if (!account || account.disabled || !publicSignup(host)) return no(401, "This account can't run jobs here now.", { code: "worker-token" });+ const gpu = accountGpu(id);+ if (!gpu) return no(403, CONNECT_GPU_MESSAGE, { code: "connect-gpu" });+ if (gpu.mode !== "computer") return no(409, "Your GPU is connected with a link, so the server runs it.", { code: "link-mode" });+ return w.principal as Principal;+}++/** 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;+/** At most `limit` calls a minute of one kind for a principal. */export function rateOf(principal: Principal, what: string, limit: number): Response | null {const r = hit(`relay-${what}:${principal}`, limit, 60_000);diff --git a/src/server/computer/pairing-http.ts b/src/server/computer/pairing-http.tsnew file mode 100644index 00000000..22448dc8--- /dev/null+++ b/src/server/computer/pairing-http.ts@@ -0,0 +1,37 @@+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" } });++/**+ * Who is approving or listing paired ComfyUIs: a person signed in in a browser (the owner, or an account while sign-up+ * is open). An API token can't pair a computer: a person has to see the code.+ */+export function pairingPrincipal(request: Request): Principal | Response {+ if (request.headers.get("authorization")) return no(403, "Sign in in your browser to pair a ComfyUI.");+ const v = requestViewer(request);+ if (v.kind === "owner") return "owner";+ if (v.kind === "account") return `acct:${v.account.id}`;+ return no(401, "Sign in to pair your ComfyUI.");+}++/**+ * 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.+ */+export function runOnComputer(principal: Principal): void {+ if (principal === "owner") {+ if (getSetting("comfyWhere") !== "computer") setSetting("comfyWhere", "computer");+ return;+ }+ const id = principal.slice(5);+ if (accountGpu(id)?.mode !== "computer") {+ setAccountGpu(id, { mode: "computer" });+ clearAccountLoras(id);+ dropSnapshots(principal);+ }+}diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 4d03db00..21aa78ff 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -681,6 +681,9 @@ export function purgeComputer(principal: Principal): void {d.prepare("DELETE FROM relay_inputs WHERE principal = ?").run(principal);d.prepare("DELETE FROM relay_tasks WHERE principal = ?").run(principal);d.prepare("DELETE FROM relay_runners WHERE principal = ?").run(principal);+ // Its paired ComfyUIs (Fuobe Connect) stop with it.+ d.prepare("DELETE FROM relay_workers WHERE kind = 'personal' AND principal = ?").run(principal);+ d.prepare("DELETE FROM relay_pairings WHERE principal = ?").run(principal);})();}diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.tsnew file mode 100644index 00000000..fc610053--- /dev/null+++ b/src/server/computer/workers.ts@@ -0,0 +1,300 @@+import "server-only";+import crypto from "node:crypto";+import { nanoid } from "nanoid";+import type { ComputerFacts } from "@/lib/relay";+import { db } from "../db";+import type { Principal } from "./tasks";++/**+ * Workers: programs that run ComfyUI jobs for this studio from another machine, over HTTPS, with a token of their own+ * (`Authorization: Bearer fuobe_wkr_…`). They use the same routes as the browser's "Use the ComfyUI on this computer"+ * (src/app/api/gpu/computer), and they never open a port.+ *+ * Two kinds:+ * - **personal**: one person's own ComfyUI, paired to their account (or to the owner) with a short code they approve+ * while signed in. Its token acts only as that person's computer: it takes only that person's jobs, exactly as their+ * own Fuobe tab would. Nobody else's job ever reaches it.+ * - **pool**: the owner's shared GPUs (docs/gpu-workers.md), added in Settings → Workers.+ *+ * Only the SHA-256 of a token is kept. A token is read on every call (no cache), so a revoked one stops at once.+ */++export const WORKER_TOKEN_PREFIX = "fuobe_wkr_";+const WORKER_TOKEN = /^fuobe_wkr_[A-Za-z0-9_-]{43}$/;+const BEARER_WORKER = /^Bearer\s+(fuobe_wkr_\S+)$/i;++export type WorkerKind = "personal" | "pool";++export interface WorkerRow {+ id: string;+ name: string;+ kind: WorkerKind;+ principal: string | null;+ pool: string;+ token_hash: string;+ created_at: number;+ expires_at: number | null;+ revoked_at: number | null;+ last_used_at: number | null;+ last_country: string | null;+ device: string | null;+ protocol: number | null;+ version: string | null;+ facts_json: string | null;+ inventory_json: string | null;+ inventory_hash: string | null;+ lanes_json: string | null;+ bench_json: string | null;+ warm_lane: string | null;+ paused_server: number;+ paused_local: number;+ local_why: string | null;+ local_until: number | null;+ drain: number;+ stop_now: number;+ hours_json: string | null;+ allow_json: string | null;+ claim_after_ms: number;+ switch_after_ms: number;+ state: string;+ seen_at: number | null;+}++const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");++/** A new worker token: the prefix and 32 random bytes. */+export const newWorkerToken = () => `${WORKER_TOKEN_PREFIX}${crypto.randomBytes(32).toString("base64url")}`;++/** Does this Authorization header carry a worker token (valid or not)? */+export const isWorkerAuth = (header: string | null | undefined): boolean => !!header && BEARER_WORKER.test(header.trim());++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.+ */+export function workerFromAuth(header: string | null | undefined, country?: string | 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;+ if (!row || row.revoked_at || (row.expires_at && row.expires_at <= now)) return null;+ 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);+ }+ return row;+}++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;+}++const cleanName = (name: unknown) =>+ (typeof name === "string" ? name : "")+ .replace(/[^\p{L}\p{N} ._()-]/gu, "")+ .trim()+ .slice(0, 48) || "ComfyUI";++/** A new worker and its token (the only time the token exists in the clear). */+export function createWorker(w: { name: string; kind: WorkerKind; principal?: Principal; pool?: string; facts?: ComputerFacts; expiresAt?: number }, now = Date.now()): { id: string; token: string } {+ const id = nanoid(12).replace(/[^A-Za-z0-9_-]/g, "_");+ const token = newWorkerToken();+ db()+ .prepare(+ `INSERT INTO relay_workers (id, name, kind, principal, pool, token_hash, created_at, expires_at, facts_json, paused_server, paused_local, state)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run(+ id,+ cleanName(w.name),+ w.kind,+ w.kind === "personal" ? w.principal ?? null : null,+ w.pool ?? "pool",+ sha(token),+ now,+ w.expiresAt ?? 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.+ w.kind === "personal" ? 0 : 1,+ w.kind === "personal" ? 0 : 1,+ "new",+ );+ return { id, token };+}++/** Revoke a worker: its next call gets 401. */+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 {+ 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;+ return ok ? token : null;+}++/** What a person sees of their paired ComfyUIs. */+export interface PairedView {+ id: string;+ name: string;+ createdAt: number;+ lastUsedAt: number | null;+ facts: ComputerFacts;+}++const json = <T,>(s: string | null, fallback: T): T => {+ if (!s) return fallback;+ try {+ return JSON.parse(s) as T;+ } catch {+ return fallback;+ }+};++export function pairedOf(principal: Principal): PairedView[] {+ const rows = db().prepare("SELECT * FROM relay_workers WHERE kind = 'personal' AND principal = ? AND revoked_at IS NULL ORDER BY created_at").all(principal) as WorkerRow[];+ return rows.map((r) => ({ id: r.id, name: r.name, createdAt: r.created_at, lastUsedAt: r.last_used_at, facts: json<ComputerFacts>(r.facts_json, {}) }));+}++/** Revoke one of a person's paired ComfyUIs (another person's is no worker at all). */+export function unpair(principal: Principal, id: string): boolean {+ const w = getWorker(id);+ if (!w || w.kind !== "personal" || w.principal !== principal) return false;+ return revokeWorker(id);+}++/** 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);+ db().prepare("DELETE FROM relay_pairings WHERE principal = ?").run(principal);+}++/** Keep a personal worker's facts (from its beat), for the person's list. */+export function noteWorkerFacts(id: string, facts: ComputerFacts): void {+ db().prepare("UPDATE relay_workers SET facts_json = ? WHERE id = ?").run(JSON.stringify(facts), id);+}++// ---------------------------------------------------------------------------+// Pairing: a ComfyUI shows a short code; the signed-in person approves it on this site; the ComfyUI then gets a token+// for that person only.++/** How long a code waits for the person. */+export const PAIR_MS = 10 * 60_000;+/** Letters and digits that can't be mixed up (no 0/O, 1/I/L). */+const CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";+export const PAIR_CODE = /^[A-HJKMNP-Z2-9]{4}-?[A-HJKMNP-Z2-9]{4}$/;++interface PairingRow {+ id: string;+ code: string;+ secret_hash: string;+ name: string;+ facts_json: string | null;+ created_at: number;+ expires_at: number;+ state: "waiting" | "approved" | "denied";+ principal: string | null;+ worker_id: string | null;+}++function newCode(): string {+ const bytes = crypto.randomBytes(8);+ let s = "";+ for (let i = 0; i < 8; i++) s += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];+ return `${s.slice(0, 4)}-${s.slice(4)}`;+}++/** "abcd efgh", "ABCDEFGH" → "ABCD-EFGH", or null. */+export function normaliseCode(input: unknown): string | null {+ if (typeof input !== "string") return null;+ const s = input.toUpperCase().replace(/[\s-]/g, "");+ if (!/^[A-HJKMNP-Z2-9]{8}$/.test(s)) return null;+ return `${s.slice(0, 4)}-${s.slice(4)}`;+}++function sweepPairings(now: number) {+ db().prepare("DELETE FROM relay_pairings WHERE expires_at < ?").run(now - PAIR_MS);+ // Approved, but the ComfyUI never came back for its token.+ db().prepare("DELETE FROM relay_workers WHERE kind = 'personal' AND token_hash LIKE 'pending:%' AND created_at < ?").run(now - 2 * PAIR_MS);+}++/** A ComfyUI asks to be paired: a code for the person, and a secret only it knows (it polls with it). */+export function startPairing(o: { name: string; facts?: ComputerFacts }, now = Date.now()): { id: string; secret: string; code: string; expiresAt: number } {+ sweepPairings(now);+ const id = nanoid(16).replace(/[^A-Za-z0-9_-]/g, "_");+ const secret = crypto.randomBytes(32).toString("hex");+ for (let i = 0; ; i++) {+ const code = newCode();+ try {+ db()+ .prepare("INSERT INTO relay_pairings (id, code, secret_hash, name, facts_json, created_at, expires_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting')")+ .run(id, code, sha(secret), cleanName(o.name), o.facts ? JSON.stringify(o.facts) : null, now, now + PAIR_MS);+ return { id, secret, code, expiresAt: now + PAIR_MS };+ } catch (e) {+ if (i >= 5) throw e;+ }+ }+}++/** What the person sees before they approve a code: the computer's name and GPU. Null: no such code waiting. */+export function pairingByCode(code: string, now = Date.now()): { name: string; facts: ComputerFacts; expiresAt: number } | null {+ const c = normaliseCode(code);+ if (!c) return null;+ const row = db().prepare("SELECT * FROM relay_pairings WHERE code = ?").get(c) as PairingRow | undefined;+ if (!row || row.state !== "waiting" || row.expires_at < now) return null;+ return { name: row.name, facts: json<ComputerFacts>(row.facts_json, {}), expiresAt: row.expires_at };+}++/**+ * The signed-in person approves a code: a personal worker for them is made now; the ComfyUI gets its token at its next+ * poll. Null: no such code waiting.+ */+export function approvePairing(code: string, principal: Principal, now = Date.now()): { workerId: string; name: string } | null {+ const c = normaliseCode(code);+ if (!c) return null;+ const d = db();+ return d.transaction(() => {+ const row = d.prepare("SELECT * FROM relay_pairings WHERE code = ?").get(c) as PairingRow | undefined;+ if (!row || row.state !== "waiting" || row.expires_at < now) return null;+ // The worker exists from now on, with a placeholder hash no token can have; its token is made at the poll.+ const id = nanoid(12).replace(/[^A-Za-z0-9_-]/g, "_");+ d.prepare(+ `INSERT INTO relay_workers (id, name, kind, principal, pool, token_hash, created_at, facts_json, paused_server, paused_local, state)+ VALUES (?, ?, 'personal', ?, 'pool', ?, ?, ?, 0, 0, 'new')`,+ ).run(id, row.name, principal, `pending:${row.id}`, now, row.facts_json);+ d.prepare("UPDATE relay_pairings SET state = 'approved', principal = ?, worker_id = ? WHERE id = ?").run(principal, id, row.id);+ return { workerId: id, name: row.name };+ })();+}++/** "That's not my computer": the code stops. */+export function denyPairing(code: string): boolean {+ const c = normaliseCode(code);+ return !!c && db().prepare("UPDATE relay_pairings SET state = 'denied' WHERE code = ? AND state = 'waiting'").run(c).changes > 0;+}++export type PollAnswer = { state: "waiting"; expiresAt: number } | { state: "approved"; token: string; workerId: string; name: string } | { state: "gone" };++/**+ * The ComfyUI asks whether its code was approved (with its secret). Approved: its token, once (made now; only its hash+ * is kept), and the pairing is gone. Denied, expired, unknown or already delivered: gone.+ */+export function pollPairing(id: unknown, secret: unknown, now = Date.now()): PollAnswer {+ if (typeof id !== "string" || typeof secret !== "string" || !/^[0-9a-f]{64}$/.test(secret)) return { state: "gone" };+ const d = db();+ return d.transaction((): PollAnswer => {+ const row = d.prepare("SELECT * FROM relay_pairings WHERE id = ?").get(id) as PairingRow | undefined;+ if (!row || !crypto.timingSafeEqual(Buffer.from(sha(secret)), Buffer.from(row.secret_hash))) return { state: "gone" };+ if (row.state === "waiting") return row.expires_at >= now ? { state: "waiting", expiresAt: row.expires_at } : { state: "gone" };+ d.prepare("DELETE FROM relay_pairings WHERE id = ?").run(row.id);+ if (row.state !== "approved" || !row.worker_id) return { state: "gone" };+ const token = newWorkerToken();+ const ok = d.prepare("UPDATE relay_workers SET token_hash = ? WHERE id = ? AND token_hash = ? AND revoked_at IS NULL").run(sha(token), row.worker_id, `pending:${row.id}`).changes > 0;+ return ok ? { state: "approved", token, workerId: row.worker_id, name: row.name } : { state: "gone" };+ })();+}diff --git a/src/server/db.ts b/src/server/db.tsindex 3c2998a8..000446ad 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -667,7 +667,54 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (reads INTEGER NOT NULL DEFAULT 0,created_at INTEGER NOT NULL);- CREATE INDEX IF NOT EXISTS relay_inputs_task ON relay_inputs(task_id);`;+ CREATE INDEX IF NOT EXISTS relay_inputs_task ON relay_inputs(task_id);+ CREATE TABLE IF NOT EXISTS relay_workers (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ kind TEXT NOT NULL DEFAULT 'pool',+ principal TEXT,+ pool TEXT NOT NULL DEFAULT 'pool',+ token_hash TEXT NOT NULL UNIQUE,+ created_at INTEGER NOT NULL,+ expires_at INTEGER,+ revoked_at INTEGER,+ last_used_at INTEGER,+ last_country TEXT,+ device TEXT,+ protocol INTEGER,+ version TEXT,+ facts_json TEXT,+ inventory_json TEXT,+ inventory_hash TEXT,+ lanes_json TEXT,+ bench_json TEXT,+ warm_lane TEXT,+ paused_server INTEGER NOT NULL DEFAULT 1,+ paused_local INTEGER NOT NULL DEFAULT 1,+ local_why TEXT,+ local_until INTEGER,+ drain INTEGER NOT NULL DEFAULT 0,+ stop_now INTEGER NOT NULL DEFAULT 0,+ hours_json TEXT,+ allow_json TEXT,+ claim_after_ms INTEGER NOT NULL DEFAULT 0,+ switch_after_ms INTEGER NOT NULL DEFAULT 1800000,+ state TEXT NOT NULL DEFAULT 'new',+ seen_at INTEGER+ );+ CREATE INDEX IF NOT EXISTS relay_workers_principal ON relay_workers(principal);+ CREATE TABLE IF NOT EXISTS relay_pairings (+ id TEXT PRIMARY KEY,+ code TEXT NOT NULL UNIQUE,+ secret_hash TEXT NOT NULL,+ name TEXT NOT NULL,+ facts_json TEXT,+ created_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL,+ state TEXT NOT NULL DEFAULT 'waiting',+ principal TEXT,+ worker_id TEXT+ );`;/*** The optional external services' tables (billing.ts, moderation.ts). billing_outbox: every settle, refund and release@@ -723,6 +770,18 @@ const HOOK_COLUMNS: [string, string, string][] = [const RELAY_COLUMNS: [string, string, string][] = [["relay_runners", "comfy", "TEXT NOT NULL DEFAULT 'ok'"],["relay_tasks", "down_why", "TEXT"],+ // Workers (src/server/computer/workers.ts): all NULL for a browser computer's tasks, which work as before.+ ["relay_tasks", "account", "TEXT"],+ ["relay_tasks", "pools", "TEXT"],+ ["relay_tasks", "rank_at", "INTEGER"],+ ["relay_tasks", "lane", "TEXT"],+ ["relay_tasks", "needs_json", "TEXT"],+ ["relay_tasks", "est_ms", "INTEGER"],+ ["relay_tasks", "tried_json", "TEXT"],+ ["relay_tasks", "requeues", "INTEGER NOT NULL DEFAULT 0"],+ ["relay_tasks", "not_after", "INTEGER"],+ ["relay_tasks", "only_worker", "TEXT"],+ ["relay_tasks", "worker_id", "TEXT"],];declare global {