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
address review (self): harden media-collection id at the sanitizer boundary
[._.]/ Adam Eivyaa4f779ab2ed
diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex d5901cd199..ea9d059007 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -702,11 +702,11 @@ const CHECKSUM_PATHS = {// content (and checksum) can change even when no record file moved.universe: [UNIVERSE_BUILDER_DIR, PEER_SUBSCRIPTIONS_FILE],pipeline: [PIPELINE_SERIES_DIR, PIPELINE_ISSUES_DIR, PEER_SUBSCRIPTIONS_FILE],- // mediaCollections invalidates on its own file AND on the parent record- // files — `getMediaCollectionsSnapshot` filters collections whose linked- // universe/series is ephemeral, so a "mark ephemeral" PATCH on a universe- // must re-checksum the collections snapshot even though- // media-collections.json itself didn't move. Same goes for un-ephemeral.+ // mediaCollections invalidates on its own record dir AND on the parent+ // record files — `getMediaCollectionsSnapshot` filters collections whose+ // linked universe/series is ephemeral, so a "mark ephemeral" PATCH on a+ // universe must re-checksum the collections snapshot even though no+ // media-collections record file moved. Same goes for un-ephemeral.mediaCollections: [MEDIA_COLLECTIONS_DIR, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR, PEER_SUBSCRIPTIONS_FILE],// videoHistory is a flat history file with no parent-record dependency —// its checksum invalidates only when video-history.json itself moves.diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex bb6847fa40..0ac5bf6bea 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -39,6 +39,14 @@ export const NAME_MAX_LENGTH = 80;export const DESCRIPTION_MAX_LENGTH = 500;export const ITEMS_MAX = 5000;+// A collection id is a filesystem path segment (data/media-collections/<id>/).+// The store's idPattern allowlist rejects anything else, so a record whose id+// can't round-trip to its own dir is unrepresentable — `sanitizeCollection`+// drops it here so a malformed/peer-supplied id is skipped at the boundary+// rather than thrown deep inside `queueRecordWrite` (which would abort a whole+// sync batch). Single source of truth: also passed to `createCollectionStore`.+const COLLECTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;+export { REF_MAX_LENGTH, itemKey };const sanitizeItem = (raw) => {@@ -81,7 +89,10 @@ const SERIES_ID_MAX = 80;const sanitizeCollection = (raw) => {if (!raw || typeof raw !== 'object') return null;- if (typeof raw.id !== 'string' || !raw.id) return null;+ // Reject ids the store can't persist (path-segment allowlist) so a peer-+ // supplied / hand-edited bogus id is dropped here instead of throwing inside+ // queueRecordWrite and aborting the rest of a merge batch.+ if (typeof raw.id !== 'string' || !COLLECTION_ID_PATTERN.test(raw.id)) return null;if (typeof raw.name !== 'string') return null;const name = raw.name.trim().slice(0, NAME_MAX_LENGTH);if (!name) return null;@@ -148,6 +159,9 @@ const store = () => {dir,type: 'mediaCollections',schemaVersion: TYPE_SCHEMA_VERSION,+ // Same allowlist `sanitizeCollection` enforces, so the store and the+ // sanitizer agree on which ids are representable (no drift).+ idPattern: COLLECTION_ID_PATTERN,// Runs on every loadOne/loadAll. Tombstones (deleted:true) survive// sanitization so the mutators and merge path can see them.sanitizeRecord: sanitizeCollection,@@ -247,6 +261,11 @@ export async function findOrCreateCollectionByName({ name, description = '', uni// Deterministic id when universe-linked (cross-machine convergence); a fresh// random id otherwise. Queue on whichever id this call would create/adopt so// two concurrent calls for the same universe serialize on the same record.+ // NOTE: the no-universe branch queues on a random id, so two concurrent calls+ // for the same NAME do NOT serialize and could both create a same-named+ // bucket. Acceptable: this name-first helper has no production callers (it's+ // the ad-hoc/CLI path); universe/series filing uses the deterministic-id+ // helpers, which converge. A hot caller should derive a stable queue key.const canonId = linkedCollectionId({ universeId: normalizedUniverseId });const queueId = canonId || randomUUID();let createdId = null;@@ -348,10 +367,10 @@ export async function findCollectionByUniverseId(universeId) {/*** Atomic universeId-first upsert for a universe's auto-managed collection.*- * Resolution order (serialized via the shared file write tail):+ * Resolution order (serialized on the deterministic id's per-record queue):* 1. universeId stamp wins. Returned as-is — the caller's `universeName`* can be stale (it was a snapshot taken before this call entered the- * write tail), so reconciling the name here could ping-pong a fresh+ * queue), so reconciling the name here could ping-pong a fresh* cascade rename back to an old name. `renameCollectionForUniverse`* is the canonical path for name changes; if its best-effort cascade* fails, the surviving stale name is acceptable until the userdiff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex f180cc7c9e..dceb7c3c7e 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -1122,6 +1122,20 @@ describe('mergeMediaCollectionsFromSync', () => {expect(all[0].id).toBe('good');});+ it('skips a record whose id is not a valid store path-segment WITHOUT aborting the batch', async () => {+ // A malformed/peer-supplied id like '../../escape' can't be persisted (the+ // store's id allowlist would throw inside queueRecordWrite). sanitizeCollection+ // must drop it at the boundary so the valid records in the same batch still merge.+ const result = await svc.mergeMediaCollectionsFromSync([+ { id: '../../escape', name: 'Evil', description: '', coverKey: null, universeId: null, seriesId: null, items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z' },+ { id: 'has space', name: 'Spacey', items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z' },+ { id: 'valid-after-bad', name: 'Survivor', description: '', coverKey: null, universeId: null, seriesId: null, items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z' },+ ]);+ expect(result).toEqual({ applied: true, count: 1 });+ const all = await svc.listCollections({ includeDeleted: true });+ expect(all.map((c) => c.id)).toEqual(['valid-after-bad']);+ });+it('rejects items whose ref contains path-traversal tokens', async () => {// Defense in depth — a peer can push a collection containing a ref// like '../etc/passwd' via the linkedCollection field. sanitizeItemdiff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 56a7d2349f..30b98d8c85 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -1506,8 +1506,9 @@ export async function applyIncomingPush(payload) {// semantics as the snapshot-sync mediaCollections category. Failures here// don't fail the push: the record itself is already merged and the next// snapshot-sync cycle will reconcile the collection if it diverged. The- // sanitizer in mediaCollections strips a peer-supplied `id` that isn't a- // string, so a bogus payload can't plant a malformed row.+ // sanitizer in mediaCollections drops a peer-supplied `id` that isn't a+ // valid path-segment (the store's id allowlist), so a bogus payload can't+ // plant a malformed row or abort the batch.//// Defense in depth on the peer-supplied envelope:// - plain-object check (arrays would get wrapped and the sanitizer