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: a token from the environment is never rotated, and its end date is logged

Adarshbecd491c4fc9
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 0edd260b..b0c320c2 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -149,7 +149,7 @@ export function siteOf(answer) {
/**
* Run until `signal` aborts or the studio stops it. Returns why it ended: "aborted" (Ctrl+C, the scheduled task's end),
- * "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home,
+ * "signed-out" (the studio doesn't know its token) or "disconnected". `deps`: { fetch, now, sleep, readGpu, log, home, env,
* signal, requirements, ComputerRunner, rules, pins, allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own
* options), readCounters, readListeners, gpuEveryMs }.
*/
@@ -292,11 +292,17 @@ async function work(saved, deps, owner) {
const api = retrying(fetchFn, { now, sleep, signal: deps.signal, log });
// Its token: worker.json's, until the studio gives it the next one (a token with a lifetime, docs/gpu-workers.md).
let token = cfg.token;
+ // A token given in FUOBE_WORKER_TOKEN stays out of files, and the environment's token is the one every start uses: so
+ // it never takes a next token (saved in worker.json, the next start would still use the old one, which stops working
+ // once the new one is used). It says when its token ends instead, so it can be replaced in time.
+ const envToken = !!(deps.env ?? process.env).FUOBE_WORKER_TOKEN;
+ const canRotate = !!deps.home && !envToken;
+ let endWarned = null;
const call = (p, init = {}) => api(`${site}${p}`, { ...init, headers: { ...(init.headers ?? {}), Authorization: `Bearer ${token}`, "User-Agent": `FuobeWorker/${VERSION}` } });
/** The studio's next token: saved in worker.json first, then used from the next call on (the old one stops then). */
const takeToken = (next) => {
if (!next || typeof next.value !== "string" || !NEXT_TOKEN.test(next.value) || next.value === token) return;
- if (!deps.home) return;
+ if (!canRotate) return;
try {
saveConfig(deps.home, { ...savedConfig(deps.home), token: next.value });
} catch (e) {
@@ -408,8 +414,8 @@ async function work(saved, deps, owner) {
return {
protocol: PROTOCOL,
version: VERSION,
- // It saves the next token a beat answer gives it.
- canRotateToken: !!deps.home,
+ // It saves the next token a beat answer gives it (never one for a token from the environment).
+ canRotateToken: canRotate,
local: pause,
gpu: gpuInfo,
inventoryHash: invHash,
@@ -429,6 +435,12 @@ async function work(saved, deps, owner) {
if (min > PROTOCOL && answer?.worker?.minProtocol !== a.worker.minProtocol) log("The studio needs a newer worker program: it sends this one no jobs. Update the worker (docs/gpu-workers.md, \"Install and update\").");
answer = a;
takeToken(a?.worker?.token);
+ // A token from the environment with a lifetime: said once for each end date, so it is replaced there in time.
+ const ends = Number(a?.worker?.tokenExpiresAt);
+ if (envToken && Number.isFinite(ends) && ends > 0 && ends !== endWarned) {
+ endWarned = ends;
+ log(`Its token comes from FUOBE_WORKER_TOKEN, so it saves no next one: it stops working on ${new Date(ends).toISOString().slice(0, 10)}. Before then, make a new token in Settings → Workers and put it in FUOBE_WORKER_TOKEN.`);
+ }
// The owner's switch on the Workers page wins over worker.json; null leaves worker.json's.
const s = a?.worker?.autoResume;
gpu.o.autoResume = typeof s === "boolean" ? s : !!cfg.autoResume;
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 1553d406..febe3f62 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -69,6 +69,8 @@ or press Disconnect in ComfyUI (`POST /api/gpu/computer/unpair`). A disconnected
Settings → Workers (the setting is `comfyWhere=workers`).
On a machine with no keyboard, set `FUOBE_WORKER_TOKEN` and `FUOBE_WORKER_SITE` so that the token stays out of files.
+The worker never rotates a token from the environment: with a token lifetime set, replace it there before it ends (see
+"A token's lifetime" below).
### Install and update
@@ -519,6 +521,12 @@ minutes. A paired ComfyUI's token keeps no lifetime. The worker program sends `c
next token in `worker.json` first, then uses it. If it can't save it, it keeps the token it has and gets the next one
again later. An older worker program doesn't rotate its token: update every worker before you set the lifetime, or
its token expires at the end of its lifetime and the worker stops until you rotate its token in Settings → Workers.
+Every beat answer for a token with a lifetime also says when it ends (`worker.tokenExpiresAt`).
+
+A worker whose token comes from `FUOBE_WORKER_TOKEN` never rotates it. That token stays out of files, and every start
+uses the environment's token, so a next token saved in `worker.json` would not survive a restart. Such a worker sends
+`canRotateToken: false` and writes the token's end date to its log once. Before that date, press **New token** in
+Settings → Workers and put the new token in `FUOBE_WORKER_TOKEN`.
**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
@@ -528,8 +536,8 @@ its target), at most once an hour each.
- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, canRotateToken?, local: { paused, why,
until }, gpu: { otherApps, tempC }, inventoryHash, warmLane, held, slept? }`. The answer adds `worker: { paused, pauseNow,
- drain, autoResume, insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token? }` (`token`: the next token,
- above).
+ drain, autoResume, insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token?, tokenExpiresAt? }` (`token`:
+ the next token, above; `tokenExpiresAt`: when the token ends, for a token with a lifetime).
- `protocol` is 2 for a worker that says which inputs it takes, makes clips and sound again, and keeps its ComfyUI
behind the guard.
- `held` (optional) names the jobs whose finished results the worker keeps on its disk. A pause now sends those
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index a0562347..5719a5d9 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -204,6 +204,11 @@ export interface WorkerAnswer {
* 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 };
+ /**
+ * When its token stops working, for a token with a lifetime (absent: it never expires). A worker that can't save a next
+ * token (one given in its environment) says so before then.
+ */
+ tokenExpiresAt?: number;
}
/** What a worker says in its beat, on top of a browser's. */
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index ae20097f..343dd0ca 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -169,7 +169,7 @@ function start(
w: W,
s: Studio,
p: Pc,
- o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number; now?: () => number; sleep?: (ms: number) => Promise<void> } = {},
+ o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number; now?: () => number; sleep?: (ms: number) => Promise<void>; env?: Record<string, string | undefined> } = {},
) {
const ctrl = new AbortController();
const cfg = {
@@ -210,6 +210,7 @@ function start(
},
...(o.rescanMs && { rescanMs: o.rescanMs }),
...(o.modelsCheckMs && { modelsCheckMs: o.modelsCheckMs }),
+ ...(o.env && { env: o.env }),
});
const r = { ctrl, done };
running.push(r);
@@ -743,4 +744,41 @@ describe("its model folders", () => {
delete process.env.FUOBE_WORKER_TOKEN_DAYS;
}
});
+
+ it("a token from FUOBE_WORKER_TOKEN: it never takes a next one or writes a token to a file, and says when its token ends", async () => {
+ process.env.FUOBE_WORKER_TOKEN_DAYS = "2";
+ try {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const beats: Record<string, unknown>[] = [];
+ s.intercept = (q, init) => {
+ if (q === "/api/gpu/computer/beat") beats.push(JSON.parse(String(init.body)));
+ return undefined;
+ };
+ // Half its life is gone: a worker that saves tokens would be given the next one now.
+ const ends = Date.now() + 60 * 60_000;
+ db().prepare("UPDATE relay_workers SET expires_at = ? WHERE id = ?").run(ends, w.id);
+ start(w, s, p, { env: { FUOBE_WORKER_TOKEN: w.token } });
+ const { id } = addTask();
+ expect((await ended(id)).state).toBe("done");
+ await until(() => beats.length >= 3);
+ // It never says it saves tokens, so the studio offers none, and its token stays the one it has.
+ expect(beats.every((b) => b.canRotateToken === false)).toBe(true);
+ expect(s.tokens).toEqual([]);
+ expect(fs.existsSync(path.join(p.home, "worker.json"))).toBe(false);
+ const row = db().prepare("SELECT token_hash, next_token_hash FROM relay_workers WHERE id = ?").get(w.id) as { token_hash: string; next_token_hash: string | null };
+ expect(row.token_hash).toBe(crypto.createHash("sha256").update(w.token).digest("hex"));
+ expect(row.next_token_hash).toBeNull();
+ // It says when its token ends, once, so it is replaced in the environment in time.
+ const said = await until(() => {
+ const lines = p.logs.filter((l) => /FUOBE_WORKER_TOKEN/.test(l));
+ return lines.length ? lines : null;
+ });
+ expect(said).toHaveLength(1);
+ expect(said[0]).toContain(new Date(ends).toISOString().slice(0, 10));
+ } finally {
+ delete process.env.FUOBE_WORKER_TOKEN_DAYS;
+ }
+ });
});
diff --git a/tests/worker-tokens.test.ts b/tests/worker-tokens.test.ts
index dae44f3b..0d0c504b 100644
--- a/tests/worker-tokens.test.ts
+++ b/tests/worker-tokens.test.ts
@@ -45,7 +45,10 @@ 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();
+ const answer = beat(w.id, 2, Date.now() + 400 * DAY).worker;
+ expect(answer.token).toBeUndefined();
+ // No end date to tell it either.
+ expect(answer.tokenExpiresAt).toBeUndefined();
});
it("with a lifetime: the next token once half is gone, to a worker that says it saves tokens; the old one stops at its first use", () => {
@@ -55,6 +58,8 @@ describe("a pool worker's token lifetime", () => {
expect(row(w.id).expires_at).toBe(t0 + 10 * DAY);
// More than half left: nothing yet. A worker that doesn't say it saves tokens never gets one, whatever its protocol.
expect(beat(w.id, 2, t0 + 4 * DAY).worker.token).toBeUndefined();
+ // Every beat answer says when its token ends (a worker with its token in its environment says so on its PC).
+ expect(beat(w.id, 2, t0 + 4 * DAY, false).worker.tokenExpiresAt).toBe(t0 + 10 * DAY);
expect(beat(w.id, 2, t0 + 6 * DAY, false).worker.token).toBeUndefined();
expect(beat(w.id, 3, t0 + 6 * DAY, false).worker.token).toBeUndefined();
expect(pool.cleanBeat({ protocol: 2, canRotateToken: "yes" }).canRotateToken).toBeUndefined();