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([issue-2199]): verify safetensors integrity after Civitai/HF LoRA download

Adam Eivy0d830e124edd
diff --git a/server/lib/README.md b/server/lib/README.md
index 6b357194bf..0289e3e5fd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -102,7 +102,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). |
| `hfErrors.js` | Parse huggingface_hub gated-access errors: `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and LoRA trainer. Pure. |
-| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. |
+| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check (reads only the header region) — also used by the Civitai/HF LoRA install path to reject truncated downloads. |
| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |
| `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. |
| `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate; uses `SSE_HEADERS` from `sseHeaders.js`) — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index 96d4930f95..efb5e3df2d 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -167,7 +167,7 @@ const SHA256_RE = /^[0-9a-f]{64}$/;
// Cheap structural check for a single .safetensors file. Reads only the header
// region (a few KB), never the tensor payload. Returns { ok, reason, ... }.
-async function verifySafetensorsStructure(path, size) {
+export async function verifySafetensorsStructure(path, size) {
if (size < 8) return { ok: false, reason: 'truncated-header' };
let fd;
try {
diff --git a/server/services/loras.js b/server/services/loras.js
index 4f1de4d7c5..aff8aa5454 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -25,7 +25,8 @@ import { Readable, Transform } from 'stream';
import { pipeline } from 'stream/promises';
import { basename, join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
-import { atomicWrite, assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, assertSafeFilename, ensureDir, listDirectoryByExtension, sha256File, PATHS } from '../lib/fileUtils.js';
+import { verifySafetensorsStructure } from '../lib/hfCache.js';
import { isPlainObject } from '../lib/objects.js';
import {
applyDownloadToken,
@@ -367,6 +368,43 @@ const downloadToFile = async (url, destPath, { fetchImpl = fetch, headers = {} ,
});
};
+// After a LoRA finishes downloading, verify the on-disk `.safetensors` before
+// we commit to it by writing the sidecar. A truncated (short download) or
+// right-size-but-wrong-bytes file otherwise installs silently and renders
+// garbage ("mosaic" output) at generate time — the leading non-Metal cause of
+// corrupt output (issue #2199; mirrors the HF-cache integrity check in
+// hfCache.js / #1324). Always runs the cheap structural header/size check
+// (reads only the header region, never the multi-GB payload); adds a deep
+// sha256 compare only when the source metadata carried a digest (Civitai
+// `file.hashes.SHA256`). On any failure the file is deleted so the next install
+// re-downloads instead of training/rendering against corrupt weights.
+const verifyDownloadedLora = async (destPath, { expectedSha256 = null, source = 'civitai' } = {}) => {
+ const label = source === 'huggingface' ? 'HuggingFace' : 'Civitai';
+ const code = source === 'huggingface' ? 'HF_LORA_CORRUPT' : 'CIVITAI_LORA_CORRUPT';
+ const st = await stat(destPath).catch(() => null);
+ const structural = await verifySafetensorsStructure(destPath, st?.size ?? 0);
+ if (!structural.ok) {
+ await rm(destPath, { force: true }).catch(() => {});
+ throw new ServerError(
+ `${label} LoRA download is corrupt (${structural.reason}) — the partial file was deleted. Retry the install.`,
+ { status: 502, code },
+ );
+ }
+ // Civitai hashes are uppercase hex; sha256File returns lowercase — compare
+ // case-insensitively and only when the digest is a well-formed sha256.
+ const want = typeof expectedSha256 === 'string' ? expectedSha256.trim().toLowerCase() : '';
+ if (/^[0-9a-f]{64}$/.test(want)) {
+ const actual = await sha256File(destPath).catch(() => null);
+ if (actual && actual.toLowerCase() !== want) {
+ await rm(destPath, { force: true }).catch(() => {});
+ throw new ServerError(
+ `${label} LoRA failed SHA-256 verification (expected ${want.slice(0, 12)}…, got ${actual.slice(0, 12)}…) — the file was deleted. Retry the install.`,
+ { status: 502, code },
+ );
+ }
+ }
+};
+
// Install a LoRA from a Civitai URL. Returns the new sidecar JSON so the
// client can render it immediately without a second list round-trip.
export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
@@ -435,6 +473,7 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
headers: { 'User-Agent': 'PortOS/civitai-installer' },
hasApiKey: !!apiKey,
});
+ await verifyDownloadedLora(destPath, { expectedSha256: file?.hashes?.SHA256 || null, source: 'civitai' });
const sidecar = buildSidecar({ model, version, file, filename });
await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
@@ -506,6 +545,10 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr
onProgress,
signal,
});
+ // HF's model metadata doesn't expose a per-file digest through pickHfLoraFile,
+ // so the structural header/size check is the integrity guard here (no deep
+ // sha256 compare available for this path).
+ await verifyDownloadedLora(destPath, { source: 'huggingface' });
const sidecar = buildHfLoraSidecar({ repo, revision, file, model, family, filename });
await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index 4b2134fc7c..b7254f0b01 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -1,9 +1,21 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mockJsonResponse } from '../lib/testHelper.js';
import { existsSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';
+import { createHash } from 'crypto';
import { tmpdir } from 'os';
import { join } from 'path';
+// Minimal structurally-valid safetensors blob: 8-byte LE header length + JSON
+// header. verifyDownloadedLora (issue #2199) rejects anything that isn't a
+// parseable safetensors header, so download fixtures below must be valid.
+const validSafetensors = (header = {}) => {
+ const json = Buffer.from(JSON.stringify(header), 'utf8');
+ const len = Buffer.alloc(8);
+ len.writeBigUInt64LE(BigInt(json.length));
+ return Buffer.concat([len, json]);
+};
+const sha256Hex = (buf) => createHash('sha256').update(buf).digest('hex');
+
// Point PATHS.loras at a temp dir for the duration of each test. PATHS is
// computed at module load against process.cwd / __dirname, so the cleanest
// way to swap it is to mock fileUtils for the loras service.
@@ -277,7 +289,7 @@ describe('installFromCivitai', () => {
};
it('downloads, writes the file, writes the sidecar', async () => {
- const downloadedBytes = Buffer.from('fake-lora-weights');
+ const downloadedBytes = validSafetensors();
const calls = [];
const fetchImpl = async (url) => {
calls.push(url);
@@ -305,7 +317,7 @@ describe('installFromCivitai', () => {
// File on disk
const installedPath = join(tmpLoras, sidecar.filename);
expect(existsSync(installedPath)).toBe(true);
- expect(readFileSync(installedPath, 'utf-8')).toBe('fake-lora-weights');
+ expect(readFileSync(installedPath)).toEqual(downloadedBytes);
// Sidecar on disk
const sidecarPath = `${installedPath}.metadata.json`;
expect(JSON.parse(readFileSync(sidecarPath, 'utf-8')).civitai.modelId).toBe(2600698);
@@ -327,7 +339,7 @@ describe('installFromCivitai', () => {
if (url.startsWith('https://civitai.com/api/v1/models/')) {
return mockJsonResponse({ ...FAKE_MODEL, type: 'DoRA' });
}
- const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('w'))); c.close(); } });
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); } });
return { ok: true, status: 200, body: stream };
};
const sidecar = await lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl });
@@ -402,6 +414,52 @@ describe('installFromCivitai', () => {
const tmpFiles = await fs.readdir(tmpLoras);
expect(tmpFiles.some((f) => f.endsWith('.partial'))).toBe(false);
});
+
+ it('rejects a truncated/corrupt download and deletes the partial file', async () => {
+ // A short download that isn't a parseable safetensors header — the leading
+ // non-Metal cause of "mosaic" garbage output at generate time (issue #2199).
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://civitai.com/api/v1/models/')) return mockJsonResponse(FAKE_MODEL);
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('truncated'))); c.close(); } });
+ return { ok: true, status: 200, body: stream };
+ };
+ const err = await lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }).catch((e) => e);
+ expect(err.code).toBe('CIVITAI_LORA_CORRUPT');
+ // The corrupt file must be gone so the next install re-downloads.
+ expect(existsSync(join(tmpLoras, 'lora-realstagram-v7.safetensors'))).toBe(false);
+ // No sidecar should have been written.
+ expect(existsSync(join(tmpLoras, 'lora-realstagram-v7.safetensors.metadata.json'))).toBe(false);
+ });
+
+ it('rejects a structurally-valid download whose SHA-256 mismatches the Civitai digest', async () => {
+ const bytes = validSafetensors();
+ // A different, well-formed sha256 so the deep compare fails.
+ const wrongSha = 'f'.repeat(64);
+ const model = { ...FAKE_MODEL, modelVersions: [{ ...FAKE_MODEL.modelVersions[0], files: [{ ...FAKE_MODEL.modelVersions[0].files[0], hashes: { SHA256: wrongSha } }] }] };
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://civitai.com/api/v1/models/')) return mockJsonResponse(model);
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(bytes)); c.close(); } });
+ return { ok: true, status: 200, body: stream };
+ };
+ const err = await lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }).catch((e) => e);
+ expect(err.code).toBe('CIVITAI_LORA_CORRUPT');
+ expect(existsSync(join(tmpLoras, 'lora-realstagram-v7.safetensors'))).toBe(false);
+ });
+
+ it('accepts a download whose SHA-256 matches the Civitai digest (case-insensitive)', async () => {
+ const bytes = validSafetensors();
+ // Civitai reports hashes in uppercase; sha256File returns lowercase.
+ const rightSha = sha256Hex(bytes).toUpperCase();
+ const model = { ...FAKE_MODEL, modelVersions: [{ ...FAKE_MODEL.modelVersions[0], files: [{ ...FAKE_MODEL.modelVersions[0].files[0], hashes: { SHA256: rightSha } }] }] };
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://civitai.com/api/v1/models/')) return mockJsonResponse(model);
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(bytes)); c.close(); } });
+ return { ok: true, status: 200, body: stream };
+ };
+ const sidecar = await lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl });
+ expect(sidecar.filename).toBe('lora-realstagram-v7.safetensors');
+ expect(existsSync(join(tmpLoras, 'lora-realstagram-v7.safetensors'))).toBe(true);
+ });
});
describe('installFromHuggingface', () => {
@@ -424,7 +482,7 @@ describe('installFromHuggingface', () => {
}
if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
const stream = new ReadableStream({
- start(c) { c.enqueue(new Uint8Array(Buffer.from('weights'))); c.close(); },
+ start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); },
});
return { ok: true, status: 200, body: stream };
}
@@ -461,15 +519,19 @@ describe('installFromHuggingface', () => {
return mockJsonResponse(HF_MODEL);
}
if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
+ // Split a structurally-valid 10-byte safetensors blob across two chunks
+ // so the byte-progress accounting is exercised without tripping the
+ // post-download integrity check (issue #2199).
+ const bytes = validSafetensors();
const stream = new ReadableStream({
start(c) {
- c.enqueue(new Uint8Array(Buffer.from('abcd')));
- c.enqueue(new Uint8Array(Buffer.from('efgh')));
+ c.enqueue(new Uint8Array(bytes.subarray(0, 5)));
+ c.enqueue(new Uint8Array(bytes.subarray(5)));
c.close();
},
});
- // Carry a Content-Length so the total is known (8 bytes).
- return { ok: true, status: 200, body: stream, headers: { get: (h) => (h === 'content-length' ? '8' : null) } };
+ // Carry a Content-Length so the total is known.
+ return { ok: true, status: 200, body: stream, headers: { get: (h) => (h === 'content-length' ? String(bytes.length) : null) } };
}
throw new Error(`unexpected fetch: ${url}`);
};
@@ -481,8 +543,8 @@ describe('installFromHuggingface', () => {
expect(ticks.length).toBeGreaterThan(0);
// The flush tick always fires last with the full byte count.
const last = ticks[ticks.length - 1];
- expect(last.received).toBe(8);
- expect(last.total).toBe(8);
+ expect(last.received).toBe(10);
+ expect(last.total).toBe(10);
});
it('tolerates a missing Content-Length (total 0, still completes)', async () => {
@@ -491,7 +553,7 @@ describe('installFromHuggingface', () => {
return mockJsonResponse(HF_MODEL);
}
if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
- const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('weights'))); c.close(); } });
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); } });
return { ok: true, status: 200, body: stream }; // no headers
}
throw new Error(`unexpected fetch: ${url}`);
@@ -502,7 +564,7 @@ describe('installFromHuggingface', () => {
{ fetchImpl, onProgress: (p) => ticks.push(p) },
);
expect(sidecar.runnerFamily).toBe('ltx-video');
- expect(ticks[ticks.length - 1]).toEqual({ received: 7, total: 0 });
+ expect(ticks[ticks.length - 1]).toEqual({ received: 10, total: 0 });
});
it('forwards an AbortSignal to the download fetch so an SSE disconnect can cancel it', async () => {
@@ -512,7 +574,7 @@ describe('installFromHuggingface', () => {
if (url.startsWith('https://huggingface.co/api/models/')) return mockJsonResponse(HF_MODEL);
if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
sawSignal = opts?.signal;
- const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('w'))); c.close(); } });
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); } });
return { ok: true, status: 200, body: stream };
}
throw new Error(`unexpected fetch: ${url}`);
@@ -532,7 +594,7 @@ describe('installFromHuggingface', () => {
return mockJsonResponse({ id: 'someone/mystery-lora', siblings: [{ rfilename: 'lora.safetensors' }] });
}
if (url.includes('/resolve/main/lora.safetensors')) {
- const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('w'))); c.close(); } });
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(validSafetensors())); c.close(); } });
return { ok: true, status: 200, body: stream };
}
throw new Error(`unexpected fetch: ${url}`);
@@ -543,4 +605,21 @@ describe('installFromHuggingface', () => {
);
expect(sidecar.runnerFamily).toBe('ltx-video');
});
+
+ it('rejects a truncated/corrupt HF download and deletes the partial file', async () => {
+ const fetchImpl = async (url) => {
+ if (url.startsWith('https://huggingface.co/api/models/')) return mockJsonResponse(HF_MODEL);
+ if (url.includes('/resolve/main/pytorch_lora_weights.safetensors')) {
+ const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('truncated'))); c.close(); } });
+ return { ok: true, status: 200, body: stream };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ };
+ const err = await lorasService.installFromHuggingface(
+ { url: 'https://huggingface.co/fal/ltx2.3-audio-reactive-lora', token: 'hf_test' },
+ { fetchImpl },
+ ).catch((e) => e);
+ expect(err.code).toBe('HF_LORA_CORRUPT');
+ expect(existsSync(join(tmpLoras, 'lora-fal-ltx2.3-audio-reactive-lora-hf.safetensors'))).toBe(false);
+ });
});