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 (codex): enforce record-id allowlist on the PG path

Adam Eivy7cebf244dfea
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 533fc3c4ee..30184dbd2e 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -28,7 +28,7 @@
import { join, basename } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, ensureDir, resolveImageRef } from '../lib/fileUtils.js';
-import { getUniverseStore } from './universeBuilder/store.js';
+import { getUniverseStore, isValidUniverseId } from './universeBuilder/store.js';
import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../lib/canonPrompt.js';
import {
@@ -1456,6 +1456,15 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
const writeTasks = [];
for (const remote of remoteUniverses) {
if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;
+ // Skip a peer record whose id falls outside the store allowlist BEFORE the
+ // store throws on it — the store's writeRecord/queueRecordWrite reject such
+ // ids synchronously (collectionStore parity), which would otherwise abort
+ // this whole sync batch. A buggy/malicious peer can't poison the batch or
+ // plant a non-round-trippable id in `universes`.
+ if (!isValidUniverseId(remote.id)) {
+ console.warn(`⚠️ universe sync: skipping peer record with invalid id "${remote.id}"`);
+ continue;
+ }
const sanitized = sanitizeTemplate(remote);
if (!sanitized) continue;
// `ephemeral` is a LOCAL-only marker — never trust the inbound value.
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index d33a6861cb..5b40489b7f 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -753,6 +753,23 @@ describe("universeBuilder service", () => {
});
describe("mergeUniversesFromSync", () => {
+ it("skips a peer record with an invalid id without aborting the batch", async () => {
+ const good = await seedWorld();
+ const editTs = new Date(Date.now() + 60_000).toISOString();
+ // A malformed-id record (slash → outside the store allowlist) sits
+ // BEFORE a valid edit in the same batch. The bad one must be skipped,
+ // not throw and drop the valid edit after it.
+ const r = await svc.mergeUniversesFromSync([
+ { id: "bad/id", name: "Evil", updatedAt: editTs },
+ { ...good, name: "Edited", updatedAt: editTs },
+ ]);
+ expect(r.applied).toBe(true);
+ expect(r.count).toBe(1); // only the valid record applied
+ expect((await svc.getUniverse(good.id)).name).toBe("Edited");
+ await expect(svc.getUniverse("bad/id", { includeDeleted: true }))
+ .rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
it("applies an inbound soft-delete from a peer", async () => {
const w = await seedWorld();
const tombstoneTs = new Date(Date.now() + 60_000).toISOString();
diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.js
index 79e3cf22f5..d84140462b 100644
--- a/server/services/universeBuilder/store.js
+++ b/server/services/universeBuilder/store.js
@@ -42,6 +42,24 @@ function isFileBackend() {
return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';
}
+// Record-id allowlist — IDENTICAL to the collectionStore idPattern the file
+// backend enforced. The facade must reject the same ids on the PG path so the
+// two backends accept the same records: a malformed synced/imported id (e.g.
+// `bad/id`, or >128 chars) that the file store threw on must NOT silently land
+// in the `universes` table (where it can't round-trip back to files and could
+// break path/route consumers). queueRecordWrite/writeRecord/deleteRecord throw
+// on a bad id, so mergeUniversesFromSync's per-id `.catch` skips it exactly as
+// it did against the file backend.
+const ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
+/** True when `id` matches the universe record-id allowlist (collectionStore parity). */
+export const isValidUniverseId = (id) => typeof id === 'string' && ID_PATTERN.test(id);
+const isValidId = isValidUniverseId;
+function assertValidId(id) {
+ if (!isValidId(id)) {
+ throw new Error(`universeStore: invalid record id "${id}" — must match ${ID_PATTERN}`);
+ }
+}
+
// --- Mutation epoch (the dataSync federation-invisibility fix) ---
// Module-level so dataSync reads ONE monotonic counter regardless of how many
// times the facade is rebuilt (test PATHS.data swaps). Bumped on every record
@@ -163,6 +181,7 @@ function createFacade({ dir, sanitizeRecord }) {
// and PG serialize identically. Mirrors collectionStore's queueRecordWrite.
const recordTails = new Map();
function queueRecordWrite(id, fn) {
+ assertValidId(id); // parity with collectionStore.queueRecordWrite
const prev = recordTails.get(id) || Promise.resolve();
const next = prev.then(fn, fn);
const silenced = next.catch(() => {});
@@ -204,11 +223,13 @@ function createFacade({ dir, sanitizeRecord }) {
// ensureDir+atomicWrite(recordPath) / rm(recordDir) the service used to do.
// Both bump the mutation epoch so dataSync re-sends the universe snapshot.
writeRecord: async (id, record) => {
+ assertValidId(id); // parity with collectionStore.saveOneNow — reject bad ids on BOTH backends
const out = await (await getBackend()).writeRaw(id, record);
mutationEpoch += 1;
return out ?? record;
},
deleteRecord: async (id) => {
+ assertValidId(id); // parity with collectionStore.deleteOneNow
await (await getBackend()).deleteRaw(id);
mutationEpoch += 1;
},
diff --git a/server/services/universeBuilder/store.test.js b/server/services/universeBuilder/store.test.js
index 9319080ed4..4bb97e55ac 100644
--- a/server/services/universeBuilder/store.test.js
+++ b/server/services/universeBuilder/store.test.js
@@ -107,6 +107,23 @@ describe('universe store facade — file backend', () => {
expect((await s.loadRuns()).map((r) => r.id)).toEqual(['r-new', 'r-old']);
});
+ it('rejects ids outside the collectionStore allowlist on writeRecord/deleteRecord (backend parity)', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await expect(s.writeRecord('bad/id', { id: 'bad/id', name: 'X' })).rejects.toThrow(/invalid record id/);
+ await expect(s.writeRecord('a'.repeat(129), { id: 'a'.repeat(129), name: 'X' })).rejects.toThrow(/invalid record id/);
+ await expect(s.deleteRecord('bad/id')).rejects.toThrow(/invalid record id/);
+ // A valid id still works.
+ await s.writeRecord('ok-1', { id: 'ok-1', name: 'X' });
+ expect(await s.loadOneRaw('ok-1')).toEqual({ id: 'ok-1', name: 'X' });
+ });
+
+ it('queueRecordWrite throws on a bad id so mergeUniversesFromSync .catch skips it (parity)', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ // Throws synchronously, exactly like collectionStore.queueRecordWrite — the
+ // merge path wraps each write in a try/.catch so the bad record is skipped.
+ expect(() => s.queueRecordWrite('bad/id', async () => 'never')).toThrow(/invalid record id/);
+ });
+
it('verifySchemaVersion reports the file collection version', async () => {
const s = getUniverseStore(passthroughSanitize);
await s.writeRecord('u-1', { id: 'u-1', name: 'X' });