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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(loras,civitai): address local code-review findings
Adam Eivy8d60d560461e
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex d8215b4290..4b226c2cd8 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -37,9 +37,8 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }return () => clearInterval(t);}, [fetchJobs]);- const handleCancel = async (id) => {- try {- await cancelMediaJob(id);+ const handleCancel = (id) => cancelMediaJob(id)+ .then(() => {// Optimistic update: queued jobs flip to 'canceled' immediately (the// worker won't pick them up). For running jobs leave the server status// alone and track a UI-only `cancelRequested` flag — the next poll@@ -50,10 +49,8 @@ export default function MediaJobsQueue({ kind, recentLimit = 5, className = '' }return { ...j, cancelRequested: true };}));toast.success('Cancel requested');- } catch (err) {- toast.error(err.message || 'Cancel failed');- }- };+ })+ .catch((err) => toast.error(err?.message || 'Cancel failed'));const live = jobs.filter((j) => j.status === 'queued' || j.status === 'running');const recent = jobs.filter((j) => j.status !== 'queued' && j.status !== 'running').slice(0, recentLimit);diff --git a/server/lib/civitai.js b/server/lib/civitai.jsindex 1def8b34f5..5232828bbb 100644--- a/server/lib/civitai.js+++ b/server/lib/civitai.js@@ -53,18 +53,25 @@ export const parseCivitaiUrl = (raw) => {const bareId = trimmed.match(/^(?:civitai:)?(\d{1,12})$/);if (bareId) return { modelId: bareId[1], versionId: null };- // URL.parse can throw on malformed input — wrap in a guard rather than try/catch.if (!/^https?:\/\//i.test(trimmed)) {throw new ServerError(`Civitai URL must start with http(s):// — got "${trimmed.slice(0, 60)}"`,{ status: 400, code: 'CIVITAI_BAD_URL' },);}+ // The regex above accepts the http(s) prefix shape, but malformed+ // hostnames / brackets / encoded segments still throw `TypeError: Invalid+ // URL` from the constructor. Convert to a 400 ServerError so callers get+ // the expected error contract instead of a 500.let parsed;- // URL constructor throws on truly malformed inputs; the regex above already- // accepted the http(s) prefix shape so this is the catch-all for invalid- // hostnames / ports / encoded segments.- parsed = new URL(trimmed);+ try {+ parsed = new URL(trimmed);+ } catch {+ throw new ServerError(+ `Malformed URL: "${trimmed.slice(0, 60)}"`,+ { status: 400, code: 'CIVITAI_BAD_URL' },+ );+ }if (!CIVITAI_HOSTS.has(parsed.hostname.toLowerCase())) {throw new ServerError(`Not a Civitai URL: ${parsed.hostname}`,@@ -210,7 +217,7 @@ export const buildSidecar = ({ model, version, file, filename }) => {},runnerFamily: baseModelToRunner(baseModel), // 'mflux' | 'flux2' | 'z-image' | nulltriggerWords: Array.isArray(version?.trainedWords) ? version.trainedWords : [],- recommendedScale: typeof version?.settings?.strength === 'number' ? version.settings.strength : 1.0,+ recommendedScale: Number.isFinite(version?.settings?.strength) ? version.settings.strength : 1.0,file: {sizeKB: file?.sizeKB ?? null,hashes: file?.hashes || {},@@ -222,13 +229,17 @@ export const buildSidecar = ({ model, version, file, filename }) => {};// Sanitize a model name into a safe filename slug. Civitai model names can-// contain `/`, `\`, weird unicode, etc. — we want a portable filename that-// also keeps the .safetensors extension predictable. Limits length to keep-// the path well under most filesystems' 255-byte cap (the sidecar adds-// `.metadata.json` and the project may add prefixes).+// contain `/`, `\`, weird unicode, mixed case, etc. — we want a portable+// filename that also keeps the .safetensors extension predictable. Limits+// length to keep the path well under most filesystems' 255-byte cap (the+// sidecar adds `.metadata.json` and the project may add prefixes).+// Lowercased so the same model installed on macOS/Windows (case-insensitive)+// and Linux (case-sensitive) collides identically — `existsSync()` then+// reliably catches "already installed."export const slugifyForFilename = (name) => {const safe = String(name || 'lora').normalize('NFKD')+ .toLowerCase().replace(/[^\w\-.]+/g, '-') // anything that isn't a word char, dash, or dot → dash.replace(/-+/g, '-') // collapse runs.replace(/^[-.]+|[-.]+$/g, '') // trim leading/trailing dashes/dotsdiff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.jsindex b7ef793cae..1b31e01c77 100644--- a/server/lib/civitai.test.js+++ b/server/lib/civitai.test.js@@ -42,6 +42,12 @@ describe('parseCivitaiUrl', () => {it('rejects non-numeric modelVersionId', () => {expect(() => parseCivitaiUrl('https://civitai.com/models/123?modelVersionId=abc')).toThrow(/numeric/);});+ it('converts URL constructor TypeError into a CIVITAI_BAD_URL ServerError', () => {+ // `new URL('https://[malformed')` throws TypeError("Invalid URL").+ // The function must surface a 400 ServerError, not let the TypeError+ // bubble as a 500.+ expect(() => parseCivitaiUrl('https://[malformed')).toThrow(/Malformed URL/);+ });});describe('baseModelToRunner', () => {@@ -149,8 +155,8 @@ describe('buildAuthHeaders / applyDownloadToken', () => {describe('slugifyForFilename', () => {it('strips path-unsafe chars', () => {- expect(slugifyForFilename('Real / Stagram')).toBe('Real-Stagram');- expect(slugifyForFilename('Foo!@#Bar')).toBe('Foo-Bar');+ expect(slugifyForFilename('Real / Stagram')).toBe('real-stagram');+ expect(slugifyForFilename('Foo!@#Bar')).toBe('foo-bar');});it('caps length at 80 chars', () => {const long = 'a'.repeat(200);@@ -221,4 +227,15 @@ describe('buildSidecar', () => {expect(sc.triggerWords).toEqual([]);expect(sc.previewImageUrl).toBe(null);});+ it('rejects NaN as a recommended scale (Number.isFinite guard)', () => {+ // `typeof NaN === 'number'` would silently pass, persisting NaN into+ // the sidecar; downstream multiplies by NaN producing black images.+ const sc = buildSidecar({+ model: { id: 1, name: 'X' },+ version: { id: 2, baseModel: 'Flux.1 D', settings: { strength: NaN } },+ file: {},+ filename: 'x.safetensors',+ });+ expect(sc.recommendedScale).toBe(1.0);+ });});diff --git a/server/routes/loras.js b/server/routes/loras.jsindex 64cb1a6727..8f3e10abee 100644--- a/server/routes/loras.js+++ b/server/routes/loras.js@@ -53,7 +53,10 @@ router.post('/auth/civitai', asyncHandler(async (req, res) => {router.delete('/auth/civitai', asyncHandler(async (_req, res) => {const current = await getSettings();const next = { ...current };- if (next.civitai && typeof next.civitai === 'object') {+ // typeof === 'object' is true for arrays — guard explicitly so a+ // legacy/malformed `civitai: ['x']` value doesn't get spread into+ // `{ '0': 'x', apiKey: undefined }`.+ if (next.civitai && typeof next.civitai === 'object' && !Array.isArray(next.civitai)) {const { apiKey: _omit, ...rest } = next.civitai;next.civitai = rest;}diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 7905d194d8..d861680879 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -65,7 +65,7 @@ export const cancel = () => {return true;};-export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths, loraScales, stepwiseDir, initImagePath, initImageStrength }) => {+export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, height, steps, guidance, seed, quantize, outputPath, loraPaths = [], loraScales = [], stepwiseDir, initImagePath, initImageStrength }) => {const modelId = model?.id;if (isZImage(model)) {if (!model.repo) {diff --git a/server/services/loras.js b/server/services/loras.jsindex 2450ec287d..d8ba75b056 100644--- a/server/services/loras.js+++ b/server/services/loras.js@@ -25,7 +25,6 @@ import { ServerError } from '../lib/errorHandler.js';import { PATHS } from '../lib/fileUtils.js';import {applyDownloadToken,- buildAuthHeaders,buildSidecar,fetchCivitaiModel,parseCivitaiUrl,@@ -40,15 +39,23 @@ const SIDECAR_SUFFIX = '.metadata.json';const sidecarPath = (loraFilename) => join(PATHS.loras, `${loraFilename}${SIDECAR_SUFFIX}`);// Reads the sidecar JSON next to a LoRA file. Returns `null` when the-// sidecar is absent or unparseable — calling code can fall back to filename-// inference for legacy LoRAs the user dropped in manually pre-Civitai.+// sidecar is absent — calling code can fall back to filename inference for+// legacy LoRAs the user dropped in manually pre-Civitai. Permissions /+// I/O / parse errors get logged so an unreadable sidecar doesn't masquerade+// as a "legacy LoRA" in the manager UI.export const readSidecar = async (filename) => {- const raw = await readFile(sidecarPath(filename), 'utf-8').catch(() => null);+ const path = sidecarPath(filename);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err?.code === 'ENOENT') return null;+ console.log(`⚠️ LoRA sidecar unreadable [${filename}]: ${err?.code || err?.message || err}`);+ return null;+ });if (raw == null) return null;- // JSON.parse can throw on malformed sidecars — treat them as absent- // rather than crashing the list endpoint.let parsed = null;- try { parsed = JSON.parse(raw); } catch { return null; }+ try { parsed = JSON.parse(raw); } catch (err) {+ console.log(`⚠️ LoRA sidecar malformed JSON [${filename}]: ${err?.message || err}`);+ return null;+ }return parsed && typeof parsed === 'object' ? parsed : null;};@@ -168,7 +175,12 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} }await rm(tmpPath, { force: true }).catch(() => {});throw err;});- await rename(tmpPath, destPath);+ // rename can also fail (cross-device, locked dest, AV scan, low disk) —+ // wrap separately so the .partial doesn't leak in any failure mode.+ await rename(tmpPath, destPath).catch(async (err) => {+ await rm(tmpPath, { force: true }).catch(() => {});+ throw err;+ });};// Install a LoRA from a Civitai URL. Returns the new sidecar JSON so the@@ -185,7 +197,11 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {{ status: 422, code: 'CIVITAI_NO_DOWNLOAD' },);}- if (model?.type && model.type !== 'LORA' && model.type !== 'LoCon' && model.type !== 'LyCORIS') {+ // Civitai's `type` casing varies in the wild (LORA / Lora / lora) and the+ // family includes LoCon / LyCORIS / DoRA / LoHA — all of which load+ // through diffusers' lora pipeline. Refuse only true non-LoRA checkpoints.+ const ALLOWED_LORA_TYPES = new Set(['lora', 'locon', 'lycoris', 'dora', 'loha']);+ if (model?.type && !ALLOWED_LORA_TYPES.has(String(model.type).toLowerCase())) {throw new ServerError(`Civitai model "${model.name}" is type "${model.type}", not a LoRA — refusing to install`,{ status: 400, code: 'CIVITAI_NOT_A_LORA' },@@ -209,10 +225,14 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {await mkdir(PATHS.loras, { recursive: true });console.log(`📥 Installing Civitai LoRA: ${model.name} v${version.id} → ${filename} (${file.sizeKB ? Math.round(file.sizeKB / 1024) + ' MB' : 'size unknown'})`);+ // Authenticate downloads via `?token=` only — the Authorization header+ // doesn't survive the 302 to CDN, AND sending both means the token also+ // ends up in CDN access logs. The metadata fetch (fetchCivitaiModel)+ // still uses the header since /api/v1/* doesn't redirect.const tokenized = applyDownloadToken(file.downloadUrl, apiKey);await downloadToFile(tokenized, destPath, {fetchImpl,- headers: { 'User-Agent': 'PortOS/civitai-installer', ...buildAuthHeaders(apiKey) },+ headers: { 'User-Agent': 'PortOS/civitai-installer' },});const sidecar = buildSidecar({ model, version, file, filename });diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex 2c568d1172..40cfc323cc 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -155,7 +155,7 @@ describe('installFromCivitai', () => {throw new Error(`unexpected fetch: ${url}`);};const sidecar = await lorasService.installFromCivitai({ url: 'https://civitai.red/models/2600698/realstagram' }, { fetchImpl });- expect(sidecar.filename).toMatch(/^lora-RealStagram-v7\.safetensors$/);+ expect(sidecar.filename).toBe('lora-realstagram-v7.safetensors');expect(sidecar.civitai.modelId).toBe(2600698);expect(sidecar.civitai.versionId).toBe(7);expect(sidecar.runnerFamily).toBe('mflux');@@ -179,10 +179,24 @@ describe('installFromCivitai', () => {).rejects.toThrow(/not a LoRA/);});+ it('accepts LoRA-family types case-insensitively (DoRA, Lora, lycoris)', async () => {+ // Civitai's `type` casing isn't stable in the wild — DoRA / LoHA / Lora+ // / lower-case variants are all the same family from diffusers' POV.+ const fetchImpl = async (url) => {+ if (url.startsWith('https://civitai.com/api/v1/models/')) {+ return { ok: true, status: 200, json: async () => ({ ...FAKE_MODEL, type: 'DoRA' }) };+ }+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('w'))); c.close(); } });+ return { ok: true, status: 200, body: stream };+ };+ const sidecar = await lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl });+ expect(sidecar.civitai.type).toBe('DoRA');+ });+it('refuses to clobber an already-installed file', async () => {const fs = await import('fs/promises');await fs.mkdir(tmpLoras, { recursive: true });- await fs.writeFile(join(tmpLoras, 'lora-RealStagram-v7.safetensors'), 'pre-existing');+ await fs.writeFile(join(tmpLoras, 'lora-realstagram-v7.safetensors'), 'pre-existing');const fetchImpl = async (url) => {if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };throw new Error(`should not download: ${url}`);