Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(stt): verify cached model checksum

Arham Wanib6a384c6e7c6
diff --git a/electron/stt/modelManager.test.ts b/electron/stt/modelManager.test.ts
index 92145dc7a..fa9b93a3d 100644
--- a/electron/stt/modelManager.test.ts
+++ b/electron/stt/modelManager.test.ts
@@ -1,4 +1,5 @@
-import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -45,19 +46,51 @@ describe("modelManager", () => {
it("ensureModels succeeds when the file is already present (cache hit)", async () => {
const paths = modelPaths(dir);
await mkdir(path.dirname(paths.whisper), { recursive: true });
- await writeFile(paths.whisper, "dummy-ggml");
+ const cached = Buffer.from("dummy-ggml");
+ await writeFile(paths.whisper, cached);
+ const originalSha = STT_MODELS.whisper.files[0].expectedSha256;
+ STT_MODELS.whisper.files[0].expectedSha256 = createHash("sha256").update(cached).digest("hex");
let fetches = 0;
const fetcher: typeof fetch = async () => {
fetches++;
return new Response("should not be reached", { status: 200 });
};
- await ensureModels({
- baseDir: dir,
- only: ["whisper"],
- fetcher,
- onProgress: () => undefined,
- });
- expect(fetches).toBe(0);
+ try {
+ await ensureModels({
+ baseDir: dir,
+ only: ["whisper"],
+ fetcher,
+ onProgress: () => undefined,
+ });
+ expect(fetches).toBe(0);
+ } finally {
+ STT_MODELS.whisper.files[0].expectedSha256 = originalSha;
+ }
+ });
+
+ it("re-downloads a non-empty cached model when its checksum is wrong", async () => {
+ const paths = modelPaths(dir);
+ await mkdir(path.dirname(paths.whisper), { recursive: true });
+ await writeFile(paths.whisper, "corrupt-cache");
+ const replacement = Buffer.from("verified-ggml-weights");
+ const originalSha = STT_MODELS.whisper.files[0].expectedSha256;
+ STT_MODELS.whisper.files[0].expectedSha256 = createHash("sha256")
+ .update(replacement)
+ .digest("hex");
+ let fetches = 0;
+ const fetcher: typeof fetch = async () => {
+ fetches++;
+ return new Response(replacement, { status: 200 });
+ };
+
+ try {
+ await ensureModels({ baseDir: dir, only: ["whisper"], fetcher });
+ expect(fetches).toBe(1);
+ expect(await readFile(paths.whisper)).toEqual(replacement);
+ expect(await readFile(`${paths.whisper}.bad`, "utf8")).toBe("corrupt-cache");
+ } finally {
+ STT_MODELS.whisper.files[0].expectedSha256 = originalSha;
+ }
});
it("ensureModels downloads the missing GGML file with progress", async () => {
diff --git a/electron/stt/modelManager.ts b/electron/stt/modelManager.ts
index 8ec47652e..6265cd786 100644
--- a/electron/stt/modelManager.ts
+++ b/electron/stt/modelManager.ts
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import { createReadStream, existsSync } from "node:fs";
-import { mkdir, rename, stat } from "node:fs/promises";
+import { mkdir, rename, rm, stat } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
@@ -153,7 +153,8 @@ export interface DownloadOptions {
* Stream a model file to disk atomically (<filename>.partial → rename on
* success), optionally verify the SHA-256.
*
- * If the file already exists and is non-empty, skips the download.
+ * If the file already exists, is non-empty, and matches the expected hash,
+ * skips the download. Invalid cache entries are quarantined as `.bad`.
*/
async function ensureFile(
filePath: string,
@@ -164,7 +165,12 @@ async function ensureFile(
if (existsSync(filePath)) {
const s = await stat(filePath);
if (s.isFile() && s.size > 0) {
- return;
+ if (!expectedSha256) return;
+ const actual = await sha256OfFile(filePath);
+ if (actual.toLowerCase() === expectedSha256.toLowerCase()) return;
+ const badPath = `${filePath}.bad`;
+ await rm(badPath, { force: true });
+ await rename(filePath, badPath);
}
}
@@ -182,17 +188,19 @@ async function ensureFile(
});
const { createWriteStream } = await import("node:fs");
await pipeline(source, createWriteStream(tmp));
- await rename(tmp, filePath);
if (expectedSha256) {
- const actual = await sha256OfFile(filePath);
+ const actual = await sha256OfFile(tmp);
if (actual.toLowerCase() !== expectedSha256.toLowerCase()) {
- await rename(filePath, `${filePath}.bad`).catch(() => undefined);
+ const badPath = `${filePath}.bad`;
+ await rm(badPath, { force: true });
+ await rename(tmp, badPath);
throw new Error(
`SHA-256 mismatch for ${path.basename(filePath)}: expected ${expectedSha256}, got ${actual}`,
);
}
}
+ await rename(tmp, filePath);
}
export interface EnsureModelsOptions {
@@ -217,8 +225,6 @@ export async function ensureModels(opts: EnsureModelsOptions): Promise<void> {
}));
for (const { id, descriptor, filePath } of targets) {
- if (await areModelsPresent(opts.baseDir)) continue;
-
await mkdir(path.dirname(filePath), { recursive: true });
const file = descriptor.files[0];