CivitAI: API client, input parser and CIVITAI_TOKEN
First step towards CivitAI downloads. Lookups of models, versions and download access (login required, early access with its deadline), and a parser for civitai.com / .red / .green links, download links and AIR ids. Nothing uses it yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
29e6893a17
commit
765dac2ed2
6 files changed
+573
-1
No files matched your search
@@ -22,6 +22,11 @@ OIDC_CLIENT_SECRET=
|
||||
# (higher rate limits). Stays on the server; never sent to the browser or written to logs.
|
||||
HF_TOKEN=
|
||||
|
||||
# CivitAI API key (civitai.com or civitai.red → Account settings → API keys). Optional: public files
|
||||
# download without it, files whose creator requires a login need it. Early access still has to be
|
||||
# unlocked on CivitAI; Kaname never spends Buzz. Stays on the server.
|
||||
CIVITAI_TOKEN=
|
||||
|
||||
# Optional, comma-separated: only members of these groups (`groups` claim) can log in.
|
||||
OIDC_ALLOWED_GROUPS=
|
||||
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// CivitAI client: parsing and error mapping against a stubbed fetch. Bodies follow real API answers
|
||||
// (checked against civitai.com and civitai.red on 2026-11-10).
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { after, beforeEach, describe, it } from "node:test";
|
||||
import { CivitaiError, checkDownload, getAccess, getModel, getVersion, latestVersion, parseFile } from "./client";
|
||||
|
||||
process.env.CIVITAI_TOKEN = "test-token"; // coreEnv() reads the environment on the first request, not on import
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
let requests: { url: string; init?: RequestInit }[] = [];
|
||||
let respond: (url: string) => Response;
|
||||
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||||
|
||||
beforeEach(() => {
|
||||
requests = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const url = String(input instanceof Request ? input.url : input);
|
||||
requests.push({ url, init });
|
||||
return respond(url);
|
||||
}) as typeof fetch;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
});
|
||||
|
||||
const SHA = "DD08FA32F98D05A2443CA1419E46DF1575A0811F6E3B246D9DD47FF20F5EB66A";
|
||||
const file = {
|
||||
id: 1659952,
|
||||
sizeKB: 6938818.517578125,
|
||||
name: "JuggernautXL_Ragnarok_ByRunDiffusion.safetensors",
|
||||
type: "Model",
|
||||
metadata: { format: "SafeTensor", size: "full", fp: "fp16" },
|
||||
hashes: { AutoV2: "DD08FA32F9", SHA256: SHA },
|
||||
downloadUrl: "https://civitai.red/api/download/models/1759168",
|
||||
primary: true,
|
||||
};
|
||||
const model = {
|
||||
id: 133005,
|
||||
name: "Juggernaut XL",
|
||||
type: "Checkpoint",
|
||||
nsfw: true,
|
||||
creator: { username: "KandooAI", image: "https://image.civitai.com/x.jpeg" },
|
||||
tags: ["base model", "photorealistic"],
|
||||
description: "<p>Hi</p>",
|
||||
allowCommercialUse: ["Image", "Rent"],
|
||||
allowDerivatives: true,
|
||||
modelVersions: [
|
||||
{ id: 1, name: "old", baseModel: "SDXL 1.0", publishedAt: "2023-01-01T00:00:00.000Z", files: [] },
|
||||
{ id: 1759168, name: "Ragnarok", baseModel: "SDXL 1.0", publishedAt: "2025-05-07T21:02:16.940Z", status: "Published", files: [file] },
|
||||
{ id: 2, name: "draft", files: [] },
|
||||
],
|
||||
};
|
||||
|
||||
describe("parseFile", () => {
|
||||
it("turns sizeKB into exact bytes and lowercases the SHA-256", () => {
|
||||
const f = parseFile(file)!;
|
||||
assert.equal(f.size, 7105350162); // the storage's Content-Range total
|
||||
assert.equal(f.sha256, SHA.toLowerCase());
|
||||
assert.deepEqual([f.format, f.sizeVariant, f.fp, f.primary, f.type], ["SafeTensor", "full", "fp16", true, "Model"]);
|
||||
});
|
||||
|
||||
it("drops files whose name isn't a plain file name", () => {
|
||||
for (const name of ["../x.safetensors", "a/b.safetensors", "a\\b", "..", ""]) {
|
||||
assert.equal(parseFile({ ...file, name }), null, name);
|
||||
}
|
||||
assert.equal(parseFile({ ...file, hashes: { SHA256: "nothex" } })!.sha256, null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getModel", () => {
|
||||
it("sorts versions newest first and sends the token as a header", async () => {
|
||||
respond = () => json(model);
|
||||
const m = await getModel(133005);
|
||||
assert.deepEqual(m.versions.map((v) => v.id), [1759168, 1, 2]);
|
||||
assert.equal(latestVersion(m)?.id, 1759168);
|
||||
assert.equal(m.nsfw, true);
|
||||
assert.equal(m.creator?.username, "KandooAI");
|
||||
assert.equal(requests[0].url, "https://civitai.com/api/v1/models/133005");
|
||||
assert.equal((requests[0].init?.headers as Record<string, string>).Authorization, "Bearer test-token");
|
||||
assert.ok(!requests[0].url.includes("token"), "the token never goes into the URL");
|
||||
});
|
||||
|
||||
it("maps 404 to model_not_found", async () => {
|
||||
respond = () => json({ error: "No model with id 9" }, 404);
|
||||
await assert.rejects(getModel(9), (e: CivitaiError) => e.code === "model_not_found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getVersion / getAccess", () => {
|
||||
it("finds the model of a bare version id", async () => {
|
||||
respond = () => json({ id: 1759168, modelId: 133005, name: "Ragnarok", status: "Published", files: [file] });
|
||||
const v = await getVersion(1759168);
|
||||
assert.equal(v.modelId, 133005);
|
||||
assert.equal(v.files[0].id, 1659952);
|
||||
});
|
||||
|
||||
it("reads the access flags", async () => {
|
||||
respond = () => json({ requireAuth: true, checkPermission: true, earlyAccessEndsAt: "2026-11-15T16:00:38.148Z" });
|
||||
assert.deepEqual(await getAccess(3457797), { requireAuth: true, checkPermission: true, earlyAccessEndsAt: "2026-11-15T16:00:38.148Z" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkDownload", () => {
|
||||
it("accepts the redirect to storage without following it", async () => {
|
||||
respond = () => new Response(null, { status: 307, headers: { Location: "https://storage.example/x?X-Amz-Signature=y" } });
|
||||
await checkDownload(1759168, 1659952);
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(requests[0].init?.redirect, "manual");
|
||||
assert.equal(requests[0].url, "https://civitai.com/api/download/models/1759168?fileId=1659952");
|
||||
});
|
||||
|
||||
it("reports early access with its deadline", async () => {
|
||||
respond = () =>
|
||||
json({ error: "Early Access", deadline: "2026-11-15T16:00:38.148Z", message: "This asset is in Early Access. You can use Buzz access it now!" }, 403);
|
||||
await assert.rejects(checkDownload(3457797, 1), (e: CivitaiError) => {
|
||||
assert.equal(e.code, "early_access");
|
||||
assert.equal(e.deadline, "2026-11-15T16:00:38.148Z");
|
||||
assert.match(e.message, /until 2026-11-15/);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
it("tells an invalid token from a refused login", async () => {
|
||||
respond = (url) => (url.endsWith("/api/v1/me") ? json({ error: "Unauthorized" }, 401) : json({ error: "Unauthorized" }, 401));
|
||||
await assert.rejects(checkDownload(3457797, 1), (e: CivitaiError) => e.code === "invalid_token");
|
||||
|
||||
respond = (url) => (url.endsWith("/api/v1/me") ? json({ id: 1 }) : json({ error: "Unauthorized", message: "The creator of this asset requires you to be logged in to download it" }, 401));
|
||||
await assert.rejects(checkDownload(3457797, 1), (e: CivitaiError) => e.code === "login_required");
|
||||
});
|
||||
|
||||
it("maps a missing file and network errors", async () => {
|
||||
respond = () => json({ error: "File not found" }, 404);
|
||||
await assert.rejects(checkDownload(9, 9), (e: CivitaiError) => e.code === "file_not_found");
|
||||
respond = () => {
|
||||
throw new TypeError("fetch failed");
|
||||
};
|
||||
await assert.rejects(checkDownload(9, 9), (e: CivitaiError) => e.code === "network");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
// Minimal CivitAI API client: model and version metadata, and an access check for downloads.
|
||||
// Server-side only: it reads CIVITAI_TOKEN from the environment. Never import from client components.
|
||||
//
|
||||
// civitai.com and civitai.red serve the same API and data (lookups by id include mature models on
|
||||
// both), so every call goes to one host. Download URLs are built from ids here, not taken from the
|
||||
// API, whose links echo whatever host was asked.
|
||||
|
||||
import { coreEnv } from "@/lib/env";
|
||||
|
||||
const API = "https://civitai.com";
|
||||
const TIMEOUT_MS = 20_000;
|
||||
const USER_AGENT = "kaname-model-manager";
|
||||
|
||||
export type CivitaiErrorCode =
|
||||
| "invalid_token"
|
||||
| "model_not_found"
|
||||
| "version_not_found"
|
||||
| "file_not_found"
|
||||
| "login_required" // the creator requires a logged-in download and no token is set
|
||||
| "early_access" // paid early access, not unlocked for this account
|
||||
| "unavailable" // archived or taken down: no files to download
|
||||
| "rate_limited"
|
||||
| "network"
|
||||
| "unknown";
|
||||
|
||||
export class CivitaiError extends Error {
|
||||
constructor(
|
||||
public code: CivitaiErrorCode,
|
||||
message: string,
|
||||
public status?: number,
|
||||
/** Early access: when the version becomes free (ISO date). */
|
||||
public deadline?: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "CivitaiError";
|
||||
}
|
||||
}
|
||||
|
||||
export type CivitaiFile = {
|
||||
id: number;
|
||||
name: string;
|
||||
/** CivitAI's file type: "Model", "Pruned Model", "VAE", "Config", "Training Data", … */
|
||||
type: string;
|
||||
primary: boolean;
|
||||
/** Exact bytes (the API's sizeKB is bytes / 1024). */
|
||||
size: number;
|
||||
/** Lowercase hex, or null if CivitAI has no hash for the file. */
|
||||
sha256: string | null;
|
||||
format: string | null; // "SafeTensor", "PickleTensor", "GGUF", …
|
||||
sizeVariant: string | null; // "pruned" | "full"
|
||||
fp: string | null; // "fp16", "fp32", "bf16", …
|
||||
};
|
||||
|
||||
export type CivitaiVersion = {
|
||||
id: number;
|
||||
modelId: number;
|
||||
name: string;
|
||||
baseModel: string | null;
|
||||
publishedAt: string | null;
|
||||
/** Only on the versions endpoint; "Published" for every version the models endpoint lists. */
|
||||
status: string | null;
|
||||
files: CivitaiFile[];
|
||||
};
|
||||
|
||||
export type CivitaiModel = {
|
||||
id: number;
|
||||
name: string;
|
||||
/** "Checkpoint", "LORA", "TextualInversion", "VAE", "Controlnet", … */
|
||||
type: string;
|
||||
nsfw: boolean;
|
||||
creator: { username: string; image: string | null } | null;
|
||||
tags: string[];
|
||||
/** HTML from the creator; sanitize before showing it. */
|
||||
description: string | null;
|
||||
allowCommercialUse: string[];
|
||||
allowDerivatives: boolean | null;
|
||||
/** "Archived" or "TakenDown" when files are gone; null normally. */
|
||||
mode: string | null;
|
||||
/** Newest first. */
|
||||
versions: CivitaiVersion[];
|
||||
};
|
||||
|
||||
export type CivitaiAccess = {
|
||||
/** Downloads need a token (the creator requires a login, or early access). */
|
||||
requireAuth: boolean;
|
||||
/** Gated: early access or private; the account must have unlocked it. */
|
||||
checkPermission: boolean;
|
||||
earlyAccessEndsAt: string | null;
|
||||
};
|
||||
|
||||
function headers(): Record<string, string> {
|
||||
const h: Record<string, string> = { "User-Agent": USER_AGENT, Accept: "application/json" };
|
||||
const token = coreEnv().CIVITAI_TOKEN;
|
||||
if (token) h.Authorization = `Bearer ${token}`;
|
||||
return h;
|
||||
}
|
||||
|
||||
async function civitaiFetch(path: string, init: RequestInit = {}): Promise<Response> {
|
||||
try {
|
||||
return await fetch(`${API}${path}`, {
|
||||
...init,
|
||||
headers: { ...headers(), ...init.headers },
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
throw new CivitaiError("network", `Could not reach civitai.com (${reason}).`);
|
||||
}
|
||||
}
|
||||
|
||||
type ErrorBody = { error?: string; message?: string; deadline?: string };
|
||||
|
||||
async function errorBody(res: Response): Promise<ErrorBody> {
|
||||
try {
|
||||
const j = (await res.json()) as unknown;
|
||||
return j && typeof j === "object" ? (j as ErrorBody) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Is the configured token valid? Only called after a 401. */
|
||||
async function tokenIsValid(): Promise<boolean> {
|
||||
const res = await civitaiFetch("/api/v1/me");
|
||||
return res.ok;
|
||||
}
|
||||
|
||||
/** Map a failed response; `notFound` names what a 404 means for this request. */
|
||||
async function toCivitaiError(res: Response, notFound: CivitaiErrorCode, what: string): Promise<CivitaiError> {
|
||||
const body = await errorBody(res);
|
||||
const hasToken = Boolean(coreEnv().CIVITAI_TOKEN);
|
||||
if (res.status === 404) return new CivitaiError(notFound, `${what} not found on CivitAI.`, 404);
|
||||
if (res.status === 429) return new CivitaiError("rate_limited", "CivitAI rate limit hit. Try again in a minute.", 429);
|
||||
if (res.status === 403 && body.error === "Early Access") {
|
||||
const until = body.deadline ? ` until ${body.deadline.slice(0, 10)}` : "";
|
||||
return new CivitaiError(
|
||||
"early_access",
|
||||
`${what} is in early access${until}. Unlock it on CivitAI first (Kaname never spends Buzz), or wait.`,
|
||||
403,
|
||||
body.deadline,
|
||||
);
|
||||
}
|
||||
if (res.status === 401) {
|
||||
if (hasToken && !(await tokenIsValid())) {
|
||||
return new CivitaiError("invalid_token", "CIVITAI_TOKEN is invalid or expired.", 401);
|
||||
}
|
||||
return new CivitaiError(
|
||||
"login_required",
|
||||
hasToken
|
||||
? `CivitAI refused the download of ${what} for this token's account.`
|
||||
: `The creator of ${what} requires a login to download. Set CIVITAI_TOKEN.`,
|
||||
401,
|
||||
);
|
||||
}
|
||||
const msg = body.message ?? body.error ?? res.statusText;
|
||||
return new CivitaiError("unknown", `CivitAI API error ${res.status}: ${msg}`, res.status);
|
||||
}
|
||||
|
||||
// --- Parsing (the API's JSON is untrusted: check every field) ----------------------------------
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const obj = (v: unknown): Json => (v && typeof v === "object" && !Array.isArray(v) ? (v as Json) : {});
|
||||
const str = (v: unknown): string | null => (typeof v === "string" && v !== "" ? v : null);
|
||||
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
||||
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
|
||||
const posInt = (v: unknown): number | null => {
|
||||
const n = num(v);
|
||||
return n != null && Number.isInteger(n) && n > 0 ? n : null;
|
||||
};
|
||||
|
||||
export function parseFile(raw: unknown): CivitaiFile | null {
|
||||
const f = obj(raw);
|
||||
const id = posInt(f.id);
|
||||
const name = str(f.name);
|
||||
const sizeKB = num(f.sizeKB);
|
||||
// A file name becomes a path in the model folder: no directories, no dot-names.
|
||||
if (!id || !name || sizeKB == null || sizeKB < 0 || /[\\/\0]/.test(name) || name === "." || name === "..") return null;
|
||||
const sha = str(obj(f.hashes).SHA256);
|
||||
const meta = obj(f.metadata);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: str(f.type) ?? "Model",
|
||||
primary: f.primary === true,
|
||||
size: Math.round(sizeKB * 1024),
|
||||
sha256: sha && /^[0-9a-f]{64}$/i.test(sha) ? sha.toLowerCase() : null,
|
||||
format: str(meta.format),
|
||||
sizeVariant: str(meta.size),
|
||||
fp: str(meta.fp),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseVersion(raw: unknown, modelId?: number): CivitaiVersion | null {
|
||||
const v = obj(raw);
|
||||
const id = posInt(v.id);
|
||||
const mid = posInt(v.modelId) ?? modelId ?? null;
|
||||
if (!id || !mid) return null;
|
||||
return {
|
||||
id,
|
||||
modelId: mid,
|
||||
name: str(v.name) ?? String(id),
|
||||
baseModel: str(v.baseModel),
|
||||
publishedAt: str(v.publishedAt),
|
||||
status: str(v.status),
|
||||
files: arr(v.files)
|
||||
.map(parseFile)
|
||||
.filter((f): f is CivitaiFile => f !== null),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseModel(raw: unknown): CivitaiModel | null {
|
||||
const m = obj(raw);
|
||||
const id = posInt(m.id);
|
||||
const name = str(m.name);
|
||||
if (!id || !name) return null;
|
||||
const creator = obj(m.creator);
|
||||
const username = str(creator.username);
|
||||
const image = str(creator.image);
|
||||
const versions = arr(m.modelVersions)
|
||||
.map((v) => parseVersion(v, id))
|
||||
.filter((v): v is CivitaiVersion => v !== null)
|
||||
// Newest first; unpublished (no date) last.
|
||||
.sort((a, b) => (b.publishedAt ?? "").localeCompare(a.publishedAt ?? ""));
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
type: str(m.type) ?? "Other",
|
||||
nsfw: m.nsfw === true,
|
||||
creator: username ? { username, image: image?.startsWith("https://") ? image : null } : null,
|
||||
tags: arr(m.tags).filter((t): t is string => typeof t === "string"),
|
||||
description: str(m.description),
|
||||
allowCommercialUse: arr(m.allowCommercialUse).filter((t): t is string => typeof t === "string"),
|
||||
allowDerivatives: typeof m.allowDerivatives === "boolean" ? m.allowDerivatives : null,
|
||||
mode: str(m.mode),
|
||||
versions,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Calls --------------------------------------------------------------------------------------
|
||||
|
||||
/** A model with all its versions and their files. */
|
||||
export async function getModel(modelId: number): Promise<CivitaiModel> {
|
||||
const res = await civitaiFetch(`/api/v1/models/${modelId}`);
|
||||
if (!res.ok) throw await toCivitaiError(res, "model_not_found", `Model ${modelId}`);
|
||||
const model = parseModel(await res.json());
|
||||
if (!model) throw new CivitaiError("unknown", `CivitAI sent an unexpected answer for model ${modelId}.`);
|
||||
return model;
|
||||
}
|
||||
|
||||
/** One version (finds the model a bare version id belongs to). */
|
||||
export async function getVersion(versionId: number): Promise<CivitaiVersion> {
|
||||
const res = await civitaiFetch(`/api/v1/model-versions/${versionId}`);
|
||||
if (!res.ok) throw await toCivitaiError(res, "version_not_found", `Version ${versionId}`);
|
||||
const version = parseVersion(await res.json());
|
||||
if (!version) throw new CivitaiError("unknown", `CivitAI sent an unexpected answer for version ${versionId}.`);
|
||||
return version;
|
||||
}
|
||||
|
||||
/** What a download of this version needs (login, early access). */
|
||||
export async function getAccess(versionId: number): Promise<CivitaiAccess> {
|
||||
const res = await civitaiFetch(`/api/v1/model-versions/mini/${versionId}`);
|
||||
if (!res.ok) throw await toCivitaiError(res, "version_not_found", `Version ${versionId}`);
|
||||
const j = obj(await res.json());
|
||||
return {
|
||||
requireAuth: j.requireAuth === true,
|
||||
checkPermission: j.checkPermission === true,
|
||||
earlyAccessEndsAt: str(j.earlyAccessEndsAt),
|
||||
};
|
||||
}
|
||||
|
||||
/** The newest published version, or null if the model has none. */
|
||||
export function latestVersion(model: CivitaiModel): CivitaiVersion | null {
|
||||
return model.versions.find((v) => v.publishedAt && (v.status ?? "Published") === "Published") ?? null;
|
||||
}
|
||||
|
||||
/** The download endpoint for one file. Answers with a redirect to a presigned storage URL. */
|
||||
export function downloadUrl(versionId: number, fileId: number): string {
|
||||
return `${API}/api/download/models/${versionId}?fileId=${fileId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Can this file be downloaded with the configured token? Asks the download endpoint without following
|
||||
* its redirect, so nothing is downloaded. Throws a CivitaiError (login_required, early_access, …) if not.
|
||||
*/
|
||||
export async function checkDownload(versionId: number, fileId: number, what = `Version ${versionId}`): Promise<void> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(downloadUrl(versionId, fileId), {
|
||||
headers: headers(),
|
||||
redirect: "manual",
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
throw new CivitaiError("network", `Could not reach civitai.com (${reason}).`);
|
||||
}
|
||||
if (res.status >= 300 && res.status < 400) {
|
||||
await res.body?.cancel();
|
||||
return;
|
||||
}
|
||||
if (res.ok) {
|
||||
await res.body?.cancel(); // served directly: allowed, don't read the file
|
||||
return;
|
||||
}
|
||||
throw await toCivitaiError(res, "file_not_found", what);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { civitaiPageUrl, isCivitaiInput, parseCivitaiInput } from "./input";
|
||||
|
||||
describe("parseCivitaiInput", () => {
|
||||
it("reads model pages on every CivitAI domain", () => {
|
||||
for (const host of ["civitai.com", "civitai.red", "civitai.green", "www.civitai.com"]) {
|
||||
assert.deepEqual(parseCivitaiInput(`https://${host}/models/133005/juggernaut-xl`), { modelId: 133005, versionId: undefined });
|
||||
}
|
||||
assert.deepEqual(parseCivitaiInput("https://civitai.red/models/133005?modelVersionId=1759168"), { modelId: 133005, versionId: 1759168 });
|
||||
assert.deepEqual(parseCivitaiInput("civitai.com/models/4201"), { modelId: 4201, versionId: undefined });
|
||||
assert.deepEqual(parseCivitaiInput(" https://civitai.com/models/4201/ "), { modelId: 4201, versionId: undefined });
|
||||
});
|
||||
|
||||
it("reads download links as a version id", () => {
|
||||
assert.deepEqual(parseCivitaiInput("https://civitai.com/api/download/models/1759168?fileId=1659952"), { versionId: 1759168 });
|
||||
});
|
||||
|
||||
it("reads AIR and the short form", () => {
|
||||
assert.deepEqual(parseCivitaiInput("urn:air:sdxl:checkpoint:civitai:133005@1759168"), { modelId: 133005, versionId: 1759168 });
|
||||
assert.deepEqual(parseCivitaiInput("civitai:4201"), { modelId: 4201, versionId: undefined });
|
||||
assert.deepEqual(parseCivitaiInput("CivitAI:4201@501240"), { modelId: 4201, versionId: 501240 });
|
||||
});
|
||||
|
||||
it("ignores Hugging Face repos, other hosts and bad ids", () => {
|
||||
for (const s of [
|
||||
"Qwen/Qwen3-8B",
|
||||
"https://huggingface.co/Qwen/Qwen3-8B",
|
||||
"https://civitai.com.evil.example/models/1",
|
||||
"https://civitai.com/images/123",
|
||||
"https://civitai.com/models/abc",
|
||||
"https://civitai.com/models/0",
|
||||
"civitai:",
|
||||
"",
|
||||
]) {
|
||||
assert.equal(parseCivitaiInput(s), null, s);
|
||||
assert.equal(isCivitaiInput(s), false, s);
|
||||
}
|
||||
assert.deepEqual(parseCivitaiInput("https://civitai.com/models/4201?modelVersionId=x"), { modelId: 4201, versionId: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe("civitaiPageUrl", () => {
|
||||
it("links mature models to civitai.red", () => {
|
||||
assert.equal(civitaiPageUrl(4201), "https://civitai.com/models/4201");
|
||||
assert.equal(civitaiPageUrl(133005, { nsfw: true, versionId: 1759168 }), "https://civitai.red/models/133005?modelVersionId=1759168");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// Recognize CivitAI references in the add-model input. No imports: client components use it too.
|
||||
//
|
||||
// civitai.com (SFW only since 2026), civitai.red (everything) and civitai.green (old SFW domain)
|
||||
// share one catalog and one id space, so all three map to the same model and version ids.
|
||||
|
||||
export type CivitaiRef = { modelId?: number; versionId?: number };
|
||||
|
||||
const HOST = /^(?:www\.)?civitai\.(?:com|red|green)$/i;
|
||||
|
||||
/** A positive integer id, or undefined. */
|
||||
function id(s: string | null | undefined): number | undefined {
|
||||
if (!s || !/^\d{1,12}$/.test(s)) return undefined;
|
||||
const n = Number(s);
|
||||
return n > 0 ? n : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a CivitAI reference, or return null if the input isn't one. Accepted:
|
||||
* - model pages: https://civitai.red/models/133005/juggernaut-xl?modelVersionId=1759168
|
||||
* - download links: https://civitai.com/api/download/models/1759168 (a version id)
|
||||
* - AIR: urn:air:sdxl:checkpoint:civitai:133005@1759168
|
||||
* - short form: civitai:133005 or civitai:133005@1759168
|
||||
* At least one of modelId / versionId is set.
|
||||
*/
|
||||
export function parseCivitaiInput(input: string): CivitaiRef | null {
|
||||
const s = input.trim();
|
||||
|
||||
const air = s.match(/^(?:urn:air:[\w.-]+:[\w.-]+:)?civitai:(\d+)(?:@(\d+))?$/i);
|
||||
if (air) {
|
||||
const modelId = id(air[1]);
|
||||
if (!modelId) return null;
|
||||
return { modelId, versionId: id(air[2]) };
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(/^https?:\/\//i.test(s) ? s : `https://${s}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!HOST.test(url.hostname)) return null;
|
||||
const parts = url.pathname.split("/").filter(Boolean);
|
||||
const versionParam = id(url.searchParams.get("modelVersionId"));
|
||||
|
||||
if (parts[0] === "models") {
|
||||
const modelId = id(parts[1]);
|
||||
return modelId ? { modelId, versionId: versionParam } : null;
|
||||
}
|
||||
if (parts[0] === "api" && parts[1] === "download" && parts[2] === "models") {
|
||||
const versionId = id(parts[3]);
|
||||
return versionId ? { versionId } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Does the input look like a CivitAI reference (for routing the lookup)? */
|
||||
export function isCivitaiInput(input: string): boolean {
|
||||
return parseCivitaiInput(input) !== null;
|
||||
}
|
||||
|
||||
/** The model's page. Mature models only show on civitai.red. */
|
||||
export function civitaiPageUrl(modelId: number, opts: { versionId?: number; nsfw?: boolean } = {}): string {
|
||||
const host = opts.nsfw ? "civitai.red" : "civitai.com";
|
||||
const q = opts.versionId ? `?modelVersionId=${opts.versionId}` : "";
|
||||
return `https://${host}/models/${modelId}${q}`;
|
||||
}
|
||||
+3
-1
@@ -1,13 +1,15 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// Shared by the web app and the worker. Never import this from a client component:
|
||||
// it contains HF_TOKEN. Web code should go through "@/lib/server-env", which is guarded
|
||||
// it contains HF_TOKEN and CIVITAI_TOKEN. Web code should go through "@/lib/server-env", which is guarded
|
||||
// by "server-only".
|
||||
|
||||
const emptyToUndefined = (v: unknown) => (v === "" ? undefined : v);
|
||||
|
||||
const coreSchema = z.object({
|
||||
HF_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/** CivitAI API key: needed for files whose creator requires a login. Same name as the CivitAI CLI uses. */
|
||||
CIVITAI_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
MODELS_DIR: z.preprocess(emptyToUndefined, z.string().default("/models")),
|
||||
DATABASE_URL: z.preprocess(emptyToUndefined, z.string().default("file:/data/app.db")),
|
||||
MAX_CONCURRENT_DOWNLOADS: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).default(1)),
|
||||
|
||||
Reference in new issue
Block a user