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(settings): strip MortalLoom store keys from settings.json (#448)

[._.]/ Adam Eivyd484276aaff3
diff --git a/server/lib/README.md b/server/lib/README.md
index 2a0c16a129..60f9a801ee 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -162,7 +162,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `asyncMutex.js` | Promise-based async mutex. |
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |
-| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement) + `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads). |
+| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
diff --git a/server/lib/objects.js b/server/lib/objects.js
index c952b43602..78d4b95ba4 100644
--- a/server/lib/objects.js
+++ b/server/lib/objects.js
@@ -39,7 +39,11 @@ export const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArr
// helper is shared across three routes and a future caller could hand it
// `req.body` directly or an LLM tool-call payload — defense in depth is
// cheap. Reflects no behavioral change for valid input.
-const POLLUTING_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
+//
+// Exported so other sanitizers (e.g. server/services/settings.js
+// stripStoreKeys) can share one canonical denylist instead of redefining
+// it (drift risk on security-relevant constants).
+export const POLLUTING_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
export const deepMerge = (base, patch) => {
if (!isPlainObject(patch)) return patch === undefined ? base : patch;
diff --git a/server/services/settings.js b/server/services/settings.js
index a9b990e65e..27861185d7 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -2,9 +2,49 @@ import { readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { EventEmitter } from 'events';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { isPlainObject, POLLUTING_KEYS } from '../lib/objects.js';
+
+// POLLUTING_KEYS (`__proto__`/`constructor`/`prototype`) is the project-wide
+// prototype-pollution denylist (defined in server/lib/objects.js). Without it,
+// rebuilding the cleaned object via `cleaned[k] = v` against a payload that
+// JSON.parse exposed those names on would invoke the prototype setter and
+// mutate Object.prototype. Settings never legitimately uses these keys.
const SETTINGS_FILE = join(PATHS.data, 'settings.json');
+// Keys that belong to the MortalLoom iCloud store (MortalLoom.json), NOT to
+// PortOS settings (data/settings.json). A historical bug or hand-edit can pollute
+// settings.json with these top-level arrays/objects, which then bloats every
+// `GET /api/settings` response and rides forward through every
+// `saveSettings({ ...current, x: y })` mutation. Strip them on both read and
+// write so the corruption auto-heals on the next save and can't propagate.
+// Superset of ARRAY_KEYS in mortalLoomStore.js — also includes the non-array
+// store objects `profile` and `genomeScanRecord` observed in the actual
+// corruption. Keep both sides in sync when MortalLoom adds new store keys.
+const MORTALLOOM_STORE_KEYS = new Set([
+ 'alcoholDrinks', 'alcoholPresets', 'bloodTests', 'bodyEntries',
+ 'epigeneticTests', 'eyeExams', 'goals', 'habits', 'healthMetrics',
+ 'nicotineEntries', 'nicotinePresets', 'saunaPresets', 'saunaSessions',
+ 'profile', 'genomeScanRecord'
+]);
+
+// Pure rebuild — drops MortalLoom store keys and prototype-pollution keys.
+// Non-plain-object inputs (arrays, null, primitives) pass through unchanged;
+// rebuilding them as `{}` would silently coerce-then-lose the original value.
+// Warning emission is the caller's responsibility (see `save()`) so a single
+// updateSettings call produces at most one log line, tied to a successful
+// persisted write.
+const stripStoreKeys = (settings) => {
+ if (!isPlainObject(settings)) return settings;
+ const cleaned = {};
+ for (const [k, v] of Object.entries(settings)) {
+ if (POLLUTING_KEYS.has(k)) continue;
+ if (MORTALLOOM_STORE_KEYS.has(k)) continue;
+ cleaned[k] = v;
+ }
+ return cleaned;
+};
+
// Tiny pub/sub so cache holders (annotationIdentity, etc.) can invalidate on
// writes without each subscribing through socket.io. Listeners receive the
// merged settings object so they can pick fields they care about. Use a
@@ -15,22 +55,45 @@ export const settingsEvents = new EventEmitter();
// default-10-listeners warning.
settingsEvents.setMaxListeners(50);
-const load = async () => {
+// Reads are always silent — a polluted file would otherwise spam logs on
+// every GET /api/settings. `save()` warns based on what it's HANDED, so:
+// - `updateSettings(patch)` exposes both disk pollution (via the unstripped
+// raw snapshot) AND patch pollution to save(), yielding one consolidated
+// warning per successful write.
+// - Manual `getSettings() → modify → saveSettings(...)` flows hand save() an
+// already-stripped object, so no warning fires — but those flows also
+// can't reintroduce store-key pollution, so silence is correct.
+// - A direct `saveSettings(badObject)` with store keys warns once after the
+// write resolves.
+const loadRaw = async () => {
const raw = await readFile(SETTINGS_FILE, 'utf-8').catch(() => '{}');
return safeJSONParse(raw, {});
};
const save = async (settings) => {
- await writeFile(SETTINGS_FILE, JSON.stringify(settings, null, 2) + '\n');
- settingsEvents.emit('settings:updated', settings);
+ const cleaned = stripStoreKeys(settings);
+ await writeFile(SETTINGS_FILE, JSON.stringify(cleaned, null, 2) + '\n');
+ // Warn AFTER the successful write so a thrown writeFile never produces
+ // a misleading "stripped" log line for a write that didn't happen.
+ if (isPlainObject(settings)) {
+ const polluted = Object.keys(settings).filter((k) => MORTALLOOM_STORE_KEYS.has(k));
+ if (polluted.length > 0) {
+ console.warn(`⚠️ settings.json: stripped MortalLoom store keys: ${polluted.join(', ')}`);
+ }
+ }
+ settingsEvents.emit('settings:updated', cleaned);
+ return cleaned;
};
-export const getSettings = load;
+export const getSettings = async () => stripStoreKeys(await loadRaw());
export const saveSettings = save;
+// Merge against the unstripped on-disk snapshot so save() sees every
+// MortalLoom store key in one place — guaranteeing exactly one warning
+// per updateSettings call, only when the write succeeds.
export const updateSettings = async (patch) => {
- const current = await load();
- const merged = { ...current, ...patch };
- await save(merged);
- return merged;
+ const raw = await loadRaw();
+ const incoming = isPlainObject(patch) ? patch : {};
+ const merged = { ...raw, ...incoming };
+ return save(merged);
};
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 469dceb0cc..9a333c9686 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -148,4 +148,146 @@ describe('settings.js', () => {
expect(result).toEqual({ theme: 'dark' });
});
});
+
+ describe('MortalLoom store key pollution guard', () => {
+ it('strips MortalLoom-store top-level keys on read', async () => {
+ // Simulates the historical corruption: settings.json contains both
+ // legitimate settings and MortalLoom store arrays.
+ const polluted = {
+ theme: 'dark',
+ timezone: 'UTC',
+ alcoholDrinks: [{ id: 'A', name: 'beer' }],
+ bloodTests: [{ id: 'B' }],
+ goals: [{ id: 'G' }],
+ profile: { name: 'X' },
+ mortalloom: { enabled: true }
+ };
+ readFile.mockResolvedValue(JSON.stringify(polluted));
+
+ const result = await getSettings();
+
+ expect(result).toEqual({
+ theme: 'dark',
+ timezone: 'UTC',
+ mortalloom: { enabled: true }
+ });
+ expect(result.alcoholDrinks).toBeUndefined();
+ expect(result.goals).toBeUndefined();
+ expect(result.profile).toBeUndefined();
+ });
+
+ it('strips MortalLoom-store keys before writing', async () => {
+ const existing = { theme: 'dark' };
+ readFile.mockResolvedValue(JSON.stringify(existing));
+ writeFile.mockResolvedValue();
+
+ // Caller accidentally passes a payload with store keys.
+ await updateSettings({ alcoholDrinks: [], goals: [], voice: { enabled: true } });
+
+ const [, content] = writeFile.mock.calls[0];
+ const written = JSON.parse(content);
+ expect(written).toEqual({ theme: 'dark', voice: { enabled: true } });
+ expect(written.alcoholDrinks).toBeUndefined();
+ expect(written.goals).toBeUndefined();
+ });
+
+ it('auto-heals corrupted settings.json on next save', async () => {
+ // Polluted file on disk.
+ const polluted = {
+ theme: 'dark',
+ alcoholDrinks: [{ id: 'A' }],
+ bloodTests: [{ id: 'B' }],
+ habits: [{ id: 'H' }]
+ };
+ readFile.mockResolvedValue(JSON.stringify(polluted));
+ writeFile.mockResolvedValue();
+
+ // Any save (even unrelated) cleans up the file.
+ await updateSettings({ timezone: 'UTC' });
+
+ const [, content] = writeFile.mock.calls[0];
+ const written = JSON.parse(content);
+ expect(written).toEqual({ theme: 'dark', timezone: 'UTC' });
+ });
+
+ it('preserves legitimate mortalloom config key (not in store-key list)', async () => {
+ readFile.mockResolvedValue('{}');
+ writeFile.mockResolvedValue();
+
+ await updateSettings({ mortalloom: { enabled: true, path: '/foo' } });
+
+ const [, content] = writeFile.mock.calls[0];
+ const written = JSON.parse(content);
+ expect(written.mortalloom).toEqual({ enabled: true, path: '/foo' });
+ });
+
+ it('reads are silent but auto-heal write announces the strip', async () => {
+ // Pollution sitting on disk.
+ const polluted = {
+ theme: 'dark',
+ alcoholDrinks: [{ id: 'A' }]
+ };
+ readFile.mockResolvedValue(JSON.stringify(polluted));
+ writeFile.mockResolvedValue();
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ // Pure read — must NOT log (otherwise every GET /api/settings spams).
+ await getSettings();
+ expect(warnSpy).not.toHaveBeenCalled();
+
+ // Write path — the auto-heal must surface a single warning so the
+ // operator sees the file is being cleaned.
+ await updateSettings({ timezone: 'UTC' });
+ expect(warnSpy).toHaveBeenCalled();
+ const firstCallArg = warnSpy.mock.calls[0][0];
+ expect(firstCallArg).toContain('alcoholDrinks');
+
+ warnSpy.mockRestore();
+ });
+
+ it('does not warn when writeFile throws (no misleading log for a write that did not happen)', async () => {
+ readFile.mockResolvedValue(JSON.stringify({ theme: 'dark', alcoholDrinks: [{}] }));
+ writeFile.mockRejectedValue(new Error('EROFS'));
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ await expect(updateSettings({ timezone: 'UTC' })).rejects.toThrow('EROFS');
+ expect(warnSpy).not.toHaveBeenCalled();
+
+ warnSpy.mockRestore();
+ });
+
+ it('emits exactly one warning per updateSettings even when both disk AND patch are polluted', async () => {
+ // Disk pollution: alcoholDrinks. Patch pollution: goals. Spec: one log line.
+ readFile.mockResolvedValue(JSON.stringify({ theme: 'dark', alcoholDrinks: [{}] }));
+ writeFile.mockResolvedValue();
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ await updateSettings({ goals: [], timezone: 'UTC' });
+
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ const msg = warnSpy.mock.calls[0][0];
+ expect(msg).toContain('alcoholDrinks');
+ expect(msg).toContain('goals');
+
+ warnSpy.mockRestore();
+ });
+
+ it('drops __proto__ / constructor / prototype keys instead of mutating Object.prototype', async () => {
+ // A `__proto__` own property arrives via JSON.parse of a payload like
+ // `{"__proto__":{"polluted":true}}`. Without the guard, the cleaned-object
+ // rebuild would invoke the __proto__ setter.
+ const malicious = JSON.parse('{"theme":"dark","__proto__":{"polluted":true},"constructor":{"polluted":true}}');
+ readFile.mockResolvedValue(JSON.stringify(malicious));
+ writeFile.mockResolvedValue();
+
+ const result = await getSettings();
+
+ expect(result).toEqual({ theme: 'dark' });
+ // Confirm no prototype pollution — a fresh object must not see `polluted`.
+ expect({}.polluted).toBeUndefined();
+ });
+ });
});