AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { describe, it, expect, vi } from 'vitest'
import { existsSync, writeFileSync, readFileSync, readdirSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { decryptFile, ENCRYPTED_DOC_SUFFIX } from '../../src/main/services/workspace-vault'
import {
createQueuedDocument,
prepareDocument,
documentsDir
} from '../../src/main/services/ingestion'
import { testBudgetMs } from '../helpers/hang-budget'
import { tempRoot } from '../helpers/db-fixtures'
import { lockedVault, unlockedController } from '../helpers/vault-fixtures'
// full-audit 2026-07-12 SEC-1 — a DocumentCipher captured BEFORE "Lock now" must fail closed
// when invoked AFTER lock() zeroed the vault key. Previously `documentCipher()` closed over the
// key Buffer object itself; `lock()` fills it with zeros in place, so a cipher captured by an
// in-flight import kept "working" — encrypting the document sidecar under 32 zero bytes: a
// GCM-valid `.enc` anyone can decrypt, resting inside the locked workspace. The closures now
// re-read the live key PER INVOCATION and throw a typed, content-free `VaultLockedError`.
//
// The import-across-lock test gates `sha256File` (the audit's real park point: seconds–minutes
// for a large file on USB) — mirroring the gated-embedder idiom: everything else is REAL
// (vault, crypto, DB, ingestion); the gate only controls WHEN the hash resolves, so the lock
// deterministically lands inside the window. Kept in its own file because the module mock
// must not leak into the behavioral ingestion/vault suites.
//
// Explicit per-test budgets, `testBudgetMs(60_000)` (60 s locally, widened on CI; the issue-#84 /
// PR-#86 pattern, made CI-aware by #458): this file is ~1.5 s end to
// end on a healthy runner (FAST_KDF — real scrypt at N=1024, real AES-GCM, real SQLite, real
// fs), but a STARVED shared CI runner can stall any of these real-vault fixtures past vitest's
// global 15 s budget — the master push run of 2026-07-24 (run 30080155163, windows/22.x) timed
// out the two describe-openers at 15 s while the SAME tree had passed that exact leg on the PR
// minutes earlier and the same run's windows/24.x leg ran this file in 1.5 s. Every assertion
// here is SEMANTIC (typed throws, no sidecar bytes), none is a timing bound, so the wider
// budget loosens nothing about what the tests prove; all four tests carry it because they
// share the same fixture weight (the relock test does strictly more crypto than the opener).
const gate = vi.hoisted(() => {
const state = {
enabled: false,
entered: undefined as Promise<void> | undefined,
open: undefined as Promise<void> | undefined,
signalEntered: () => {},
release: () => {},
arm(): void {
state.enabled = true
state.entered = new Promise<void>((r) => (state.signalEntered = r))
state.open = new Promise<void>((r) => (state.release = r))
}
}
return state
})
vi.mock('../../src/main/services/models', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../src/main/services/models')>()
return {
...actual,
sha256File: async (
...args: Parameters<typeof actual.sha256File>
): ReturnType<typeof actual.sha256File> => {
if (gate.enabled) {
gate.enabled = false // one-shot: only the armed import parks
gate.signalEntered()
await gate.open
}
return actual.sha256File(...args)
}
}
})
const SECRET_TEXT = 'strictly confidential: the vault must not leak this after Lock now'
const ZERO_KEY = Buffer.alloc(32)
describe('documentCipher across lock() (full-audit 2026-07-12 SEC-1)', () => {
it('a captured cipher THROWS the typed error after lock() instead of encrypting under the zeroed key', async () => {
const ctl = unlockedController(lockedVault('lock-cipher', 'pw'), 'pw')
const cipher = ctl.documentCipher()
expect(cipher).not.toBeNull()
const dir = tempRoot('lock-cipher-files')
const plain = join(dir, 'note.txt')
writeFileSync(plain, SECRET_TEXT)
// Sanity: the captured cipher works while unlocked (happy path unchanged).
const encBefore = join(dir, 'before.enc')
await cipher!.encryptFileAsync(plain, encBefore)
expect(readFileSync(encBefore).includes(Buffer.from(SECRET_TEXT))).toBe(false)
ctl.lock()
// RED on pre-fix code: the closure captured the key Buffer that lock() zeroed in place,
// so this WROTE a zero-key-decryptable file instead of throwing. Awaited, so a regression that
// resolves has finished writing before the existsSync check below.
const encAfter = join(dir, 'after.enc')
let thrown: unknown = null
try {
await cipher!.encryptFileAsync(plain, encAfter)
} catch (err) {
thrown = err
}
expect(thrown).toBeInstanceOf(Error)
expect((thrown as Error).name).toBe('VaultLockedError')
expect((thrown as Error).message).not.toContain('note.txt') // content-free
expect(existsSync(encAfter)).toBe(false) // nothing was written
// Both closures fail closed the same way (per-invocation key read), and SYNCHRONOUSLY:
// requireKey() runs before the async body starts, so no file is even opened.
expect(() => cipher!.encryptFileAsync(plain, encAfter)).toThrow(/locked/i)
expect(() => cipher!.decryptFileAsync(encBefore, join(dir, 'out.txt'))).toThrow(/locked/i)
expect(existsSync(join(dir, 'out.txt'))).toBe(false)
}, testBudgetMs(60_000))
it('a cipher captured across lock → unlock reads the LIVE key again (per-invocation read)', async () => {
const ctl = unlockedController(lockedVault('lock-cipher', 'pw'), 'pw')
const cipher = ctl.documentCipher()!
ctl.lock()
ctl.unlock('pw')
// Fix-impact Q3 decision: no consumer legitimately spans a lock/unlock cycle (each IPC
// call / import job captures a fresh cipher), but one that did now picks up the live
// data key — the SAME key bytes the fresh cipher would use — instead of a zeroed Buffer.
const dir = tempRoot('lock-cipher-relock')
const plain = join(dir, 'note.txt')
writeFileSync(plain, SECRET_TEXT)
const enc = join(dir, 'note.enc')
await cipher.encryptFileAsync(plain, enc)
const back = join(dir, 'back.txt')
await ctl.documentCipher()!.decryptFileAsync(enc, back) // decrypts under a FRESH capture too
expect(readFileSync(back, 'utf8')).toBe(SECRET_TEXT)
ctl.lock()
}, testBudgetMs(60_000))
})
describe('lock landing mid-import (full-audit 2026-07-12 SEC-1, drained prepare)', () => {
it('a lock during the pre-encrypt hash fails the prepare cleanly — no zero-key sidecar lands', async () => {
const vp = lockedVault('lock-cipher', 'pw')
const ctl = unlockedController(vp, 'pw')
const db = ctl.requireDb()
const cipher = ctl.documentCipher()!
const store = documentsDir(dirname(vp.dbPath))
const srcDir = tempRoot('lock-cipher-src')
const file = join(srcDir, 'contract.txt')
writeFileSync(file, SECRET_TEXT)
const doc = createQueuedDocument(db, file)
// Park the prepare inside `await sha256File(origin)` — the audit's lock window — then
// lock the vault (closes the DB, zeroes the key) and let the drained prepare resume.
gate.arm()
const prepare = prepareDocument(db, store, doc.id, { cipher })
await gate.entered
ctl.lock()
gate.release()
// The drained prepare FAILS (its row-capture hits the closed DB — the import loop's
// drain swallows this, registerDocsIpc.ts) …
await expect(prepare).rejects.toThrow()
// … and the store holds NO sidecar at all — in particular nothing a 32-zero-byte key
// can decrypt. RED on pre-fix code: `<id>.txt.enc` existed AND decrypted under ZERO_KEY.
const leftovers = readdirSync(store)
for (const name of leftovers.filter((n) => n.endsWith(ENCRYPTED_DOC_SUFFIX))) {
const out = join(srcDir, `${name}.zero-key-plain`)
expect(() => decryptFile(join(store, name), out, ZERO_KEY)).toThrow()
expect(existsSync(out)).toBe(false)
}
expect(leftovers).toEqual([]) // the guard threw BEFORE anything was written
}, testBudgetMs(60_000))
it('an ordinary unlocked import still writes a real-key sidecar (happy path unchanged)', async () => {
const vp = lockedVault('lock-cipher', 'pw')
const ctl = unlockedController(vp, 'pw')
const db = ctl.requireDb()
const cipher = ctl.documentCipher()!
const store = documentsDir(dirname(vp.dbPath))
const srcDir = tempRoot('lock-cipher-src2')
const file = join(srcDir, 'contract.txt')
writeFileSync(file, SECRET_TEXT)
const doc = createQueuedDocument(db, file)
const prepared = await prepareDocument(db, store, doc.id, { cipher })
expect(prepared.ready).toBe(true)
const stored = readdirSync(store)
expect(stored).toHaveLength(1)
expect(stored[0].endsWith(ENCRYPTED_DOC_SUFFIX)).toBe(true)
// Encrypted under the REAL vault key: the vault cipher round-trips it, the zero key can't.
const back = join(srcDir, 'back.txt')
await cipher.decryptFileAsync(join(store, stored[0]), back)
expect(readFileSync(back, 'utf8')).toBe(SECRET_TEXT)
expect(() => decryptFile(join(store, stored[0]), join(srcDir, 'zk.txt'), ZERO_KEY)).toThrow()
ctl.lock()
}, testBudgetMs(60_000))
})