Skip to content

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

fix: preserve integration settings when stored JSON is unreadable (#6970)

[._.]/ Adam Eivyb43eccd6261f
diff --git a/server/services/calendarAccounts.js b/server/services/calendarAccounts.js
index 80225f5746..1f2e5c96aa 100644
--- a/server/services/calendarAccounts.js
+++ b/server/services/calendarAccounts.js
@@ -11,7 +11,8 @@ const queueWrite = createFileWriteQueue();
async function loadAccounts() {
await ensureDir(PATHS.calendar);
- const parsed = await readJSONFile(ACCOUNTS_FILE, {});
+ // Account mutations must never save an empty map over unreadable account bytes.
+ const parsed = await readJSONFile(ACCOUNTS_FILE, {}, { strict: true });
return isPlainObject(parsed) ? parsed : {};
}
diff --git a/server/services/claudeChangelog.js b/server/services/claudeChangelog.js
index 821498bd73..6e93e0489c 100644
--- a/server/services/claudeChangelog.js
+++ b/server/services/claudeChangelog.js
@@ -85,6 +85,8 @@ function stripHtml(html) {
* Returns cached data if checked within the last hour.
*/
export async function checkChangelog() {
+ // Replaceable feed cache: entries and the seen-version/check cursor come from
+ // this poll, not user edits. A failed read may safely rebuild them from the feed.
const state = await readJSONFile(STATE_FILE, defaultState())
// Return cached data if fresh enough
diff --git a/server/services/datadog.js b/server/services/datadog.js
index 0ef0f8e3f6..6d852a69f8 100644
--- a/server/services/datadog.js
+++ b/server/services/datadog.js
@@ -26,14 +26,14 @@ function sanitizeQueryValue(value) {
* Get DataDog instances configuration
*/
export async function getInstances() {
- return await readJSONFile(DATADOG_CONFIG_FILE, { instances: {} });
+ return await readJSONFile(DATADOG_CONFIG_FILE, { instances: {} }, { strict: true });
}
// Whether this install has any DataDog instance configured — the signal the
// instance-feature registry uses to decide whether the DataDog nav entries
// should appear before the user has toggled the feature explicitly.
//
-// Deliberately NOT getInstances(): `strict` makes a PRESENT-but-corrupt config
+// Like getInstances(), `strict` makes a PRESENT-but-corrupt config
// throw instead of reading as the empty default, so the caller records
// "detection failed" and falls back to the shipped default rather than a
// confident "no instances" that would silently hide the DataDog navigation. An
diff --git a/server/services/github.js b/server/services/github.js
index c8aa323c5a..0e82f62aa2 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -34,7 +34,8 @@ async function load() {
const now = Date.now();
if (cache && (now - cacheTimestamp) < CACHE_TTL_MS) return cache;
await ensureDir(DATA_DIR);
- cache = await readJSONFile(REPOS_FILE, defaultData());
+ // This cache includes user flags and secret assignments, not just remote repo data.
+ cache = await readJSONFile(REPOS_FILE, defaultData(), { strict: true });
cacheTimestamp = now;
return cache;
}
diff --git a/server/services/integrationJsonWriteback.test.js b/server/services/integrationJsonWriteback.test.js
new file mode 100644
index 0000000000..546f1c3baa
--- /dev/null
+++ b/server/services/integrationJsonWriteback.test.js
@@ -0,0 +1,134 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+import { EventEmitter } from 'events';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'integration-writeback-'));
+const fault = vi.hoisted(() => ({ path: null }));
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readFile: (...args) => String(args[0]) === fault.path
+ ? Promise.reject(Object.assign(new Error('injected read denial'), { code: 'EACCES' }))
+ : actual.readFile(...args),
+ };
+});
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+vi.mock('./settings.js', () => ({ getSettings: vi.fn(), updateSettings: vi.fn() }));
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ spawn: (_command, args) => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ queueMicrotask(() => {
+ const output = args[0] === 'repo'
+ ? JSON.stringify([{ name: 'sample', nameWithOwner: 'test-owner/sample' }])
+ : args[0] === 'auth' ? 'test-token' : 'test-owner';
+ child.stdout.emit('data', output);
+ child.emit('close', 0);
+ });
+ return child;
+ },
+}));
+
+const calendar = await import('./calendarAccounts.js');
+const datadog = await import('./datadog.js');
+const github = await import('./github.js');
+const obsidian = await import('./obsidian.js');
+const updates = await import('./updateChecker.js');
+const tools = await import('./tools.js');
+const { PATHS } = await import('../lib/fileUtils.js');
+
+const stores = [
+ {
+ name: 'calendar accounts', path: join(PATHS.calendar, 'accounts.json'),
+ seed: { existing: { id: 'existing', name: 'Existing' } },
+ mutate: () => calendar.createAccount({ name: 'New', type: 'outlook-calendar' }),
+ preserved: data => data.existing,
+ initialized: data => Object.values(data).some(account => account.name === 'New'),
+ },
+ {
+ name: 'Datadog instances', path: join(PATHS.data, 'datadog.json'),
+ seed: { instances: { existing: { name: 'Existing', site: 'api.datadoghq.com' } } },
+ mutate: () => datadog.upsertInstance('new', { name: 'New', site: 'api.datadoghq.com' }),
+ preserved: data => data.instances.existing,
+ initialized: data => data.instances.new.name === 'New',
+ },
+ {
+ name: 'GitHub repository configuration', path: join(PATHS.data, 'github-repos.json'),
+ seed: {
+ repos: { 'test-owner/sample': { fullName: 'test-owner/sample', flags: { npmProject: true }, managedSecrets: ['EXAMPLE'] } },
+ secrets: {}, githubUser: 'test-owner',
+ },
+ mutate: () => github.syncRepos(),
+ preserved: data => data.repos['test-owner/sample'].flags,
+ initialized: data => data.repos['test-owner/sample'].fullName === 'test-owner/sample',
+ },
+ {
+ name: 'Obsidian vault configuration', path: join(PATHS.brain, 'obsidian-vaults.json'),
+ seed: { vaults: [{ id: 'existing', name: 'Existing', path: '/example/old-vault' }] },
+ mutate: () => obsidian.addVault({ name: 'New', path: TEST_DATA_ROOT }),
+ preserved: data => data.vaults[0],
+ initialized: data => data.vaults[0].name === 'New',
+ },
+ {
+ name: 'update preferences', path: join(PATHS.data, 'update.json'),
+ seed: { ignoredVersions: ['1.0.0'], lastUpdateResult: { success: false, error: 'existing result' } },
+ mutate: () => updates.ignoreVersion('2.0.0'),
+ preserved: data => data.lastUpdateResult,
+ initialized: data => data.ignoredVersions.includes('2.0.0'),
+ },
+];
+
+beforeEach(() => {
+ fault.path = null;
+ github.__resetGitHubDataCache();
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+});
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+// These service boundaries uniquely prove each store cannot persist its fallback,
+// using real IO rather than assertions that a mocked reader received strict:true.
+describe.each(stores)('$name durable write-back', store => {
+ it.each(['{"truncated":', ''])('preserves unreadable bytes (%j) and can retry after repair', async bytes => {
+ mkdirSync(dirname(store.path), { recursive: true });
+ writeFileSync(store.path, bytes);
+ await expect(store.mutate()).rejects.toThrow('Unreadable JSON file');
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+
+ writeFileSync(store.path, JSON.stringify(store.seed));
+ await store.mutate();
+ const saved = JSON.parse(readFileSync(store.path, 'utf8'));
+ expect(store.preserved(saved)).toEqual(store.preserved(store.seed));
+ });
+
+ it('preserves existing bytes on a filesystem read failure', async () => {
+ mkdirSync(dirname(store.path), { recursive: true });
+ const bytes = JSON.stringify(store.seed);
+ writeFileSync(store.path, bytes);
+ fault.path = store.path;
+ await expect(store.mutate()).rejects.toThrow('Unreadable JSON file');
+ expect(readFileSync(store.path, 'utf8')).toBe(bytes);
+ });
+
+ it('initializes an absent file through the mutation entry point', async () => {
+ await store.mutate();
+ expect(store.initialized(JSON.parse(readFileSync(store.path, 'utf8')))).toBe(true);
+ });
+});
+
+it('tool updates already refuse to rewrite an unreadable record', async () => {
+ const path = join(PATHS.tools, 'existing.json');
+ mkdirSync(dirname(path), { recursive: true });
+ const bytes = '{"truncated":';
+ writeFileSync(path, bytes);
+ expect(await tools.updateTool('existing', { name: 'Changed' })).toBeNull();
+ expect(readFileSync(path, 'utf8')).toBe(bytes);
+});
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index f417571403..07e1d1944b 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -29,7 +29,7 @@ const SKIP_DIRS = new Set(['.obsidian', '.trash', 'node_modules', '.git']);
export async function getVaults() {
await ensureDir(PATHS.brain);
- const data = await readJSONFile(VAULTS_FILE, { vaults: [] });
+ const data = await readJSONFile(VAULTS_FILE, { vaults: [] }, { strict: true });
return data.vaults || [];
}
diff --git a/server/services/tools.js b/server/services/tools.js
index 1af6407aa9..efac5435bf 100644
--- a/server/services/tools.js
+++ b/server/services/tools.js
@@ -57,6 +57,8 @@ export async function getTools() {
return loadAllPromise;
}
+// Non-strict by design: updateTool returns without writing when this read fails;
+// registerTool is an explicit complete replacement and does not merge this fallback.
export async function getTool(id) {
return readJSONFile(toolPath(id), null);
}
diff --git a/server/services/updateChecker.js b/server/services/updateChecker.js
index f598b33030..f658aa0ef8 100644
--- a/server/services/updateChecker.js
+++ b/server/services/updateChecker.js
@@ -92,7 +92,8 @@ export async function getCurrentVersion() {
async function loadState() {
await ensureDir(PATHS.data);
- const raw = await readJSONFile(UPDATE_FILE, defaultState(), { allowArray: false });
+ // Ignored versions and update outcomes are durable user state, not a rebuildable cache.
+ const raw = await readJSONFile(UPDATE_FILE, defaultState(), { allowArray: false, strict: true });
const defaults = defaultState();
const stateFromFile = isPlainObject(raw) ? raw : {};
return {