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.

Your keys: an empty balance shows Add credit, and a saved key can be checked again

Adarshe217e019a5ba
diff --git a/src/app/api/account/keys/[provider]/route.ts b/src/app/api/account/keys/[provider]/route.ts
index e6b9ad2d..f8773e48 100644
--- a/src/app/api/account/keys/[provider]/route.ts
+++ b/src/app/api/account/keys/[provider]/route.ts
@@ -1,10 +1,10 @@
import { z } from "zod";
import { isCloudProvider, NOT_ACCOUNT_KEYS, type CloudProvider } from "@/lib/your-keys";
-import { accountKeyInfo, cleanKey, removeAccountKey, saveAccountKey } from "@/server/account-keys";
+import { accountKey, accountKeyInfo, cleanKey, markKeyBalanceEmpty, markKeyGood, markKeyRejected, removeAccountKey, saveAccountKey } from "@/server/account-keys";
import { accountKeyRecord, LoginGuard, requestAccount } from "@/server/auth";
import { hit, unhit } from "@/server/rate";
import { SecretBoxError } from "@/server/secret-box";
-import { checkKey, runsGoingMessage, runsOnKey, stopRunsOnKey } from "@/server/your-keys";
+import { checkKey, recheckKey, runsGoingMessage, runsOnKey, stopRunsOnKey } from "@/server/your-keys";
/**
* Settings → Your keys: add, replace or remove the account's own fal.ai key or Replicate token. PUT checks the key with
@@ -44,7 +44,7 @@ function countCheck(id: string, headers: Headers): { ok: true } | { ok: false; r
return { ok: true };
}
-const Body = z.object({ key: z.string().max(400), stopRuns: z.boolean().optional() });
+const Body = z.union([z.object({ recheck: z.literal(true) }).strict(), z.object({ key: z.string().max(400), stopRuns: z.boolean().optional() })]);
/** The account asking and the provider named, or the answer for anyone else. */
async function who(request: Request, ctx: RouteContext<"/api/account/keys/[provider]">): Promise<{ refused: Response } | { id: string; provider: CloudProvider }> {
@@ -60,12 +60,26 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/account/keys
if ("refused" in w) return w.refused;
const { id, provider } = w;
const parsed = Body.safeParse(await request.json().catch(() => null));
- const key = parsed.success ? cleanKey(parsed.data.key) : null;
- if (!parsed.success || !key) return answer(400, { error: "Paste the whole key, without spaces." });
+ // "Check again": the saved key, asked of its provider again (a refusal or an empty balance noted before may be over).
+ if (parsed.success && "recheck" in parsed.data) {
+ const saved = accountKey(id, provider);
+ if (!saved) return answer(404, { error: "Add your key first." });
+ const counted = countCheck(id, request.headers);
+ if (!counted.ok) return answer(429, { error: "Too many checks. Wait a minute." }, { "Retry-After": String(counted.retryAfterS) });
+ const again = await recheckKey(provider, saved);
+ if (again.ok) {
+ markKeyGood(id, provider);
+ if (again.balance) markKeyBalanceEmpty(id, provider, saved);
+ } else if (again.rejected) markKeyRejected(id, provider, saved);
+ const info = accountKeyInfo(id)[provider];
+ return again.ok ? answer(200, { provider, ...info }) : answer(again.status, { error: again.error, ...(again.details && { details: again.details }), ...(info && { info }) });
+ }
+ const key = parsed.success && "key" in parsed.data ? cleanKey(parsed.data.key) : null;
+ if (!parsed.success || !("key" in parsed.data) || !key) return answer(400, { error: "Paste the whole key, without spaces." });
const counted = countCheck(id, request.headers);
if (!counted.ok) return answer(429, { error: "Too many checks. Wait a minute." }, { "Retry-After": String(counted.retryAfterS) });
const check = await checkKey(provider, key);
- if (!check.ok) return answer(check.status, { error: check.error });
+ if (!check.ok) return answer(check.status, { error: check.error, ...(check.details && { details: check.details }) });
const said = { detail: check.detail, ...(check.note && { note: check.note }) };
if (new URL(request.url).searchParams.get("test") === "1") return answer(200, { provider, ok: true, ...said });
// Replacing a key runs are going on: they stop first, with the key they were sent with.
@@ -74,7 +88,9 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/account/keys
if (going.length) await stopRunsOnKey(id, provider);
try {
const info = saveAccountKey(id, provider, key);
- return answer(200, { provider, ...info, ...said });
+ // A key that works on an account with nothing on it yet: Settings says Add credit until a run is taken.
+ if (check.balance) markKeyBalanceEmpty(id, provider, key);
+ return answer(200, { provider, ...(accountKeyInfo(id)[provider] ?? info), ...said });
} catch (e) {
if (e instanceof SecretBoxError) return answer(503, { error: e.message });
throw e;
diff --git a/src/components/keys/your-keys.tsx b/src/components/keys/your-keys.tsx
index eca55dbc..71782ce2 100644
--- a/src/components/keys/your-keys.tsx
+++ b/src/components/keys/your-keys.tsx
@@ -1,7 +1,8 @@
"use client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { AlertTriangle, Check, ExternalLink, KeyRound, Loader2 } from "lucide-react";
+import { AlertTriangle, Check, CreditCard, ExternalLink, KeyRound, Loader2 } from "lucide-react";
+import { BILLING_URL } from "@/lib/diagnose";
import Link from "next/link";
import { useEffect, useId, useState } from "react";
import { toast } from "sonner";
@@ -180,6 +181,26 @@ function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo |
const [replacing, setReplacing] = useState(false);
const [confirm, setConfirm] = useState<null | { going?: string }>(null);
const [busy, setBusy] = useState(false);
+ const [checking, setChecking] = useState(false);
+ const [checkNote, setCheckNote] = useState<{ words: string; details?: string } | null>(null);
+ // Check again: the saved key asked of its provider again (free, nothing runs). A refusal or an empty balance noted on a
+ // run is cleared when the provider says the key works now.
+ const checkAgain = async () => {
+ setChecking(true);
+ setCheckNote(null);
+ try {
+ const r = await fetch(`/api/account/keys/${provider}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ recheck: true }) });
+ const j = (await r.json().catch(() => ({}))) as KeyInfo & { error?: string; details?: string };
+ changed();
+ if (r.ok) toast.success(j.balanceEmptyAt ? `Your ${p.label} key works, but its balance is empty. Add credit, then run.` : `Your ${p.label} key works.`);
+ else setCheckNote({ words: j.error ?? "We couldn't check your key. Try again in a minute.", ...(j.details && { details: j.details }) });
+ } catch {
+ setCheckNote({ words: "We couldn't check your key. Check this computer's internet, then try again." });
+ } finally {
+ setChecking(false);
+ }
+ };
+ const empty = !!info?.readable && !info.rejectedAt && !!info.balanceEmptyAt;
const remove = async (stopRuns: boolean) => {
setBusy(true);
@@ -205,11 +226,23 @@ function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo |
<h3 className="text-[14px] font-medium">{p.label}</h3>
<p className="text-[12px] text-muted-foreground">{p.blurb}</p>
</div>
- {info?.readable && !info.rejectedAt && (
+ {info?.readable && !info.rejectedAt && !empty && (
<span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-[12px] font-medium text-emerald-700 dark:text-emerald-400">
<Check className="size-3" /> Ready
</span>
)}
+ {empty && (
+ // The key works, but its provider account has no balance left: the badge is the way to add some.
+ <a
+ href={BILLING_URL[provider]}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex shrink-0 items-center gap-1 rounded-full bg-highlight px-2 py-0.5 text-[12px] font-medium text-highlight-foreground hover:opacity-90"
+ >
+ <CreditCard className="size-3" /> Add credit
+ <ExternalLink className="size-3 opacity-60" aria-hidden />
+ </a>
+ )}
</div>
{info && !replacing ? (
<>
@@ -229,9 +262,20 @@ function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo |
{info.readable && info.rejectedAt && (
<p className="inline-flex items-start gap-1.5 text-[13px] text-destructive">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
- {p.label} stopped accepting this key on {day(info.rejectedAt)}. Replace it, or remove it.
+ {p.label} stopped accepting this key on {day(info.rejectedAt)}. Replace it, or check it again.
+ </p>
+ )}
+ {empty && (
+ <p className="text-[13px] text-muted-foreground">
+ Your {p.label} balance ran out on {day(info.balanceEmptyAt!)}. Add credit on {p.label}, then press Check again.
</p>
)}
+ {checkNote && (
+ <div aria-live="polite" className="space-y-0.5">
+ <p className="text-[13px]">{checkNote.words}</p>
+ {checkNote.details && <p className="font-mono text-[10.5px] text-muted-foreground/80">{checkNote.details}</p>}
+ </div>
+ )}
{confirm ? (
confirm.going ? (
<RunsGoing message={confirm.going} action="Stop runs and remove" busy={busy} onGo={() => void remove(true)} onKeep={() => setConfirm(null)} />
@@ -256,6 +300,11 @@ function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo |
<Button size="sm" variant="secondary" onClick={() => setReplacing(true)}>
{info.readable ? "Replace" : "Add again"}
</Button>
+ {info.readable && (
+ <Button size="sm" variant="ghost" onClick={() => void checkAgain()} disabled={checking}>
+ {checking && <Loader2 className="animate-spin" />} Check again
+ </Button>
+ )}
<Button size="sm" variant="ghost" onClick={() => setConfirm({})}>
Remove
</Button>
diff --git a/src/lib/your-keys.ts b/src/lib/your-keys.ts
index e7935c87..d582c1be 100644
--- a/src/lib/your-keys.ts
+++ b/src/lib/your-keys.ts
@@ -33,6 +33,8 @@ export interface KeyInfo {
readable: boolean;
/** When the provider refused it in a run. */
rejectedAt?: number;
+ /** When a run (or the check) found its provider account's balance empty: "Add credit" until it takes a run again. */
+ balanceEmptyAt?: number;
}
/** GET /api/account/keys. */
@@ -99,12 +101,26 @@ export function cloudVersionKey(
has: (id: string) => boolean,
getModel: (id: string) => Routed | undefined,
): CloudProvider | null {
+ return cloudVersion(preset, model, keys, has, getModel)?.provider ?? null;
+}
+
+/**
+ * The tool's cloud version that one of the account's keys runs: the key, the model, and (another model) its operation
+ * there. What "Run with your fal.ai key" runs, once, before Run or on a run that couldn't reach the GPU.
+ */
+export function cloudVersion(
+ preset: Parameters<typeof presetRoutes>[0] | undefined,
+ model: (Routed & { id: string }) | undefined,
+ keys: readonly CloudProvider[],
+ has: (id: string) => boolean,
+ getModel: (id: string) => Routed | undefined,
+): { provider: CloudProvider; modelId: string; op?: string } | null {
if (!keys.length) return null;
- const ids = preset ? presetRoutes(preset, "cloud", has).map((r) => r.modelId) : model && dualEngine(model as Parameters<typeof dualEngine>[0]) ? [model.id] : [];
- for (const id of ids) {
+ const routes: { modelId: string; op?: string }[] = preset ? presetRoutes(preset, "cloud", has) : model && dualEngine(model as Parameters<typeof dualEngine>[0]) ? [{ modelId: model.id }] : [];
+ for (const { modelId: id, op } of routes) {
const m = getModel(id);
const p = m && CLOUD_PROVIDERS.find((k) => keys.includes(k) && m.routes.some((r) => r.provider === k));
- if (p) return p;
+ if (p) return { provider: p, modelId: id, ...(op && id !== model?.id && { op }) };
}
return null;
}
diff --git a/src/server/account-keys.ts b/src/server/account-keys.ts
index be17020d..a5826b5c 100644
--- a/src/server/account-keys.ts
+++ b/src/server/account-keys.ts
@@ -2,6 +2,7 @@ import "server-only";
import { CLOUD_PROVIDERS, type CloudProvider, type KeyInfo } from "@/lib/your-keys";
import { accountKeyRecord, setAccountKey } from "./auth";
import { accountKeyContext, open, seal } from "./secret-box";
+import { balanceEmptyAt, clearBalanceEmpty, markBalanceEmpty } from "./key-notes";
import { savedSetting } from "./settings";
/**
@@ -21,7 +22,8 @@ export function accountKey(id: string, p: CloudProvider): string | null {
export function accountKeyInfo(id: string): Record<CloudProvider, KeyInfo | null> {
const info = (p: CloudProvider): KeyInfo | null => {
const r = accountKeyRecord(id, p);
- return r ? { last4: r.last4, addedAt: r.addedAt, readable: accountKey(id, p) !== null, ...(r.rejectedAt && { rejectedAt: r.rejectedAt }) } : null;
+ const empty = r ? balanceEmptyAt(id, p, r.addedAt) : undefined;
+ return r ? { last4: r.last4, addedAt: r.addedAt, readable: accountKey(id, p) !== null, ...(r.rejectedAt && { rejectedAt: r.rejectedAt }), ...(empty && { balanceEmptyAt: empty }) } : null;
};
return { fal: info("fal"), replicate: info("replicate") };
}
@@ -36,11 +38,13 @@ export function cleanKey(raw: unknown): string | null {
export function saveAccountKey(id: string, p: CloudProvider, key: string): KeyInfo {
const stored = { sealed: seal(key, accountKeyContext(id, p)), last4: key.slice(-4), addedAt: Date.now() };
setAccountKey(id, p, stored);
+ clearBalanceEmpty(id, p);
return { last4: stored.last4, addedAt: stored.addedAt, readable: true };
}
export function removeAccountKey(id: string, p: CloudProvider): void {
setAccountKey(id, p, null);
+ clearBalanceEmpty(id, p);
}
/** The provider refused the key in a run: Settings says so. Only when `used` is still the saved key (not one replaced since). */
@@ -50,12 +54,41 @@ export function markKeyRejected(id: string, p: CloudProvider, used: string): voi
setAccountKey(id, p, { ...record, rejectedAt: Date.now() });
}
+/**
+ * The provider said the key works but its account has no balance left (a run, or the free check): Settings says "Add
+ * credit", and the key isn't offered for "Run with your … key" until it takes a run again. Only when `used` is still the
+ * saved key.
+ */
+export function markKeyBalanceEmpty(id: string, p: CloudProvider, used: string): void {
+ const record = accountKeyRecord(id, p);
+ if (!record || accountKey(id, p) !== used) return;
+ markBalanceEmpty(id, p, record.addedAt);
+}
+
+/** The provider took a run on the key, or its check passed: a refusal or an empty balance noted before is over. */
+export function markKeyGood(id: string, p: CloudProvider): void {
+ const record = accountKeyRecord(id, p);
+ if (!record) return;
+ if (record.rejectedAt) setAccountKey(id, p, { sealed: record.sealed, last4: record.last4, addedAt: record.addedAt });
+ if (balanceEmptyAt(id, p, record.addedAt)) clearBalanceEmpty(id, p);
+}
+
/** The studio lets accounts run paid models on their own keys: it isn't open-source only (Settings → Engine mode). */
export const paidAllowed = () => savedSetting("engineMode") !== "open";
/** The providers the account has a key for that this server can open. */
export const accountProviders = (id: string): CloudProvider[] => CLOUD_PROVIDERS.filter((p) => accountKey(id, p) !== null);
+/**
+ * The providers whose key "Run with your … key" may offer: one this server can open that the provider didn't refuse and
+ * whose balance isn't known to be empty (pressing it would only fail again).
+ */
+export const usableProviders = (id: string): CloudProvider[] =>
+ CLOUD_PROVIDERS.filter((p) => {
+ const r = accountKeyRecord(id, p);
+ return !!r && !r.rejectedAt && !balanceEmptyAt(id, p, r.addedAt) && accountKey(id, p) !== null;
+ });
+
/**
* The engine mode an account's work runs with: "both" (open models on its own GPU, paid ones on its own keys) while it
* has a key this server can open and the studio isn't open-source only; otherwise "open".
diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.ts
index ab345ae7..32c0d9f7 100644
--- a/src/server/account-sweep.ts
+++ b/src/server/account-sweep.ts
@@ -13,6 +13,7 @@ import { strayAccountIds } from "./auth-store";
import { accountEvent, accountFacts } from "./billing";
import { db } from "./db";
import { handOversDone } from "./generations";
+import { forgetKeyNotes } from "./key-notes";
import { deleteForever } from "./library";
import { deleteAsset, scratchDir } from "./storage";
@@ -48,6 +49,7 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: n
const files = (db().prepare("SELECT id FROM assets WHERE account_id = ?").all(id) as { id: string }[]).map((r) => r.id);
for (const f of files) deleteAsset(f);
clearAccountLoras(id);
+ forgetKeyNotes(id);
deleteAccountCanvases(id);
// A tool's own rows under its projects go before the projects themselves.
deleteAccountCinema(id);
diff --git a/src/server/key-notes.ts b/src/server/key-notes.ts
new file mode 100644
index 00000000..454a841f
--- /dev/null
+++ b/src/server/key-notes.ts
@@ -0,0 +1,54 @@
+import "server-only";
+import type { CloudProvider } from "@/lib/your-keys";
+import { db } from "./db";
+
+/**
+ * What a run last learnt of an account's own key that its sealed record doesn't hold: that the provider account's balance
+ * ran out (Settings → Your keys then says "Add credit" instead of "Ready"). Tied to the key it was learnt for (its
+ * added_at), so a key replaced since reads as new. Kept in a table of its own, made here when first used (no numbered
+ * migration). Never the key.
+ */
+
+/** Databases the table was made in (once each). */
+const ready = new WeakSet<object>();
+
+function table() {
+ const d = db();
+ if (!ready.has(d)) {
+ d.exec(`CREATE TABLE IF NOT EXISTS account_key_notes (
+ account_id TEXT NOT NULL,
+ provider TEXT NOT NULL,
+ added_at INTEGER NOT NULL,
+ balance_empty_at INTEGER,
+ PRIMARY KEY (account_id, provider)
+ )`);
+ ready.add(d);
+ }
+ return d;
+}
+
+/** The key (added at `addedAt`) works, but the provider account's balance ran out. */
+export function markBalanceEmpty(id: string, p: CloudProvider, addedAt: number, at = Date.now()): void {
+ table()
+ .prepare(
+ `INSERT INTO account_key_notes (account_id, provider, added_at, balance_empty_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT (account_id, provider) DO UPDATE SET added_at = excluded.added_at, balance_empty_at = excluded.balance_empty_at`,
+ )
+ .run(id, p, addedAt, at);
+}
+
+/** The provider took a run (or the free check passed) on the key: its balance is fine again. */
+export function clearBalanceEmpty(id: string, p: CloudProvider): void {
+ table().prepare("DELETE FROM account_key_notes WHERE account_id = ? AND provider = ?").run(id, p);
+}
+
+/** When the balance of the key added at `addedAt` was found empty, if it was. */
+export function balanceEmptyAt(id: string, p: CloudProvider, addedAt: number): number | undefined {
+ const r = table().prepare("SELECT added_at, balance_empty_at FROM account_key_notes WHERE account_id = ? AND provider = ?").get(id, p) as { added_at: number; balance_empty_at: number | null } | undefined;
+ return r && r.added_at === addedAt && r.balance_empty_at ? r.balance_empty_at : undefined;
+}
+
+/** Everything noted for an account (its account is deleted). */
+export function forgetKeyNotes(id: string): void {
+ table().prepare("DELETE FROM account_key_notes WHERE account_id = ?").run(id);
+}
diff --git a/src/server/provider-keys.ts b/src/server/provider-keys.ts
index bcda584e..0bb7850e 100644
--- a/src/server/provider-keys.ts
+++ b/src/server/provider-keys.ts
@@ -1,6 +1,6 @@
import "server-only";
import { addKeyMessage, balanceMessage, CLOUD_KEY, keyRejectedMessage, type CloudProvider } from "@/lib/your-keys";
-import { accountKey, markKeyRejected } from "./account-keys";
+import { accountKey, markKeyBalanceEmpty, markKeyRejected } from "./account-keys";
import { ProviderError } from "./providers/types";
import { getSetting } from "./settings";
import { tenant, tenantAccount } from "./tenant";
@@ -56,7 +56,11 @@ export function accountKeyError(p: CloudProvider, status: number, text: string,
// `said`: the provider's own words (the key already taken out), for the run's details line and to tell a key refused
// from a model the key may not run (src/lib/diagnose.ts).
const said = (e: ProviderError) => Object.assign(e, { said: text });
- if (balanceRefusal(status, text)) return said(new ProviderError(balanceMessage(p), status));
+ if (balanceRefusal(status, text)) {
+ // Settings → Your keys says "Add credit", and the key isn't offered elsewhere until it takes a run again.
+ markKeyBalanceEmpty(account, p, used);
+ return said(new ProviderError(balanceMessage(p), status));
+ }
if (status === 401 || status === 403) {
if (status === 401) markKeyRejected(account, p, used);
return said(new ProviderError(keyRejectedMessage(p), status));
diff --git a/src/server/your-keys.ts b/src/server/your-keys.ts
index 4cf4b876..af0bfb42 100644
--- a/src/server/your-keys.ts
+++ b/src/server/your-keys.ts
@@ -11,22 +11,56 @@ import { testReplicateKey } from "./providers/replicate";
* removes or replaces. The key itself is only ever sent to its provider; nothing here logs it or answers with it.
*/
+/** The waits before the free check is asked again when the provider was busy, down or out of reach. Tests make them shorter. */
+export const KEY_CHECK = { waitsMs: [1_000, 3_000] };
+
+/** A check that says nothing about the key (the provider busy, down, or out of reach): worth asking again in a moment. */
+const passing = (c: KeyCheck) => !c.ok && (c.reason === "unreachable" || (c.reason === "odd" && (c.status === 429 || (c.status ?? 0) >= 500)));
+
+/** The provider's free check of a key, asked again (twice, with a growing wait) while the provider is busy or down. */
+export async function testKey(p: CloudProvider, key: string): Promise<KeyCheck> {
+ let check: KeyCheck = p === "fal" ? await testFalKey(key) : await testReplicateKey(key);
+ for (const ms of KEY_CHECK.waitsMs) {
+ if (!passing(check)) break;
+ await new Promise((r) => setTimeout(r, ms));
+ check = p === "fal" ? await testFalKey(key) : await testReplicateKey(key);
+ }
+ return check;
+}
+
+/** What a check that couldn't tell said: plain words, the provider's status in `details`. */
+function unclear(p: CloudProvider, check: KeyCheck & { ok: false }): { ok: false; error: string; status: number; details?: string } {
+ const { label } = CLOUD_KEY[p];
+ return check.reason === "unreachable"
+ ? { ok: false, status: 503, error: `We couldn't reach ${label} to check your key. Try again in a minute.` }
+ : { ok: false, status: 503, error: `${label} is busy right now, so we couldn't check your key. Try again in a minute.`, ...(check.status && { details: `${label} answered ${check.status}` }) };
+}
+
/**
* A key checked with its provider before it is saved: a free call that runs nothing, with the typed key only. A key that
- * works on a provider account with no balance left is saved too, with a note that says to top it up.
+ * works on a provider account with no balance left is saved too, with a note that says to top it up (`balance`).
*/
-export async function checkKey(p: CloudProvider, key: string): Promise<{ ok: true; detail: string; note?: string } | { ok: false; error: string; status: number }> {
+export async function checkKey(p: CloudProvider, key: string): Promise<{ ok: true; detail: string; note?: string; balance?: true } | { ok: false; error: string; status: number; details?: string }> {
const { label } = CLOUD_KEY[p];
- const check: KeyCheck = p === "fal" ? await testFalKey(key) : await testReplicateKey(key);
+ const check = await testKey(p, key);
if (check.ok) return { ok: true, detail: check.detail };
- if (check.reason === "balance") return { ok: true, detail: "Key accepted", note: emptyBalanceNote(p) };
+ if (check.reason === "balance") return { ok: true, detail: "Key accepted", note: emptyBalanceNote(p), balance: true };
if (check.reason === "rejected") {
const hint = settingProblem(CLOUD_KEY[p].setting, key);
return { ok: false, status: 422, error: `${label} didn't accept this key. ${hint ? `${hint}.` : `Copy it again from ${label}.`}` };
}
// 503, not 502: a proxy in front (Cloudflare) answers an origin's 502 with its own page, and these words would be lost.
- if (check.reason === "unreachable") return { ok: false, status: 503, error: `Couldn't reach ${label} to check the key, so it wasn't saved. Try again in a moment.` };
- return { ok: false, status: 503, error: `${label} answered ${check.status ?? "oddly"}, so the key couldn't be checked. Try again in a moment.` };
+ return unclear(p, check);
+}
+
+/** The saved key checked again (Settings' "Check again"): what the provider says of it now. */
+export async function recheckKey(p: CloudProvider, key: string): Promise<{ ok: true; balance?: true } | { ok: false; rejected?: true; error: string; status: number; details?: string }> {
+ const { label } = CLOUD_KEY[p];
+ const check = await testKey(p, key);
+ if (check.ok) return { ok: true };
+ if (check.reason === "balance") return { ok: true, balance: true };
+ if (check.reason === "rejected") return { ok: false, rejected: true, status: 422, error: `${label} still doesn't accept this key. Replace it with a new one from ${label}.` };
+ return unclear(p, check);
}
/** The account's runs going on a provider now (queued, running, or a step waiting to be sent there). */