Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(db): make owner-only file permissions real on Windows (#791)

OhOkThisIsFinee83fd94004ef
diff --git a/server/src/__tests__/db/hardening.test.ts b/server/src/__tests__/db/hardening.test.ts
index f996c25e..56504c59 100644
--- a/server/src/__tests__/db/hardening.test.ts
+++ b/server/src/__tests__/db/hardening.test.ts
@@ -3,6 +3,11 @@ import os from 'os';
import path from 'path';
import { describe, it, expect, afterEach } from 'vitest';
import { connectDb } from '../../db/index.js';
+import { aclEntries } from '../helpers/acl.js';
+
+const isWindows = process.platform === 'win32';
+const itPosix = it.skipIf(isWindows);
+const itWindows = it.skipIf(!isWindows);
const created: string[] = [];
@@ -46,16 +51,23 @@ describe('database runtime hardening', () => {
expect(jmValue.toLowerCase()).toBe('wal');
});
- it('restricts the database file to the owner', () => {
+ // The DB holds encrypted provider keys and the dashboard password hash, so it
+ // must not be readable by other local accounts. The guarantee is the same on
+ // both platforms; only the mechanism that expresses it differs, so each leg
+ // asserts what its own OS can actually enforce. Asserting POSIX modes on
+ // Windows is not a stricter test — it is an unfalsifiable one: Node
+ // synthesizes 0o666 there and chmod cannot clear it, so the assertion failed
+ // whether or not the file was protected.
+
+ itPosix('restricts the database file to the owner', () => {
const dbPath = tempDbPath();
connectDb(dbPath);
- // The DB holds encrypted provider keys and the dashboard password hash.
const mode = fs.statSync(dbPath).mode & 0o777;
expect(mode & 0o077).toBe(0);
});
- it('restricts the WAL sidecars once they exist', () => {
+ itPosix('restricts the WAL sidecars once they exist', () => {
const dbPath = tempDbPath();
const db = connectDb(dbPath);
// Force a write so -wal/-shm are created, then reconnect to chmod them.
@@ -71,6 +83,54 @@ describe('database runtime hardening', () => {
}
});
+ itWindows('restricts the database file to the owner', () => {
+ const dbPath = tempDbPath();
+ connectDb(dbPath);
+
+ const entries = aclEntries(dbPath);
+ // Inherited ACEs are where the extra principals come from: a file created
+ // under %TEMP% or a shared profile inherits Modify for app containers and
+ // for other local accounts. If any (I) survives, hardening did not run.
+ expect(entries.filter(e => e.includes('(I)'))).toEqual([]);
+ // Exactly the owner, SYSTEM and Administrators — the POSIX 0600 equivalent,
+ // where root likewise keeps access.
+ expect(entries).toHaveLength(3);
+ });
+
+ itWindows('restricts the WAL sidecars once they exist', () => {
+ const dbPath = tempDbPath();
+ const db = connectDb(dbPath);
+ // Force a write so -wal/-shm are created, then reconnect to harden them.
+ db.exec('CREATE TABLE IF NOT EXISTS probe (id INTEGER PRIMARY KEY)');
+ db.exec('INSERT INTO probe (id) VALUES (1)');
+ connectDb(dbPath);
+
+ let checked = 0;
+ for (const suffix of ['-wal', '-shm']) {
+ const target = `${dbPath}${suffix}`;
+ if (!fs.existsSync(target)) continue;
+ checked++;
+ expect(aclEntries(target).filter(e => e.includes('(I)'))).toEqual([]);
+ }
+ // The original test silently passed when neither sidecar existed; make the
+ // Windows leg say so rather than pretending it verified something.
+ //
+ // Note what the reconnect above buys, and what it does not: it proves the
+ // pass restricts sidecars THAT ALREADY EXIST. A real server never gets
+ // here — it opens once, and SQLite creates the sidecars afterwards on the
+ // first write. See the known gap on restrictDbFilePermissions.
+ expect(checked).toBeGreaterThan(0);
+ });
+
+ itWindows('leaves an already-restricted file unchanged when reconnecting', () => {
+ const dbPath = tempDbPath();
+ connectDb(dbPath);
+ const first = aclEntries(dbPath);
+ connectDb(dbPath);
+
+ expect(aclEntries(dbPath)).toEqual(first);
+ });
+
it('works for an in-memory database without touching the filesystem', () => {
expect(() => connectDb(':memory:')).not.toThrow();
});
diff --git a/server/src/__tests__/helpers/acl.ts b/server/src/__tests__/helpers/acl.ts
new file mode 100644
index 00000000..c14895c7
--- /dev/null
+++ b/server/src/__tests__/helpers/acl.ts
@@ -0,0 +1,26 @@
+import path from 'path';
+import { execFileSync } from 'node:child_process';
+
+/**
+ * The access-control entries icacls reports for a file, one line per principal.
+ *
+ * Windows has no POSIX mode and Node exposes no ACL API, so asking the OS is
+ * the only way for a test to assert the real guarantee. This shells out to
+ * icacls directly rather than reusing lib/file-permissions, so a bug in the
+ * production helper cannot make its own test pass.
+ *
+ * Every ACE line carries a "PRINCIPAL:(RIGHTS)" pair; the leading path line
+ * ("C:\\...") and the trailing "Successfully processed" summary do not. An
+ * inherited entry is marked "(I)" — its absence is what proves the file no
+ * longer picks up principals from its parent directory.
+ *
+ * Windows-only: callers must gate on `process.platform === 'win32'`.
+ */
+export function aclEntries(target: string): string[] {
+ const out = execFileSync(
+ path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'icacls.exe'),
+ [target],
+ { encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] },
+ );
+ return out.split(/\r?\n/).map(line => line.trim()).filter(line => /:\(/.test(line));
+}
diff --git a/server/src/__tests__/lib/crypto-keyfile.test.ts b/server/src/__tests__/lib/crypto-keyfile.test.ts
index d765cbc4..630c8dbd 100644
--- a/server/src/__tests__/lib/crypto-keyfile.test.ts
+++ b/server/src/__tests__/lib/crypto-keyfile.test.ts
@@ -4,6 +4,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { initEncryptionKey, encrypt, decrypt } from '../../lib/crypto.js';
+import { aclEntries } from '../helpers/acl.js';
// FIX 2: the dev-fallback key is persisted to a file next to the DB, not into
// the `settings` table it protects. These tests use REAL file-backed DBs
@@ -59,8 +60,13 @@ describe('initEncryptionKey — key file (dev fallback)', () => {
const enc = encrypt('hello');
expect(decrypt(enc.encrypted, enc.iv, enc.authTag)).toBe('hello');
+ // The master key must be owner-only. Each platform asserts what it can
+ // actually enforce: POSIX modes on POSIX, the NTFS ACL on Windows, where
+ // chmod cannot express this at all.
if (process.platform !== 'win32') {
expect(fs.statSync(keyFile).mode & 0o777).toBe(0o600);
+ } else {
+ expect(aclEntries(keyFile).filter(e => e.includes('(I)'))).toEqual([]);
}
});
diff --git a/server/src/__tests__/lib/file-permissions.test.ts b/server/src/__tests__/lib/file-permissions.test.ts
new file mode 100644
index 00000000..dcff5e99
--- /dev/null
+++ b/server/src/__tests__/lib/file-permissions.test.ts
@@ -0,0 +1,218 @@
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ restrictToOwner,
+ restrictAllToOwner,
+ windowsRestrictArgs,
+ type ExecFileSyncLike,
+} from '../../lib/file-permissions.js';
+
+// Every Windows assertion here runs on Linux CI too: the child_process seam is
+// injected, so nothing spawns and nothing depends on being on Windows. The
+// end-to-end "does the ACL actually land" check lives in db/hardening.test.ts,
+// which is necessarily Windows-only.
+
+const SID = 'S-1-5-21-111-222-333-1002';
+const WHOAMI_OUT = `"E-DESK\\ethan","${SID}"\r\n`;
+
+const created: string[] = [];
+
+function tempFile(contents = 'x'): string {
+ const p = path.join(os.tmpdir(), `freeapi-fileperms-${Date.now()}-${Math.random()}`);
+ fs.writeFileSync(p, contents);
+ created.push(p);
+ return p;
+}
+
+/** A fake icacls/whoami that records calls and answers the SID lookup. */
+function fakeExec(overrides?: { onIcacls?: () => string }): ExecFileSyncLike & { calls: Array<{ file: string; args: string[] }> } {
+ const calls: Array<{ file: string; args: string[] }> = [];
+ const fn = ((file: string, args: string[]) => {
+ calls.push({ file, args });
+ if (file.toLowerCase().endsWith('whoami.exe')) return WHOAMI_OUT;
+ return overrides?.onIcacls ? overrides.onIcacls() : '';
+ }) as ExecFileSyncLike & { calls: typeof calls };
+ fn.calls = calls;
+ return fn;
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+});
+
+afterEach(() => {
+ for (const p of created.splice(0)) {
+ try { fs.unlinkSync(p); } catch { /* best effort */ }
+ }
+});
+
+describe('windowsRestrictArgs', () => {
+ it('drops inheritance and replaces the ACL with owner + SYSTEM + Administrators', () => {
+ expect(windowsRestrictArgs('C:\\data\\freeapi.db', SID)).toEqual([
+ 'C:\\data\\freeapi.db',
+ '/inheritance:r',
+ '/grant:r', `*${SID}:(F)`,
+ '/grant:r', '*S-1-5-18:(F)',
+ '/grant:r', '*S-1-5-32-544:(F)',
+ ]);
+ });
+
+ it('names the privileged principals by SID, not by their localized display names', () => {
+ // BUILTIN\Administrators is "VORDEFINIERT\Administratoren" on a German
+ // Windows; matching on names would silently harden nothing there.
+ const args = windowsRestrictArgs('f', SID).join(' ');
+ expect(args).not.toMatch(/Administrators|SYSTEM/i);
+ expect(args).toContain('*S-1-5-32-544');
+ expect(args).toContain('*S-1-5-18');
+ });
+
+ it('replaces rather than adds, so repeated hardening is idempotent', () => {
+ expect(windowsRestrictArgs('f', SID)).toContain('/grant:r');
+ expect(windowsRestrictArgs('f', SID)).not.toContain('/grant');
+ });
+});
+
+describe('restrictToOwner on Windows', () => {
+ it('resolves the owner SID and hands icacls the restriction', () => {
+ const target = tempFile();
+ const exec = fakeExec();
+
+ expect(restrictToOwner(target, { platform: 'win32', execFileSync: exec })).toBe(true);
+
+ expect(exec.calls).toHaveLength(2);
+ expect(exec.calls[0].file.toLowerCase()).toContain('whoami.exe');
+ expect(exec.calls[0].args).toEqual(['/user', '/fo', 'csv', '/nh']);
+ expect(exec.calls[1].file.toLowerCase()).toContain('icacls.exe');
+ expect(exec.calls[1].args).toEqual(windowsRestrictArgs(target, SID));
+ });
+
+ it('invokes the System32 binaries by absolute path, never off PATH', () => {
+ // A Git Bash / MSYS `whoami` shadows the Windows one and fails outright,
+ // and letting PATH pick the binary that hardens a file is a hijack vector.
+ const target = tempFile();
+ const exec = fakeExec();
+ restrictToOwner(target, { platform: 'win32', execFileSync: exec });
+
+ for (const call of exec.calls) {
+ // path.win32, not path.isAbsolute: the value under test is a Windows path,
+ // and the POSIX implementation this file runs under on CI reads
+ // "C:\\Windows/System32/whoami.exe" as relative because it has no leading
+ // slash. Judging a Windows path by POSIX rules fails the test on the one
+ // platform that always runs it.
+ expect(path.win32.isAbsolute(call.file)).toBe(true);
+ expect(call.file.replace(/\\/g, '/').toLowerCase()).toContain('/system32/');
+ }
+ });
+
+ it('skips the SID lookup when the caller already resolved it', () => {
+ const target = tempFile();
+ const exec = fakeExec();
+
+ restrictToOwner(target, { platform: 'win32', execFileSync: exec, ownerSid: SID });
+
+ expect(exec.calls).toHaveLength(1);
+ expect(exec.calls[0].file.toLowerCase()).toContain('icacls.exe');
+ });
+
+ it('reports failure instead of throwing when icacls fails', () => {
+ const target = tempFile();
+ const exec = fakeExec({ onIcacls: () => { throw new Error('Access is denied.'); } });
+
+ expect(() => restrictToOwner(target, { platform: 'win32', execFileSync: exec })).not.toThrow();
+ expect(restrictToOwner(target, { platform: 'win32', execFileSync: exec })).toBe(false);
+ });
+
+ it('reports failure when the owner SID cannot be determined', () => {
+ const target = tempFile();
+ const exec = (() => 'not a csv row') as ExecFileSyncLike;
+
+ expect(restrictToOwner(target, { platform: 'win32', execFileSync: exec })).toBe(false);
+ });
+
+ it('reports failure when the SID lookup itself throws', () => {
+ const target = tempFile();
+ const exec = (() => { throw new Error('ENOENT'); }) as ExecFileSyncLike;
+
+ expect(restrictToOwner(target, { platform: 'win32', execFileSync: exec })).toBe(false);
+ });
+
+ it('does not cache an injected fake between calls', () => {
+ // The real SID is memoized (a process cannot change its own SID), but a
+ // memoized fake would leak one test's answer into the next.
+ const target = tempFile();
+ const first = fakeExec();
+ restrictToOwner(target, { platform: 'win32', execFileSync: first });
+
+ const second = fakeExec();
+ restrictToOwner(target, { platform: 'win32', execFileSync: second });
+
+ expect(second.calls[0].file.toLowerCase()).toContain('whoami.exe');
+ });
+});
+
+describe('restrictToOwner on POSIX', () => {
+ it('uses chmod and never spawns a process', () => {
+ const target = tempFile();
+ const exec = fakeExec();
+
+ expect(restrictToOwner(target, { platform: 'linux', execFileSync: exec })).toBe(true);
+ expect(exec.calls).toHaveLength(0);
+ });
+
+ it('reports failure instead of throwing when chmod fails', () => {
+ const target = tempFile();
+ vi.spyOn(fs, 'chmodSync').mockImplementation(() => { throw new Error('EPERM'); });
+
+ expect(restrictToOwner(target, { platform: 'linux' })).toBe(false);
+ });
+});
+
+describe('restrictToOwner on a missing file', () => {
+ it('treats an absent target as nothing to do, on either platform', () => {
+ // SQLite's -wal/-shm sidecars do not exist until the first write.
+ const missing = path.join(os.tmpdir(), `freeapi-fileperms-absent-${Date.now()}`);
+ const exec = fakeExec();
+
+ expect(restrictToOwner(missing, { platform: 'win32', execFileSync: exec })).toBe(true);
+ expect(restrictToOwner(missing, { platform: 'linux', execFileSync: exec })).toBe(true);
+ expect(exec.calls).toHaveLength(0);
+ });
+});
+
+describe('restrictAllToOwner', () => {
+ it('resolves the owner SID once for the whole batch', () => {
+ const targets = [tempFile(), tempFile(), tempFile()];
+ const exec = fakeExec();
+
+ expect(restrictAllToOwner(targets, { platform: 'win32', execFileSync: exec })).toEqual([]);
+
+ const whoamiCalls = exec.calls.filter(c => c.file.toLowerCase().endsWith('whoami.exe'));
+ expect(whoamiCalls).toHaveLength(1);
+ expect(exec.calls.filter(c => c.file.toLowerCase().endsWith('icacls.exe'))).toHaveLength(3);
+ });
+
+ it('returns the targets it could not restrict rather than throwing', () => {
+ const ok = tempFile();
+ const bad = tempFile();
+ const exec = ((file: string, args: string[]) => {
+ if (file.toLowerCase().endsWith('whoami.exe')) return WHOAMI_OUT;
+ if (args[0] === bad) throw new Error('Access is denied.');
+ return '';
+ }) as ExecFileSyncLike;
+
+ expect(restrictAllToOwner([ok, bad], { platform: 'win32', execFileSync: exec })).toEqual([bad]);
+ });
+
+ it('does not report a missing sidecar as a failure', () => {
+ const present = tempFile();
+ const absent = `${present}-wal`;
+
+ expect(restrictAllToOwner([present, absent], {
+ platform: 'win32',
+ execFileSync: fakeExec(),
+ ownerSid: SID,
+ })).toEqual([]);
+ });
+});
diff --git a/server/src/db/index.ts b/server/src/db/index.ts
index 0db2ac1e..fa7082ee 100644
--- a/server/src/db/index.ts
+++ b/server/src/db/index.ts
@@ -5,6 +5,7 @@ import { createRequire } from 'node:module';
import { fileURLToPath } from 'url';
import { runMigrationsSync } from './migrate/runner.js';
import { initEncryptionKey, isEncryptionKeyInitialized } from '../lib/crypto.js';
+import { restrictAllToOwner } from '../lib/file-permissions.js';
import { nodeSqliteFactory } from './node-sqlite.js';
import type { Db, DbFactory } from './types.js';
@@ -83,16 +84,24 @@ export function connectDb(
/** Restrict the DB and its WAL sidecars to the owner. The file holds encrypted
* provider keys plus the dashboard password hash, so it must not be readable by
- * other local users. Best-effort: filesystems without POSIX modes (Windows,
- * some mounts) throw, and that must not stop startup. */
+ * other local users. Best-effort: a filesystem that cannot express the
+ * restriction must not stop startup — but it now says so instead of failing
+ * silently, because a hardening step nobody can see failing is one nobody
+ * notices is absent.
+ *
+ * Known gap, pre-existing and platform-independent: on a clean start the
+ * `-wal`/`-shm` sidecars do not exist yet (SQLite creates them on the first
+ * write and removes them on the last close), so this pass only ever restricts
+ * the main file. Covering them needs the containing directory to carry the
+ * restriction so new children inherit it, which cannot be done blindly here —
+ * FREEAPI_DB_PATH may point anywhere, including a shared temp directory. */
function restrictDbFilePermissions(resolvedPath: string): void {
- for (const suffix of ['', '-wal', '-shm']) {
- const target = `${resolvedPath}${suffix}`;
- try {
- if (fs.existsSync(target)) fs.chmodSync(target, 0o600);
- } catch {
- // Non-fatal: permissions are a hardening measure, not a correctness one.
- }
+ const failed = restrictAllToOwner(['', '-wal', '-shm'].map(suffix => `${resolvedPath}${suffix}`));
+ if (failed.length > 0) {
+ console.warn(
+ `[db] could not restrict database file permissions (${failed.length} of 3 targets); ` +
+ 'the database may be readable by other local accounts',
+ );
}
}
diff --git a/server/src/lib/crypto.ts b/server/src/lib/crypto.ts
index b0e1163f..3bef4136 100644
--- a/server/src/lib/crypto.ts
+++ b/server/src/lib/crypto.ts
@@ -1,6 +1,7 @@
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
+import { restrictToOwner } from './file-permissions.js';
import type { Db } from '../db/types.js';
const ALGORITHM = 'aes-256-gcm';
@@ -67,14 +68,19 @@ function keyFilePathFor(db: Db): string | null {
}
// Write the hex key with a temp-file-and-rename so a crash never leaves a
-// half-written key, and chmod 0600 so it isn't readable by other local users.
+// half-written key, and restrict it to the owner so it isn't readable by other
+// local users. The temp file is restricted BEFORE the rename so the key is
+// never briefly world-readable under its final name; a rename carries the DACL
+// with it, and the second call is idempotent belt-and-braces.
function writeKeyFileAtomic(keyFile: string, hex: string): void {
const dir = path.dirname(keyFile);
const tmp = path.join(dir, `${KEY_FILE_NAME}.tmp-${crypto.randomBytes(6).toString('hex')}`);
fs.writeFileSync(tmp, hex, { mode: 0o600 });
- try { fs.chmodSync(tmp, 0o600); } catch { /* best effort — e.g. filesystems without POSIX modes */ }
+ restrictToOwner(tmp);
fs.renameSync(tmp, keyFile);
- try { fs.chmodSync(keyFile, 0o600); } catch { /* best effort */ }
+ if (!restrictToOwner(keyFile)) {
+ console.warn(`[crypto] could not restrict permissions on ${KEY_FILE_NAME} — it may be readable by other local accounts`);
+ }
}
/**
diff --git a/server/src/lib/file-permissions.ts b/server/src/lib/file-permissions.ts
new file mode 100644
index 00000000..b175ba9d
--- /dev/null
+++ b/server/src/lib/file-permissions.ts
@@ -0,0 +1,174 @@
+import fs from 'fs';
+import path from 'path';
+import { execFileSync as nodeExecFileSync } from 'node:child_process';
+
+/**
+ * Restrict a sensitive file to its owner on every platform we support.
+ *
+ * POSIX gets `chmod 0600`. Windows has no POSIX modes at all: `fs.chmodSync`
+ * there only maps the owner-write bit onto FILE_ATTRIBUTE_READONLY, so
+ * `chmod(0o600)` is a silent no-op and the file keeps whatever ACL it inherited
+ * from its directory. That is not a cosmetic gap — a freshly created database
+ * under `%TEMP%` or a shared profile can inherit Modify for app containers and
+ * for other local accounts, and this file holds encrypted provider keys, the
+ * dashboard password hash, or the master encryption key.
+ *
+ * The Windows leg therefore drops inheritance and rewrites the ACL to exactly
+ * three principals: the current user, SYSTEM and Administrators. Keeping the
+ * last two mirrors POSIX, where 0600 never locks root out — and dropping them
+ * would break backup agents and service accounts for no security gain, since
+ * both can take ownership regardless.
+ */
+
+/** Injectable seam so tests never spawn a real process. Mirrors the `ExecFile`
+ * seam in routes/update.ts, but sync: the callers run at startup, not on the
+ * request path, and making them async would ripple through every connectDb. */
+export type ExecFileSyncLike = (
+ file: string,
+ args: string[],
+ options: { encoding: 'utf8'; timeout: number; windowsHide: true; stdio: ['ignore', 'pipe', 'pipe'] },
+) => string;
+
+export interface RestrictOptions {
+ platform?: NodeJS.Platform;
+ execFileSync?: ExecFileSyncLike;
+ /** Pre-resolved owner SID, so a caller hardening several files pays for the
+ * lookup once. Tests pass it to skip the `whoami` round trip entirely. */
+ ownerSid?: string | null;
+}
+
+const EXEC_TIMEOUT_MS = 5_000;
+
+/** SYSTEM and the local Administrators group, as well-known SIDs. Referenced by
+ * SID rather than by name because the display names are localized — a German
+ * Windows reports `VORDEFINIERT\Administratoren`. */
+const SID_SYSTEM = 'S-1-5-18';
+const SID_ADMINISTRATORS = 'S-1-5-32-544';
+
+const defaultExecFileSync: ExecFileSyncLike = (file, args, options) =>
+ nodeExecFileSync(file, args, options) as unknown as string;
+
+/** Absolute path into System32. Never resolve these off PATH: a Git Bash or
+ * MSYS `whoami` shadows the Windows one and fails outright, and letting PATH
+ * decide which binary hardens a file is itself a hijack vector. */
+function system32(binary: string): string {
+ return path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', binary);
+}
+
+let cachedOwnerSid: string | null | undefined;
+
+/**
+ * The current user's SID, via `whoami /user /fo csv /nh`, which prints
+ * `"DOMAIN\\user","S-1-5-21-..."`. Returns null if it cannot be determined.
+ * Memoized only for the real binary — a process's own SID cannot change — so an
+ * injected fake in tests is never cached and never reads another test's value.
+ */
+function resolveOwnerSid(exec: ExecFileSyncLike, useCache: boolean): string | null {
+ if (useCache && cachedOwnerSid !== undefined) return cachedOwnerSid;
+
+ let sid: string | null = null;
+ try {
+ // No existsSync guard: a missing binary throws ENOENT out of exec, which
+ // this catch already handles, and probing the filesystem first would make
+ // the Windows branch untestable anywhere but Windows.
+ const out = exec(system32('whoami.exe'), ['/user', '/fo', 'csv', '/nh'], {
+ encoding: 'utf8',
+ timeout: EXEC_TIMEOUT_MS,
+ windowsHide: true,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ sid = /"(S-1-[0-9-]+)"/.exec(out)?.[1] ?? null;
+ } catch {
+ sid = null;
+ }
+
+ if (useCache) cachedOwnerSid = sid;
+ return sid;
+}
+
+/**
+ * The icacls arguments that restrict `target` to `ownerSid` + SYSTEM +
+ * Administrators. Split out from the spawn so the command shape is testable
+ * without a Windows box.
+ *
+ * `/inheritance:r` removes the inherited ACEs (the whole point — that is where
+ * the extra principals come from), and `/grant:r` replaces rather than adds, so
+ * running it twice is idempotent. The `*` prefix makes icacls read each
+ * principal as a SID literal instead of an account name.
+ */
+export function windowsRestrictArgs(target: string, ownerSid: string): string[] {
+ return [
+ target,
+ '/inheritance:r',
+ '/grant:r', `*${ownerSid}:(F)`,
+ '/grant:r', `*${SID_SYSTEM}:(F)`,
+ '/grant:r', `*${SID_ADMINISTRATORS}:(F)`,
+ ];
+}
+
+/**
+ * Restrict `target` to its owner. Never throws: permissions are a hardening
+ * measure, not a correctness one, and startup must survive a filesystem that
+ * cannot express them.
+ *
+ * @returns true when the restriction was applied, false when it could not be.
+ * Callers are expected to surface a false — the failure mode that made
+ * this function necessary was a guard everyone believed was running.
+ */
+export function restrictToOwner(target: string, opts?: RestrictOptions): boolean {
+ const platform = opts?.platform ?? process.platform;
+ const exec = opts?.execFileSync ?? defaultExecFileSync;
+
+ try {
+ if (!fs.existsSync(target)) return true;
+ } catch {
+ return false;
+ }
+
+ if (platform !== 'win32') {
+ try {
+ fs.chmodSync(target, 0o600);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ const ownerSid = opts?.ownerSid !== undefined
+ ? opts.ownerSid
+ : resolveOwnerSid(exec, opts?.execFileSync === undefined);
+ if (!ownerSid) return false;
+
+ try {
+ exec(system32('icacls.exe'), windowsRestrictArgs(target, ownerSid), {
+ encoding: 'utf8',
+ timeout: EXEC_TIMEOUT_MS,
+ windowsHide: true,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Restrict several files that share an owner, resolving the SID at most once.
+ * Missing files are skipped, not failed — SQLite's `-wal`/`-shm` sidecars do not
+ * exist until the first write.
+ *
+ * @returns the targets that could not be restricted.
+ */
+export function restrictAllToOwner(targets: string[], opts?: RestrictOptions): string[] {
+ const platform = opts?.platform ?? process.platform;
+ const exec = opts?.execFileSync ?? defaultExecFileSync;
+ const ownerSid = platform === 'win32' && opts?.ownerSid === undefined
+ ? resolveOwnerSid(exec, opts?.execFileSync === undefined)
+ : opts?.ownerSid ?? null;
+
+ const failed: string[] = [];
+ for (const target of targets) {
+ if (!restrictToOwner(target, { ...opts, platform, ownerSid })) failed.push(target);
+ }
+ return failed;
+}