Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(loras): detect Civitai early-access before download + improve contrast

Adam Eivy9cd3b5e0d219
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index d9d9aac38a..964cb4976c 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -92,7 +92,13 @@ export default function Loras() {
setInstallUrl('');
})
.catch((err) => {
- if (err?.code === 'CIVITAI_AUTH') {
+ // Early-access content is gated by Civitai membership, not by API
+ // key — routing into the key-prompt modal would be misleading
+ // because the user's key (saved or env) can't unlock it. Surface
+ // the message (which already includes hours-remaining) as a toast.
+ if (err?.code === 'CIVITAI_EARLY_ACCESS') {
+ toast.error(err.message || 'LoRA is in Civitai early-access');
+ } else if (err?.code === 'CIVITAI_AUTH') {
setAuthPrompt({ url, message: err.message || 'This LoRA needs an API key.' });
} else {
toast.error(err?.message || 'Install failed');
@@ -486,8 +492,8 @@ function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry
</div>
{message && (
- <div className="text-xs bg-port-warning/10 border border-port-warning/30 rounded px-3 py-2 text-port-warning flex items-start gap-2">
- <AlertTriangle size={14} className="shrink-0 mt-0.5" />
+ <div className="text-xs bg-port-warning/10 border border-port-warning/30 rounded px-3 py-2 text-amber-100 flex items-start gap-2">
+ <AlertTriangle size={14} className="shrink-0 mt-0.5 text-port-warning" />
<span>{message}</span>
</div>
)}
diff --git a/server/lib/civitai.js b/server/lib/civitai.js
index 0cdeb4a44b..a00a18aa19 100644
--- a/server/lib/civitai.js
+++ b/server/lib/civitai.js
@@ -217,6 +217,41 @@ export const applyDownloadToken = (downloadUrl, apiKey) => {
return `${downloadUrl}${sep}token=${encodeURIComponent(apiKey.trim())}`;
};
+// Detect early-access status from a Civitai modelVersion. New uploads on
+// Civitai can be flagged as "Early Access" — only paid Civitai supporters
+// can download them for a window (typically 1-14 days). The download
+// endpoint returns 401 in this case even with a valid API key, which would
+// otherwise route the user into the "set CIVITAI_API_KEY" modal where their
+// key is already saved. Detect ahead of the download attempt and surface a
+// distinct error so the UI can explain it without prompting for a key.
+//
+// Returns { early: false } for public versions, or
+// { early: true, endsAt: ISO|null, hoursRemaining: number|null } when
+// early-access. Field shapes vary across Civitai API versions, so we check
+// both `earlyAccessConfig.endsAt` and a `publishedAt + period` fallback.
+export const detectEarlyAccess = (version) => {
+ const availability = String(version?.availability || '').toLowerCase();
+ const config = version?.earlyAccessConfig;
+ const flagged = availability === 'earlyaccess' || (config && (config.period > 0 || config.endsAt));
+ if (!flagged) return { early: false };
+
+ let endsAt = null;
+ if (typeof config?.endsAt === 'string') {
+ endsAt = config.endsAt;
+ } else if (typeof version?.earlyAccessEndsAt === 'string') {
+ endsAt = version.earlyAccessEndsAt;
+ } else if (typeof version?.publishedAt === 'string' && Number.isFinite(config?.period)) {
+ const t = Date.parse(version.publishedAt);
+ if (Number.isFinite(t)) endsAt = new Date(t + config.period * 24 * 3600 * 1000).toISOString();
+ }
+ let hoursRemaining = null;
+ if (endsAt) {
+ const t = Date.parse(endsAt);
+ if (Number.isFinite(t)) hoursRemaining = Math.max(0, Math.round((t - Date.now()) / 3600_000));
+ }
+ return { early: true, endsAt, hoursRemaining };
+};
+
// Build the canonical sidecar shape. Stored next to the .safetensors file as
// `<filename>.metadata.json`. Decoupled from fetchCivitaiModel so callers can
// build it from a known model+version pair without a second API hit (the
diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.js
index 6c44c35783..7b5ff768cf 100644
--- a/server/lib/civitai.test.js
+++ b/server/lib/civitai.test.js
@@ -4,6 +4,7 @@ import {
baseModelToRunner,
buildAuthHeaders,
buildSidecar,
+ detectEarlyAccess,
fetchCivitaiModel,
normalizeCivitaiImageUrl,
parseCivitaiUrl,
@@ -159,6 +160,47 @@ describe('buildAuthHeaders / applyDownloadToken', () => {
});
});
+describe('detectEarlyAccess', () => {
+ it('reports public versions as not-early', () => {
+ expect(detectEarlyAccess({ availability: 'Public' })).toEqual({ early: false });
+ expect(detectEarlyAccess({})).toEqual({ early: false });
+ expect(detectEarlyAccess(null)).toEqual({ early: false });
+ });
+ it('flags EarlyAccess and surfaces endsAt directly', () => {
+ const future = new Date(Date.now() + 13 * 3600_000).toISOString();
+ const out = detectEarlyAccess({ availability: 'EarlyAccess', earlyAccessConfig: { endsAt: future } });
+ expect(out.early).toBe(true);
+ expect(out.endsAt).toBe(future);
+ expect(out.hoursRemaining).toBeGreaterThanOrEqual(12);
+ expect(out.hoursRemaining).toBeLessThanOrEqual(14);
+ });
+ it('computes endsAt from publishedAt + period when only the period is given', () => {
+ const publishedAt = new Date(Date.now() - 1 * 24 * 3600_000).toISOString();
+ const out = detectEarlyAccess({
+ availability: 'EarlyAccess',
+ publishedAt,
+ earlyAccessConfig: { period: 7 },
+ });
+ expect(out.early).toBe(true);
+ // Roughly 6 days * 24h remaining (allow ±2h drift for test execution time)
+ expect(out.hoursRemaining).toBeGreaterThanOrEqual(6 * 24 - 2);
+ expect(out.hoursRemaining).toBeLessThanOrEqual(6 * 24 + 2);
+ });
+ it('flags via earlyAccessConfig.period even when availability is missing', () => {
+ expect(detectEarlyAccess({ earlyAccessConfig: { period: 3, endsAt: '2099-01-01T00:00:00Z' } })).toMatchObject({
+ early: true,
+ endsAt: '2099-01-01T00:00:00Z',
+ });
+ });
+ it('handles flagged early-access with no resolvable end date', () => {
+ expect(detectEarlyAccess({ availability: 'EarlyAccess' })).toEqual({
+ early: true,
+ endsAt: null,
+ hoursRemaining: null,
+ });
+ });
+});
+
describe('normalizeCivitaiImageUrl', () => {
it('rewrites the original=true transform to a width-bounded variant', () => {
const original = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/1f686daa-ff68-4830-ae94-c318e8f9ee30/original=true/129269017.jpeg';
diff --git a/server/services/loras.js b/server/services/loras.js
index 1d94908398..e09840528a 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -28,6 +28,7 @@ import {
applyDownloadToken,
baseModelToRunner,
buildSidecar,
+ detectEarlyAccess,
fetchCivitaiModel,
normalizeCivitaiImageUrl,
parseCivitaiUrl,
@@ -177,15 +178,19 @@ export const resolveCivitaiKey = async () => {
// `.partial` from a previous crashed install (and prevents two concurrent
// installs of the same target from racing on the same temp path).
// fetchImpl is injectable for tests.
-const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} } = {}) => {
+const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} , hasApiKey = false } = {}) => {
const tmpPath = `${destPath}.${randomBytes(6).toString('hex')}.partial`;
const res = await fetchImpl(url, { headers, redirect: 'follow' });
if (!res.ok) {
if (res.status === 401 || res.status === 403) {
- throw new ServerError(
- `Civitai download rejected (${res.status}) — this LoRA may require an API key. Set CIVITAI_API_KEY in Settings and retry.`,
- { status: res.status, code: 'CIVITAI_AUTH' },
- );
+ // When a key was supplied and Civitai still rejects, the cause is
+ // almost always early-access content or a deactivated/scoped key —
+ // not a missing key. Don't tell the user to set a key they've
+ // already set; surface both possibilities instead.
+ const message = hasApiKey
+ ? `Civitai rejected the download (${res.status}) even with your saved API key. The LoRA is likely in early-access (Civitai supporters only) or your key has expired/been revoked.`
+ : `Civitai download rejected (${res.status}) — this LoRA may require an API key. Set CIVITAI_API_KEY in Settings and retry.`;
+ throw new ServerError(message, { status: res.status, code: 'CIVITAI_AUTH' });
}
throw new ServerError(`Civitai download failed: ${res.status} ${res.statusText}`, { status: 502, code: 'CIVITAI_DOWNLOAD_FAILED' });
}
@@ -216,6 +221,22 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
const apiKey = (typeof input?.apiKey === 'string' && input.apiKey.trim()) || (await resolveCivitaiKey());
const model = await fetchCivitaiModel(modelId, { apiKey, fetchImpl });
const version = pickVersion(model, versionId);
+ // Refuse early-access versions up front. The download endpoint would
+ // 401 even with a valid API key (only Civitai supporters can download
+ // during the early-access window), and routing the user into the
+ // "set API key" modal is misleading because their key isn't the issue.
+ const ea = detectEarlyAccess(version);
+ if (ea.early) {
+ const when = ea.hoursRemaining != null
+ ? (ea.hoursRemaining < 24
+ ? `~${ea.hoursRemaining}h`
+ : `~${Math.round(ea.hoursRemaining / 24)}d`)
+ : 'soon';
+ throw new ServerError(
+ `"${model.name}" v${version.id} is in Civitai early-access — only Civitai supporters can download it for ${when} more${ea.endsAt ? ` (until ${ea.endsAt})` : ''}. Try again once it goes public.`,
+ { status: 403, code: 'CIVITAI_EARLY_ACCESS' },
+ );
+ }
const file = pickPrimaryFile(version);
if (!file?.downloadUrl) {
throw new ServerError(
@@ -259,6 +280,7 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
await downloadToFile(tokenized, destPath, {
fetchImpl,
headers: { 'User-Agent': 'PortOS/civitai-installer' },
+ hasApiKey: !!apiKey,
});
const sidecar = buildSidecar({ model, version, file, filename });