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

address review (self): stable checksum + prototype-id guard for brain reconcile

Adam Eivy5e180e0b3043
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
index 0fa5bd4244..91eb4aa8f3 100644
--- a/server/routes/brain.test.js
+++ b/server/routes/brain.test.js
@@ -90,11 +90,11 @@ vi.mock('../services/brainSync.js', () => ({
applyRemoteChanges: vi.fn()
}));
-// Mock the brain anti-entropy reconcile service (#1077)
+// Mock the brain anti-entropy reconcile service (#1077). Only the two read
+// endpoints are exposed over HTTP; applyBrainSnapshot is orchestrator-only.
vi.mock('../services/brainReconcile.js', () => ({
getBrainChecksum: vi.fn(),
- getBrainSnapshot: vi.fn(),
- applyBrainSnapshot: vi.fn()
+ getBrainSnapshot: vi.fn()
}));
// Mock the brain journal service
diff --git a/server/services/brainReconcile.js b/server/services/brainReconcile.js
index 99e4fa3eb4..582768a443 100644
--- a/server/services/brainReconcile.js
+++ b/server/services/brainReconcile.js
@@ -52,13 +52,32 @@ async function buildRawMap() {
return map;
}
+/**
+ * Stable JSON stringify: serialize object keys in sorted order at every depth,
+ * so the output is independent of key-insertion order. Plain `JSON.stringify`
+ * preserves insertion order, which would let two installs holding the SAME
+ * logical record hash differently — e.g. `backfillOriginInstanceId` appends
+ * `originInstanceId` last on a migrated record, while a freshly-created record
+ * carries it mid-object. That benign field-order skew would otherwise force a
+ * wasted snapshot fetch+merge every cycle. Arrays keep their order (significant);
+ * only object keys are sorted. Records are JSON-safe (no Date/Map/Set/cycles).
+ */
+function stableStringify(value) {
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
+ const keys = Object.keys(value).sort();
+ return `{${keys.map(k => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
+}
+
/**
* Deterministic md5 over the canonical brain record map. Matches `dataSync`'s
- * `computeChecksum` (md5 of a JSON string) so the two reconcile layers behave
- * the same. Stable across installs because `buildRawMap` sorts types + ids.
+ * `computeChecksum` shape (md5 of a JSON string) but uses a key-sorted
+ * serialization so two installs with identical brain state hash identically
+ * regardless of per-record field order. `buildRawMap` sorts the type + id
+ * levels; `stableStringify` extends order-independence into each record's fields.
*/
function computeChecksum(rawMap) {
- return createHash('md5').update(JSON.stringify(rawMap)).digest('hex');
+ return createHash('md5').update(stableStringify(rawMap)).digest('hex');
}
/**
@@ -95,6 +114,11 @@ export async function getBrainSnapshot() {
* @returns {Promise<{inserted:number, updated:number, deleted:number, skipped:number}>}
*/
export async function applyBrainSnapshot(snapshot) {
+ // `inserted` stays 0 by design: brainStorage.applyRemoteRecord doesn't
+ // distinguish insert vs update (it returns only `{ applied }`), so every
+ // applied upsert is counted as `updated`. The key is kept for shape-parity
+ // with brainSync.applyRemoteChanges; the caller sums all three so the total
+ // is correct either way.
let inserted = 0, updated = 0, deleted = 0, skipped = 0;
const relayBatch = [];
@@ -109,6 +133,11 @@ export async function applyBrainSnapshot(snapshot) {
if (!byId || typeof byId !== 'object') continue;
for (const [id, record] of Object.entries(byId)) {
+ // Skip dangerous prototype keys: a peer record under id `__proto__`
+ // hits Object.prototype's setter (or is dropped by JSON.stringify on
+ // write) — it can never persist or converge, but would still report
+ // applied and emit a phantom relay entry. Reject up front.
+ if (id === '__proto__' || id === 'constructor' || id === 'prototype') { skipped++; continue; }
if (!record || !record.updatedAt) { skipped++; continue; }
const op = record._deleted === true ? 'delete' : 'update';
// For a delete, hand applyRemoteRecord the wire-shape tombstone fields
diff --git a/server/services/brainReconcile.test.js b/server/services/brainReconcile.test.js
index af8db5f854..37e4daf5bd 100644
--- a/server/services/brainReconcile.test.js
+++ b/server/services/brainReconcile.test.js
@@ -61,6 +61,21 @@ describe('brainReconcile checksum', () => {
const tomb = await getBrainChecksum();
expect(live).not.toBe(tomb);
});
+
+ // #1077 review finding: plain JSON.stringify preserves field-insertion order,
+ // so two installs holding the SAME logical record (e.g. one migrated by
+ // backfillOriginInstanceId, which appends originInstanceId LAST) would hash
+ // differently and re-pull the snapshot every cycle for no reason.
+ it('is independent of per-record FIELD order (stable stringify)', async () => {
+ emptyStores({ links: { a: { id: 'a', title: 'A', updatedAt: '2026-01-01T00:00:00.000Z', originInstanceId: 'inst-1' } } });
+ const c1 = await getBrainChecksum();
+
+ // Identical record, fields in a different order (as a migrated record would be).
+ emptyStores({ links: { a: { originInstanceId: 'inst-1', updatedAt: '2026-01-01T00:00:00.000Z', id: 'a', title: 'A' } } });
+ const c2 = await getBrainChecksum();
+
+ expect(c1).toBe(c2);
+ });
});
describe('brainReconcile snapshot', () => {
@@ -125,4 +140,27 @@ describe('applyBrainSnapshot', () => {
expect(res).toEqual({ inserted: 0, updated: 0, deleted: 0, skipped: 0 });
expect(brainStorage.applyRemoteRecord).not.toHaveBeenCalled();
});
+
+ // #1077 review finding: a peer record under a dangerous prototype id can
+ // never persist/converge (dropped on write) but would still report applied
+ // and emit a phantom relay. Reject those ids up front.
+ it('skips dangerous prototype ids without applying or relaying', async () => {
+ brainStorage.applyRemoteRecord.mockResolvedValue({ applied: true });
+ // Build via JSON.parse to match the production path (res.json()): a JSON
+ // `"__proto__"` key becomes a real OWN enumerable property, unlike an object
+ // literal where `__proto__:` would set the prototype and never reach the loop.
+ const snapshot = JSON.parse(JSON.stringify({ records: { links: {} } }));
+ snapshot.records.links = JSON.parse(`{
+ "__proto__": { "updatedAt": "2026-01-02T00:00:00.000Z", "title": "evil" },
+ "constructor": { "updatedAt": "2026-01-02T00:00:00.000Z", "title": "evil" },
+ "prototype": { "updatedAt": "2026-01-02T00:00:00.000Z", "title": "evil" },
+ "ok": { "id": "ok", "updatedAt": "2026-01-02T00:00:00.000Z", "title": "good" }
+ }`);
+ const res = await applyBrainSnapshot(snapshot);
+ // Only the legitimate id is applied; the three prototype keys are skipped.
+ expect(brainStorage.applyRemoteRecord).toHaveBeenCalledTimes(1);
+ expect(brainStorage.applyRemoteRecord).toHaveBeenCalledWith(
+ 'links', 'ok', expect.objectContaining({ id: 'ok' }), 'update');
+ expect(res.updated).toBe(1);
+ });
});
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index e055e9ff12..9a5fbd8e17 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -217,7 +217,9 @@ export async function getAll(type) {
* Unlike `getAll` (which strips tombstones for user-facing reads), the sync
* reconcile path needs tombstones too: they carry the LWW `updatedAt` clock a
* peer must see to keep a delete from resurrecting. Returns a shallow copy of
- * the `{ id: record }` map so callers can't mutate the cache.
+ * the `{ id: record }` map — the map itself is safe to mutate, but the record
+ * objects are shared with the cache by reference, so callers must treat them as
+ * read-only (the reconcile path only serializes them, never mutates).
*/
export async function getRawRecords(type) {
const data = await loadJsonStore(type);