import { createHash } from 'node:crypto'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { bundledManifestPath, ConfigError, loadConfig } from '../src/config.ts'; import { BuiltinWhisperStt } from '../src/stt/builtinWhisper.ts'; import { fetchModel, validateManifest, verifyModel, type ModelManifest } from '../src/stt/modelStore.mjs'; /** * Pinning and verification of speech-model artifacts. A local stand-in for the model hub is * used, so these run without network. The real pinned artifacts are fetched and verified by * `npm run test:real-stt`. */ const sha = (data: string | Buffer) => createHash('sha256').update(data).digest('hex'); const CONTENT: Record = { 'config.json': Buffer.from('{"a":1}'), 'onnx/model.onnx': Buffer.from('not really weights, but bytes all the same'), }; const REVISION = '0123456789abcdef0123456789abcdef01234567'; const manifest: ModelManifest = { name: 'test-model', model: 'test-org/test-model', revision: REVISION, dtype: 'q8', files: Object.entries(CONTENT).map(([path, data]) => ({ path, sha256: sha(data), bytes: data.length })), }; let dir: string; let hub: Server; let hubUrl: string; let requests: string[]; let served: Record; beforeEach(async () => { dir = mkdtempSync(join(tmpdir(), 'hermeven-models-')); requests = []; served = { ...CONTENT }; hub = createServer((req, res) => { requests.push(req.url ?? ''); const prefix = `/${manifest.model}/resolve/${REVISION}/`; const file = req.url?.startsWith(prefix) ? served[req.url.slice(prefix.length)] : undefined; if (!file) return void res.writeHead(404).end(); res.writeHead(200, { 'Content-Length': file.length }).end(file); }); await new Promise((r) => hub.listen(0, '127.0.0.1', r)); hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`; }); afterEach(async () => { hub.closeAllConnections(); await new Promise((r) => hub.close(() => r())); chmodRecursive(dir, 0o700, 0o600); rmSync(dir, { recursive: true, force: true }); }); function chmodRecursive(path: string, dirMode: number, fileMode: number): void { if (!existsSync(path)) return; chmodSync(path, dirMode); for (const entry of readdirSync(path, { withFileTypes: true })) { const child = join(path, entry.name); if (entry.isDirectory()) chmodRecursive(child, dirMode, fileMode); else chmodSync(child, fileMode); } } describe('manifest validation: nothing unpinned is accepted', () => { const base = { ...manifest }; it('accepts a fully pinned manifest', () => { expect(validateManifest(base)).toEqual(manifest); }); it('refuses a branch, tag or short id as the revision', () => { for (const revision of ['main', 'v1.0', REVISION.slice(0, 12), REVISION.toUpperCase(), '', undefined]) { expect(() => validateManifest({ ...base, revision })).toThrow(/revision/); } }); it('refuses a file without a full SHA-256 or size', () => { expect(() => validateManifest({ ...base, files: [{ path: 'a', bytes: 1 }] })).toThrow(/sha256/); expect(() => validateManifest({ ...base, files: [{ path: 'a', sha256: 'abc', bytes: 1 }] })).toThrow(/sha256/); expect(() => validateManifest({ ...base, files: [{ path: 'a', sha256: sha('x') }] })).toThrow(/bytes/); expect(() => validateManifest({ ...base, files: [] })).toThrow(/files/); }); it('refuses paths that could leave the model store', () => { for (const path of ['../evil', '/etc/passwd', 'a/../../b', 'a//b', '.hidden/x', 'a\\b']) { expect(() => validateManifest({ ...base, files: [{ path, sha256: sha('x'), bytes: 1 }] })).toThrow(/unsafe path/); } expect(() => validateManifest({ ...base, model: '../x/y' })).toThrow(/model/); }); it('the bundled manifests are valid and pin a commit', () => { for (const name of ['whisper-base', 'whisper-tiny']) { const bundled = validateManifest(JSON.parse(readFileSync(bundledManifestPath(name), 'utf8'))); expect(bundled.revision).toMatch(/^[0-9a-f]{40}$/); expect(bundled.files.length).toBeGreaterThanOrEqual(7); } }); }); describe('configuration: an unpinned built-in model cannot be configured', () => { const env = { HERMES_API_KEY: 'k', HERMEVEN_DB_PATH: ':memory:' }; it('defaults to the bundled pinned whisper-base', () => { const config = loadConfig(env); expect(config.stt.provider).toBe('builtin'); expect(config.stt.manifest).toMatchObject({ model: 'onnx-community/whisper-base', dtype: 'q8' }); expect(config.stt.manifest!.revision).toMatch(/^[0-9a-f]{40}$/); }); it('refuses a hub id or any model without a bundled manifest', () => { for (const model of ['onnx-community/whisper-base', 'whisper-large', 'main', '../../etc/passwd']) { expect(() => loadConfig({ ...env, STT_MODEL: model })).toThrow(ConfigError); } }); it('accepts a custom manifest only if it is fully pinned', () => { const good = join(dir, 'good.json'); writeFileSync(good, JSON.stringify(manifest)); expect(loadConfig({ ...env, STT_MODEL_MANIFEST: good }).stt.manifest).toEqual(manifest); const moving = join(dir, 'moving.json'); writeFileSync(moving, JSON.stringify({ ...manifest, revision: 'main' })); expect(() => loadConfig({ ...env, STT_MODEL_MANIFEST: moving })).toThrow(/revision/); expect(() => loadConfig({ ...env, STT_MODEL_MANIFEST: join(dir, 'absent.json') })).toThrow(ConfigError); }); }); describe('fetch and verify', () => { it('downloads the pinned revision, verifies it, and is a no-op the second time', async () => { expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'missing', path: 'config.json' }); expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 2, verified: 2 }); expect(requests).toEqual([ `/test-org/test-model/resolve/${REVISION}/config.json`, `/test-org/test-model/resolve/${REVISION}/onnx/model.onnx`, ]); expect(await verifyModel(dir, manifest)).toEqual({ ok: true }); requests.length = 0; expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 0, verified: 2 }); expect(requests).toEqual([]); }); it('a hub that serves different bytes fails the fetch and leaves nothing in place', async () => { served['onnx/model.onnx'] = Buffer.from('not really weights, but bytes all the SAME'); // same length await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/does not match its pinned SHA-256/); const onnxDir = join(dir, manifest.model, 'onnx'); expect(existsSync(join(onnxDir, 'model.onnx'))).toBe(false); expect(readdirSync(onnxDir)).toEqual([]); expect((await verifyModel(dir, manifest)).ok).toBe(false); served['onnx/model.onnx'] = Buffer.concat([CONTENT['onnx/model.onnx']!, Buffer.from('extra')]); await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/larger than pinned/); delete served['config.json']; rmSync(join(dir, manifest.model), { recursive: true }); await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/HTTP 404/); }); it('detects a file changed on disk, by content and by size', async () => { await fetchModel(dir, manifest, { baseUrl: hubUrl }); const target = join(dir, manifest.model, 'config.json'); writeFileSync(target, '{"a":2}'); // same size, different content expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'config.json' }); writeFileSync(target, '{"a":1} '); expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'config.json' }); // Fetching again repairs it from the pinned revision. expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 1, verified: 2 }); }); it('verification works on a read-only store', async () => { await fetchModel(dir, manifest, { baseUrl: hubUrl }); chmodRecursive(dir, 0o500, 0o400); expect(await verifyModel(dir, manifest)).toEqual({ ok: true }); }); }); describe('the adapter refuses to load unverified artifacts, and never downloads', () => { const pcm = () => { const buf = Buffer.alloc(32000); for (let i = 0; i < 16000; i++) buf.writeInt16LE(Math.round(Math.sin(i / 5) * 8000), i * 2); return buf; }; const signal = new AbortController().signal; it('missing files: unavailable, reason "missing", and no network request', async () => { const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); await expect(stt.transcribe({ pcm: pcm(), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); expect(stt.lastLoadFailure).toBe('missing'); expect(requests).toEqual([]); await stt.close(); }); it('tampered files: unavailable, reason "mismatch"', async () => { await fetchModel(dir, manifest, { baseUrl: hubUrl }); writeFileSync(join(dir, manifest.model, 'onnx/model.onnx'), Buffer.from('not really weights, but bytes all the SAME')); requests.length = 0; const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); await expect(stt.transcribe({ pcm: pcm(), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); expect(stt.lastLoadFailure).toBe('mismatch'); expect(requests).toEqual([]); await stt.close(); }); });