Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Admin: set an account's password or email

Adarshda0d8f545711
diff --git a/docs/admin-api.md b/docs/admin-api.md
index edf1afcb..f7a1f88c 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -105,7 +105,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
|---|---|---|
| `GET /api/admin/accounts` | `q` (the email contains it, up to 100 characters), `email` (exactly that address), `format=csv` | `{ total, items, totals, signInNotices }`; with `q` or `email`, also `matched`. `total` and `totals` always cover every account. `signInNotices` lists each `auth.json` that was found in the data folder after the sign-in data moved into the database. Each one was set aside without being read ([Sign-in data](SELF-HOSTING.md#sign-in-data)). An entry gives `{ file, foundAt, reason, counts }`. `reason` is `stray`, `unreadable`, `link` (a symbolic link, never followed) or `import-failed`. `counts` is `{ accounts, tokens, accountsNotInDatabase }`, or `null` when the file isn't sign-in data or is a link. An entry stays in the list until you delete its file. CSV: a `text/csv` download |
| `GET /api/admin/accounts/{id}` | | one account with its numbers; 404 `No such account` |
-| `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }` or `{ signOut: true }` | the account (no numbers) |
+| `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }`, `{ signOut: true }`, `{ password: string }` or `{ email: string }` | the account (no numbers). `password`: a new password of at least 8 characters (400 otherwise), hashed as at sign-up. `email`: a new sign-in email, lower-cased as at sign-up (400 for one that isn't an email address, 409 when another account uses it). Either one ends every sign-in of the account, so it logs in again; its paired ComfyUIs stay paired. The log row names the account only, never the password or the email |
| `DELETE /api/admin/accounts/{id}` | | 204 |
| `GET /api/admin/generations` | `account` (one account), else `whose` (`people`: accounts' and guests' runs, the default; `ours`: the owner's own; `everyone`); `source` (the owner's runs only: `hands-on`, or `batch` for any automated run: `batch`, `drill`, `example`, `test`, `api`); `where` (`pool`: this install's GPUs, the owner's runs on its ComfyUI too; `provider`: a cloud provider; `own`: an account's own GPU); `status` (`finished` or `done`, `failed`, `canceled`, `waiting`, `started`, and `running` for waiting and started); `kind` (`image`, `video`, `audio`, `model3d`, `text`); `model` (letters of the model id); `from` and `to` (`yyyy-mm-dd` in UTC, both days included); `q` (words of the prompt, or a run id); `ids` (a comma list of up to 100 run ids: those runs, whoever's they are); `before` (the last page's `next`); `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. Each run has `whose`: `account`, `guest` or `owner`. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone). A failed run on this install's GPUs (and the owner's own failed run) also has `detail`: the technical reason, which the account never sees. `account` is `{ id, email }` (`email` null: a deleted account), `{ id, emailHidden: true }` without `accounts:read`, or `null` for the owner's own run, which has `source` too (`hands-on` from the site; `batch`, `drill`, `example`, `test` as its script said; `api` for a run sent with an API token that said none) and `sourceName` when its script gave one |
| `GET /api/admin/generations/{id}` | needs `runs:read` and `outputs:view` | One run in full, an account's, a guest's or the owner's own: `{ run, stored, fix, trouble, where, model, preset, studio, prompt, negativePrompt, asked, settings, inputs, batch, near, chain, sent, timing, jobs, workerLog, money, madeBy, surface, providerId, progress, checks }`. `stored.detail` is the technical reason for the owner; `comfyReason`, when there is one, is ComfyUI's own reason in one short line (a node that isn't installed, a model file not in its list, an error in a node), and each of `jobs` has it as `comfyWhy`. A job on one of this site's workers may have `nodes`: its slowest nodes, slowest first, each `{ node, type, ms, beforeStepsMs, steps }` (`beforeStepsMs` and `steps` for a node with steps; [gpu-workers.md](gpu-workers.md)). `inputs` lists each input file by slot, with its `state` (`kept` with its `url`, `removed`, `example`, `inline`, `link`). `chain` is `{ before, after }`: the steps it waits for and the steps that wait for it. Keys, tokens and GPU addresses are never part of it. 404 for an unknown run |
@@ -139,7 +139,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `GET /api/admin/tokens/self` | | `{ id, name, prefix, scopes, expiresAt, createdAt }` |
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`,
+`token.name` is the name the token had at the time. Actions: `account.disable`, `account.enable`, `account.signout`, `account.password`, `account.email`,
`account.delete`, `run.delete`, `outputs.hide`, `outputs.unhide`, `outputs.remove`, `worker.add`, `worker.change`,
`worker.rotate`, `worker.revoke`, `worker.revoke_all` (Sign everyone out with every API token), `queue.settings` (with
the values before and after), `queue.mode`, `queue.override`, `queue.override.end`, `queue.cancel`, `queue.pause` (with the `override` id and how many jobs were `sentBack`), `run.again` (the run as its target, with the account, the new run's `ids`, `place`, the `changed` settings and whether a `notice` was given), `queue.mode.end`
diff --git a/src/app/api/admin/accounts/[id]/route.ts b/src/app/api/admin/accounts/[id]/route.ts
index cf6e1851..f0134557 100644
--- a/src/app/api/admin/accounts/[id]/route.ts
+++ b/src/app/api/admin/accounts/[id]/route.ts
@@ -2,7 +2,7 @@ import { connection } from "next/server";
import { z } from "zod";
import { accountsWithStats } from "@/server/account-admin";
import { adminAccess, audit, auditRead, type Actor } from "@/server/admin-tokens";
-import { AccountError, accountInfo, setAccountDisabled, signOutAccount } from "@/server/auth";
+import { AccountError, accountInfo, setAccountDisabled, setAccountEmailAsOwner, setAccountPasswordAsOwner, signOutAccount } from "@/server/auth";
import { removeAccount } from "@/server/account-sweep";
import { revokeWorkersOf } from "@/server/computer/workers";
@@ -30,25 +30,36 @@ export async function GET(request: Request, ctx: RouteContext<"/api/admin/accoun
return Response.json(accountsWithStats([account]).items[0], { headers: NO_STORE });
}
-const Patch = z.union([z.object({ disabled: z.boolean() }).strict(), z.object({ signOut: z.literal(true) }).strict()]);
+const Patch = z.union([
+ z.object({ disabled: z.boolean() }).strict(),
+ z.object({ signOut: z.literal(true) }).strict(),
+ z.object({ password: z.string().max(500) }).strict(),
+ z.object({ email: z.string().max(254) }).strict(),
+]);
/**
- * Switch an account off (`{ disabled: true }`: signed out, can't log in) or on again, or sign it out everywhere
- * (`{ signOut: true }`: every sign-in ends and its paired ComfyUIs stop, and it stays on).
+ * Switch an account off (`{ disabled: true }`: signed out, can't log in) or on again, sign it out everywhere
+ * (`{ signOut: true }`: every sign-in ends and its paired ComfyUIs stop, and it stays on), set a new password
+ * (`{ password }`: 8 characters or more) or a new sign-in email (`{ email }`: 409 when another account uses it). A new
+ * password or email ends every sign-in of the account. The log never holds a password or an email.
*/
export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/accounts/[id]">) {
const access = adminAccess(request, "accounts:write", DENIED);
if (access instanceof Response) return access;
const parsed = Patch.safeParse(await request.json().catch(() => null));
- if (!parsed.success) return Response.json({ error: "Send { disabled: true }, { disabled: false } or { signOut: true }" }, { status: 400, headers: NO_STORE });
+ if (!parsed.success) return Response.json({ error: "Send { disabled: true }, { disabled: false }, { signOut: true }, { password } or { email }" }, { status: 400, headers: NO_STORE });
const { id } = await ctx.params;
- const action = "signOut" in parsed.data ? "account.signout" : parsed.data.disabled ? "account.disable" : "account.enable";
+ const body = parsed.data;
+ const action =
+ "signOut" in body ? "account.signout" : "password" in body ? "account.password" : "email" in body ? "account.email" : body.disabled ? "account.disable" : "account.enable";
let computers = 0;
try {
- if ("signOut" in parsed.data) {
+ if ("signOut" in body) {
signOutAccount(id);
computers = revokeWorkersOf(`acct:${id}`);
- } else setAccountDisabled(id, parsed.data.disabled);
+ } else if ("password" in body) await setAccountPasswordAsOwner(id, body.password);
+ else if ("email" in body) setAccountEmailAsOwner(id, body.email);
+ else setAccountDisabled(id, body.disabled);
} catch (e) {
return failed(e, access.actor, action, id);
}
diff --git a/src/components/admin-tokens.tsx b/src/components/admin-tokens.tsx
index c0ff0aef..f606cb3b 100644
--- a/src/components/admin-tokens.tsx
+++ b/src/components/admin-tokens.tsx
@@ -64,6 +64,8 @@ const ACTION_WORDS: Record<string, string> = {
"account.disable": "Switched an account off",
"account.enable": "Switched an account on",
"account.signout": "Signed an account out",
+ "account.password": "Set an account's password",
+ "account.email": "Changed an account's email",
"account.delete": "Deleted an account",
"run.delete": "Deleted a run",
"outputs.hide": "Hid results",
diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.ts
index 90d1cf7e..4c299b3b 100644
--- a/src/server/admin-tokens.ts
+++ b/src/server/admin-tokens.ts
@@ -45,7 +45,7 @@ export type Scope = (typeof SCOPES)[number];
/** What each scope lets a token do, in the words Settings shows. */
export const SCOPE_LABELS: Record<Scope, string> = {
"accounts:read": "See accounts",
- "accounts:write": "Switch accounts off and on, sign them out",
+ "accounts:write": "Switch accounts off and on, sign them out, set their password or email",
"accounts:delete": "Delete accounts",
"runs:read": "See accounts' runs: when, which model and how they ended (their prompts and results need Open accounts' files; emails need See accounts)",
"runs:delete": "Delete accounts' runs",
diff --git a/src/server/auth.ts b/src/server/auth.ts
index 09d18768..0b191447 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -404,6 +404,41 @@ export async function setAccountPassword(id: string, current: string, next: stri
return { ...account, ...changed };
}
+/**
+ * The owner sets an account's password (the admin API): the same 8-character rule and scrypt hash as sign-up. Every
+ * sign-in the account had ends (a new hash, and sessions_after), so it logs in again with the new password.
+ */
+export async function setAccountPasswordAsOwner(id: string, next: string): Promise<void> {
+ if (next.length < 8) throw new AccountError("Use at least 8 characters", 400);
+ if (!accountById(id)) throw new AccountError("No such account", 404);
+ const salt = crypto.randomBytes(16);
+ const hash = `${salt.toString("hex")}:${(await scrypt(next, salt)).toString("hex")}`;
+ const now = Date.now();
+ // The account may have gone while the password was hashed.
+ updateAccount(id, "password_hash = ?, password_changed_at = ?, sessions_after = ?", hash, now, now);
+}
+
+/**
+ * The owner changes an account's sign-in email (the admin API), normalised as sign-up does. Another account's email
+ * answers 409. Every sign-in the account had ends. Returns the email as stored.
+ */
+export function setAccountEmailAsOwner(id: string, email: string): string {
+ const e = normalizeEmail(email);
+ if (!e) throw new AccountError("Enter a valid email address", 400);
+ const taken = () => new AccountError("Another account already uses this email", 409);
+ try {
+ authWrite(() => {
+ const other = sql("SELECT id FROM auth_accounts WHERE email = ?").get(e) as { id: string } | undefined;
+ if (other && other.id !== id) throw taken();
+ if (!sql("UPDATE auth_accounts SET email = ?, sessions_after = ? WHERE id = ?").run(e, Date.now(), id).changes) throw new AccountError("No such account", 404);
+ });
+ } catch (err) {
+ if ((err as { code?: string }).code === "SQLITE_CONSTRAINT_UNIQUE" && /auth_accounts\.email/.test((err as Error).message)) throw taken();
+ throw err;
+ }
+ return e;
+}
+
/** How often a log-in is written down. */
const LOGIN_RECORD_MS = 60 * 60_000;
diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.ts
index 3a1125b8..10cccc25 100644
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@ -440,6 +440,54 @@ describe("admin tokens: accounts and files", () => {
expect((await routes.account.PATCH(req("/api/admin/accounts/nope", { token, method: "PATCH", body: { signOut: true } }), ctx({ id: "nope" }))).status).toBe(404);
});
+ it("sets an account's password: the same rule and hash as sign-up, every sign-in ends, and the log holds no password", async () => {
+ const { token } = make(["accounts:write"]);
+ const a = auth.createAccount(`setpw-${++n}@example.com`, "long enough");
+ const s = auth.createSession(a.id).value;
+ const patch = (body: unknown, id = a.id, t = token) => routes.account.PATCH(req(`/api/admin/accounts/${id}`, { token: t, method: "PATCH", body }), ctx({ id }));
+ expect((await patch({ password: "short" })).status).toBe(400);
+ expect(auth.checkAccount(a.email, "long enough")?.id).toBe(a.id);
+ const res = await patch({ password: "a brand new one" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toMatchObject({ id: a.id, email: a.email, disabled: false });
+ expect(auth.checkAccount(a.email, "long enough")).toBeNull();
+ expect(auth.checkAccount(a.email, "a brand new one")?.id).toBe(a.id);
+ expect(auth.accountById(a.id)!.hash).toMatch(/^[0-9a-f]{32}:[0-9a-f]{64}$/);
+ expect(auth.accountById(a.id)!.passwordChangedAt).toBeGreaterThan(0);
+ expect(auth.sessionViewer(s)).toBeNull();
+ await new Promise((r) => setTimeout(r, 5));
+ expect(auth.sessionViewer(auth.createSession(a.id).value)?.kind).toBe("account");
+ const row = auditRows().at(-1)!;
+ expect(row).toMatchObject({ action: "account.password", target: a.id, status: 200 });
+ expect(JSON.stringify(auditRows())).not.toContain("a brand new one");
+ expect((await patch({ password: "a brand new one" }, "nope")).status).toBe(404);
+ expect((await patch({ password: "a brand new one", signOut: true })).status).toBe(400);
+ // A token without accounts:write can't.
+ expect((await patch({ password: "another new one" }, a.id, make(["accounts:read"]).token)).status).toBe(403);
+ expect(auth.checkAccount(a.email, "a brand new one")?.id).toBe(a.id);
+ });
+
+ it("changes an account's sign-in email: normalised, never another account's, every sign-in ends", async () => {
+ const { token } = make(["accounts:write"]);
+ const a = auth.createAccount(`setmail-${++n}@example.com`, "long enough");
+ const other = auth.createAccount(`taken-${++n}@example.com`, "long enough");
+ const s = auth.createSession(a.id).value;
+ const patch = (body: unknown) => routes.account.PATCH(req(`/api/admin/accounts/${a.id}`, { token, method: "PATCH", body }), ctx({ id: a.id }));
+ expect((await patch({ email: "not an email" })).status).toBe(400);
+ expect((await patch({ email: other.email.toUpperCase() })).status).toBe(409);
+ expect(auth.sessionViewer(s)?.kind).toBe("account");
+ const res = await patch({ email: ` New-${n}@Example.COM ` });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toMatchObject({ id: a.id, email: `new-${n}@example.com` });
+ expect(auth.checkAccount(`new-${n}@example.com`, "long enough")?.id).toBe(a.id);
+ expect(auth.checkAccount(a.email, "long enough")).toBeNull();
+ expect(auth.sessionViewer(s)).toBeNull();
+ // Its own email again is no conflict.
+ expect((await patch({ email: `new-${n}@example.com` })).status).toBe(200);
+ expect(auditRows().filter((r) => r.action === "account.email").map((r) => r.status)).toEqual([400, 409, 200, 200]);
+ expect(JSON.stringify(auditRows().filter((r) => r.action === "account.email"))).not.toContain("example.com");
+ });
+
it("serves accounts', held and the owner's own files to outputs:view, and logs each view", async () => {
const { token, info } = make(["outputs:view"]);
const a = auth.createAccount(`files-${++n}@example.com`, "long enough");