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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: protect durable JSON writebacks (#6942)
[._.]/ Adam Eivy77fc5dcebbf8
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 84e9c03175..641e4776e1 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -612,7 +612,11 @@ describe('fileUtils', () => {const filePath = join(testDir, 'corrupt.json');await writeFile(filePath, 'not json at all');- await expect(readJSONFile(filePath, [], { strict: true })).rejects.toThrow(/Unreadable JSON file/);+ await expect(readJSONFile(filePath, [], { strict: true })).rejects.toMatchObject({+ message: expect.stringMatching(/Unreadable JSON file/),+ status: 500,+ code: 'UNREADABLE_STORE',+ });});it('returns the parsed value when the read succeeds', async () => {diff --git a/server/lib/jsonIo.js b/server/lib/jsonIo.jsindex 4ad73d23a6..98f92a64d3 100644--- a/server/lib/jsonIo.js+++ b/server/lib/jsonIo.js@@ -353,6 +353,18 @@ export async function readJSONFileStrict(filePath, defaultValue = null, { allowAreturn { ok: true, value: parsed };}+/**+ * Stable request-facing error for a durable JSON store whose bytes could not+ * be trusted. Callers may surface the code without exposing the local path;+ * the message keeps the path for server logs and direct service diagnostics.+ */+export function unreadableStoreError(filePath) {+ return Object.assign(new Error(`Unreadable JSON file: ${filePath}`), {+ status: 500,+ code: 'UNREADABLE_STORE',+ });+}+/*** Read a JSON file safely with validation and default fallback.* Combines file reading with safe JSON parsing.@@ -387,7 +399,7 @@ export async function readJSONFileStrict(filePath, defaultValue = null, { allowAexport async function readJSONFile(filePath, defaultValue = null, { allowArray = true, logError = true, strict = false } = {}) {const { ok, value } = await readJSONFileStrict(filePath, defaultValue, { allowArray, logError });if (!ok && strict) {- throw new Error(`Unreadable JSON file: ${filePath}`);+ throw unreadableStoreError(filePath);}return value;}diff --git a/server/services/audioModels.js b/server/services/audioModels.jsindex f858e61c96..a170d9a550 100644--- a/server/services/audioModels.js+++ b/server/services/audioModels.js@@ -49,7 +49,9 @@ function sanitizeUserModel(raw) {}async function loadRegistry() {- const raw = await readJSONFile(REGISTRY_FILE, {});+ // Strict: add/remove both persist the loaded registry. A swallowed failure+ // would replace every other engine's user-installed model rows.+ const raw = await readJSONFile(REGISTRY_FILE, {}, { strict: true });const out = {};if (raw && typeof raw === 'object') {for (const engineId of Object.keys(ENGINES)) {diff --git a/server/services/audioModels.test.js b/server/services/audioModels.test.jsindex 2794d20502..4b49044b74 100644--- a/server/services/audioModels.test.js+++ b/server/services/audioModels.test.js@@ -4,7 +4,7 @@*/import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';-import { mkdtempSync, rmSync } from 'fs';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -84,4 +84,14 @@ describe('audioModels — add / list / merge / remove', () => {expect((await svc.listUserModels('musicgen'))).toHaveLength(0);expect(await svc.removeAudioModel({ engine: 'musicgen', id: 'not/there' })).toBe(false);});++ it('refuses to add over an unreadable registry and preserves its bytes', async () => {+ const registry = join(TEST_DATA_ROOT, 'audio-models.json');+ writeFileSync(registry, '{"musicgen":');+ const before = readFileSync(registry);++ await expect(svc.addAudioModel({ engine: 'musicgen', repo: 'org/new-model' }))+ .rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });+ expect(readFileSync(registry)).toEqual(before);+ });});diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 68906617ae..ab3e34b3d2 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -403,7 +403,9 @@ export const LIMITS = Object.freeze({export async function getState() {await ensureDir(PATHS.data);- const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });+ // Strict: all layout mutations persist the state returned here. Falling back+ // after a failed read would replace every custom layout with shipped defaults.+ const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false, strict: true });const sanitized = [];const seenIds = new Set();if (Array.isArray(raw.layouts)) {diff --git a/server/services/dashboardLayouts.test.js b/server/services/dashboardLayouts.test.jsindex 7a8a2ee5ba..9d16d97b85 100644--- a/server/services/dashboardLayouts.test.js+++ b/server/services/dashboardLayouts.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { mkdtempSync, rmSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from 'fs';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync, unlinkSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -176,6 +176,22 @@ describe('dashboardLayouts service', () => {});});+ describe('unreadable store', () => {+ it('refuses every layout mutation without replacing the original bytes', async () => {+ writeFileSync(STATE_FILE, '{"layouts":');+ const before = readFileSync(STATE_FILE);+ const attempts = [+ svc.setActiveLayout('default'),+ svc.saveLayout({ id: 'custom', name: 'Custom', widgets: ['cos'], grid: [] }),+ ];++ for (const attempt of attempts) {+ await expect(attempt).rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });+ expect(readFileSync(STATE_FILE)).toEqual(before);+ }+ });+ });+describe('grid item fixedH', () => {it('round-trips the pin the user dragged onto a cell', async () => {await svc.saveLayout({diff --git a/server/services/quotaBurnStore.js b/server/services/quotaBurnStore.jsindex 89d00ecc23..0d4018fa05 100644--- a/server/services/quotaBurnStore.js+++ b/server/services/quotaBurnStore.js@@ -42,7 +42,7 @@ const configWriteQueue = createFileWriteQueue();const runLogWriteQueue = createFileWriteQueue();export async function getQuotaBurnConfig() {- return normalizeQuotaBurnConfig(await readJSONFile(configFile(), null));+ return normalizeQuotaBurnConfig(await readJSONFile(configFile(), null, { strict: true }));}/**@@ -54,7 +54,7 @@ export async function getQuotaBurnConfig() {*/export async function saveQuotaBurnConfig(patch) {return configWriteQueue(async () => {- const current = normalizeQuotaBurnConfig(await readJSONFile(configFile(), null));+ const current = normalizeQuotaBurnConfig(await readJSONFile(configFile(), null, { strict: true }));// Written to match `client/src/lib/quotaBurnPatch.js#mergeQuotaBurnPatch`// line for line — the client applies the same merge optimistically while the// PUT is debounced, and the two only stay honest if the claim is checkable@@ -84,7 +84,7 @@ const IN_FLIGHT_TTL_MS = 6 * 60 * 60 * 1000;/** Keys enqueued within the TTL, as a Set. Expired keys are simply not returned. */export async function getQuotaBurnInFlight({ now = Date.now() } = {}) {- const loaded = await readJSONFile(inFlightFile(), null);+ const loaded = await readJSONFile(inFlightFile(), null, { strict: true });const entries = loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {};return new Set(Object.entries(entries).filter(([, at]) => Number.isFinite(Number(at)) && now - Number(at) < IN_FLIGHT_TTL_MS)@@ -95,7 +95,7 @@ export async function getQuotaBurnInFlight({ now = Date.now() } = {}) {export async function recordQuotaBurnInFlight(keys, { now = Date.now() } = {}) {if (!keys?.length) return;return inFlightWriteQueue(async () => {- const loaded = await readJSONFile(inFlightFile(), null);+ const loaded = await readJSONFile(inFlightFile(), null, { strict: true });const entries = loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {};const next = Object.fromEntries(Object.entries(entries).filter(([, at]) => Number.isFinite(Number(at)) && now - Number(at) < IN_FLIGHT_TTL_MS));@@ -206,7 +206,7 @@ export async function releaseQuotaBurnStep(key, { now = Date.now() } = {}) {}export async function getQuotaBurnRuns() {- const loaded = await readJSONFile(runLogFile(), null);+ const loaded = await readJSONFile(runLogFile(), null, { strict: true });return Array.isArray(loaded?.runs) ? loaded.runs : [];}@@ -217,7 +217,7 @@ export async function getQuotaBurnRuns() {*/export async function recordQuotaBurnRun(entry) {return runLogWriteQueue(async () => {- const loaded = await readJSONFile(runLogFile(), null);+ const loaded = await readJSONFile(runLogFile(), null, { strict: true });const runs = Array.isArray(loaded?.runs) ? loaded.runs : [];const next = [{ at: new Date().toISOString(), ...entry }, ...runs].slice(0, RUN_LOG_LIMIT);await atomicWrite(runLogFile(), { runs: next });@@ -239,7 +239,7 @@ export async function recordQuotaBurnRun(entry) {export async function settleQuotaBurnRun(requestId, patch) {if (!requestId) return null;return runLogWriteQueue(async () => {- const loaded = await readJSONFile(runLogFile(), null);+ const loaded = await readJSONFile(runLogFile(), null, { strict: true });const runs = Array.isArray(loaded?.runs) ? loaded.runs : [];const at = runs.findIndex((entry) => entry?.requestId === requestId);if (at < 0) return runs;diff --git a/server/services/quotaBurnStore.test.js b/server/services/quotaBurnStore.test.jsnew file mode 100644index 0000000000..70cf80f571--- /dev/null+++ b/server/services/quotaBurnStore.test.js@@ -0,0 +1,86 @@+/**+ * Durable quota-burn store safety. A failed read must stop each read-modify-+ * write path before it can replace the original plan, cooldowns, or run feed.+ */++import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { mkdir } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'quota-burn-store-'));++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));++const {+ getQuotaBurnConfig,+ getQuotaBurnInFlight,+ getQuotaBurnRuns,+ recordQuotaBurnInFlight,+ recordQuotaBurnRun,+ saveQuotaBurnConfig,+ settleQuotaBurnRun,+} = await import('./quotaBurnStore.js');++const cosDir = join(TEST_DATA_ROOT, 'cos');+const paths = {+ config: join(cosDir, 'quota-burn.json'),+ inFlight: join(cosDir, 'quota-burn-inflight.json'),+ runs: join(cosDir, 'quota-burn-runs.json'),+};++beforeEach(async () => {+ rmSync(cosDir, { recursive: true, force: true });+ await mkdir(cosDir, { recursive: true });+});++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++const writeUnreadable = (path) => {+ writeFileSync(path, '{"truncated":');+ return readFileSync(path);+};++const expectPreserved = async (path, before, operation) => {+ await expect(operation()).rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });+ expect(readFileSync(path)).toEqual(before);+};++describe('quotaBurnStore unreadable files', () => {+ it('preserves the plan when a settings save follows a failed read', async () => {+ const before = writeUnreadable(paths.config);++ await expectPreserved(paths.config, before, () => saveQuotaBurnConfig({ enabled: true }));+ await expect(getQuotaBurnConfig()).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });+ });++ it('preserves cooldowns when a scheduler stamp follows a failed read', async () => {+ const before = writeUnreadable(paths.inFlight);++ await expectPreserved(paths.inFlight, before, () => recordQuotaBurnInFlight(['series:s1']));+ await expect(getQuotaBurnInFlight()).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });+ });++ it('preserves the run feed for append and settlement writes', async () => {+ const before = writeUnreadable(paths.runs);++ await expectPreserved(paths.runs, before, () => recordQuotaBurnRun({ requestId: 'r1' }));+ await expectPreserved(paths.runs, before, () => settleQuotaBurnRun('r1', { accepted: true }));+ await expect(getQuotaBurnRuns()).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });+ });+});++describe('quotaBurnStore absent files', () => {+ it('initializes each mutable store from a trustworthy empty state', async () => {+ await saveQuotaBurnConfig({ enabled: true });+ await recordQuotaBurnInFlight(['series:s1'], { now: 1000 });+ await recordQuotaBurnRun({ requestId: 'r1' });++ expect(await getQuotaBurnConfig()).toMatchObject({ enabled: true });+ expect(await getQuotaBurnInFlight({ now: 1000 })).toEqual(new Set(['series:s1']));+ expect(await getQuotaBurnRuns()).toHaveLength(1);+ });+});diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 317645b4bb..96f6e1264c 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -506,6 +506,16 @@ describe('peerSync', () => {expect(cursors['peer-a'].subscribedSince).toBeGreaterThan(0);});+ it('refuses to subscribe over an unreadable list and preserves its bytes', async () => {+ const file = join(PATHS.data, 'sharing', 'peer_subscriptions.json');+ await writeFile(file, '{"subscriptions":');+ const before = await readFile(file);++ await expect(subscribePeer({ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' }))+ .rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });+ expect(await readFile(file)).toEqual(before);+ });+it('is idempotent — re-subscribing returns the existing record without duplicating', async () => {vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo', updatedAt: '2026-01-01T00:00:00Z' });vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });diff --git a/server/services/sharing/peerSyncShared.js b/server/services/sharing/peerSyncShared.jsindex 711f86aba0..4286b8b39b 100644--- a/server/services/sharing/peerSyncShared.js+++ b/server/services/sharing/peerSyncShared.js@@ -116,7 +116,9 @@ export function subscriptionId({ peerId, recordKind, recordId }) {export async function readState() {await ensureDir(join(PATHS.data, 'sharing'));- const raw = await readJSONFile(STATE_PATH(), { subscriptions: [] }, { logError: false });+ // Strict: every subscription mutation writes this value back. A swallowed+ // parse/read failure would replace the whole federation with one new row.+ const raw = await readJSONFile(STATE_PATH(), { subscriptions: [] }, { logError: false, strict: true });const subs = Array.isArray(raw?.subscriptions) ? raw.subscriptions : [];return { subscriptions: subs };}diff --git a/server/services/sharing/peerTombstoneCursors.js b/server/services/sharing/peerTombstoneCursors.jsindex 53ff10746f..89e65f1122 100644--- a/server/services/sharing/peerTombstoneCursors.js+++ b/server/services/sharing/peerTombstoneCursors.js@@ -31,12 +31,13 @@ import { isPlainObject } from '../../lib/objects.js';const STATE_PATH = () => join(PATHS.data, 'sharing', 'peer_tombstone_cursors.json');/**- * Load the full cursor map. Tolerates a missing or malformed file by- * returning `{}` — peers that have never sync'd carry no cursor.+ * Load the full cursor map. A missing file is a trustworthy empty map. A+ * present-but-unreadable file rejects because every cursor mutation writes+ * this value back and must never reset the other peers' acknowledgement state.*/async function readState() {await ensureDir(join(PATHS.data, 'sharing'));- const raw = await readJSONFile(STATE_PATH(), {}, { logError: false });+ const raw = await readJSONFile(STATE_PATH(), {}, { logError: false, strict: true });if (!isPlainObject(raw)) return {};// Defensive: a hand-edited file could contain non-object entries.const out = {};diff --git a/server/services/sharing/peerTombstoneCursors.test.js b/server/services/sharing/peerTombstoneCursors.test.jsindex 61fa0cbb5c..6486e5acd0 100644--- a/server/services/sharing/peerTombstoneCursors.test.js+++ b/server/services/sharing/peerTombstoneCursors.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { mkdir, rm, writeFile } from 'fs/promises';+import { mkdir, readFile, rm, writeFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';@@ -84,6 +84,16 @@ describe('peerTombstoneCursors', () => {expect(await initCursor(null)).toBeNull();expect(await initCursor(42)).toBeNull();});++ it('refuses to initialize over unreadable cursors and preserves their bytes', async () => {+ const file = join(PATHS.data, 'sharing', 'peer_tombstone_cursors.json');+ await writeFile(file, '{"peer-a":');+ const before = await readFile(file);++ await expect(initCursor('peer-b', { now: 1000 }))+ .rejects.toMatchObject({ code: 'UNREADABLE_STORE', status: 500 });+ expect(await readFile(file)).toEqual(before);+ });});describe('ackDeletesUpTo', () => {