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 (gemini): centralize isSafeRecordId + fix deleteConflict id validation
Adam Eivy9f99a0750bb4
diff --git a/PLAN.md b/PLAN.mdindex 29c7765890..af828b0f7e 100644--- a/PLAN.md+++ b/PLAN.md@@ -155,6 +155,7 @@ Surfaced by the multi-reviewer release gate for v2.10.0. The CRITICAL/correctnes- [ ] [merge-union-seasons-collision] **`unionSeasons` silently drops a loser season whose `number` collides with a survivor's.** `server/services/recordMerge.js` (~line 151) `continue`s past a colliding loser season, discarding its authored title/episodes/arc metadata even though the merge is documented as "no data loss" (this is a local merge, so the conflict journal never sees it). Either union the loser season's non-empty fields into the survivor, or surface a count in the `cascade` summary so the UI can warn "N loser seasons not merged." (Batch-2 NIT.)- [ ] [conflict-journal-basehash-evict] **`sync_base_hashes.json` entries are never evicted on record delete.** `server/lib/conflictJournal.js#setSyncBaseHash` keys by `${kind}:${id}`; when a record is tombstoned and force-pruned its base-hash entry leaks (slow unbounded growth on a long-lived federated install — not a correctness bug). Delete the entry as part of the delete cascade / tombstone prune. (Batch-2 NIT.)- [ ] [test-merge-route-contracts] **Route-level tests for the merge endpoints' contracts.** `universeBuilder.test.js`/`pipeline.test.js` only assert `status === 400` for identical-ids and never pin the body `code` (`MERGE_VALIDATION`); there's no route test for a successful `POST /merge` (`{ merged, cascade }`), the `DELETE /universe-builder/:id` 409 `UNIVERSE_HAS_LIVE_SERIES` + `context.blockingSeries` body the UI depends on, nor the `POST /merge/ai-resolve` error contract (`MERGE_AI_NO_MERGEABLE_FIELDS` 422, no-provider, `LLM_INVALID_JSON` 502). Add them. (Batch-2 IMPROVEMENT.)+- [ ] [share-empty-scalar-helper] **Move `isEmptyScalar` out of `recordMerge.js` into a shared util.** `recordMerge.js`'s `isEmptyScalar` (null/undefined/empty-string/empty-array predicate) is now used by `resolveScalars` and `unionSeasons` and is a generic enough "is this value blank" check to live in `server/lib/objects.js` (or `validation.js`) for reuse. Low priority. (Batch-3/gemini NIT.)- [ ] [test-codereview-defaults-cache-isolation] **`codeReview.test.js` doesn't reset the module-level `cachedDefaults` between tests.** `getCodeReviewDefaults` memoizes into `cachedDefaults` (invalidated only by a `settings:updated` event the test stubs as a no-op); `afterEach` resets `mockedSettings.current` but never clears the cache, so a future test adding a second `getCodeReviewDefaults()` call with different settings would silently read stale data. Export a test-only `__resetCodeReviewDefaultsCache()` and call it in `afterEach`. Latent (no current failure). (Batch-1/claude NIT.)- [ ] [test-codereview-local-route] **`POST /api/code-review/local` has no route-level test.** Add a supertest-style test (mocking `runLocalCodeReview`/`getSettings`): empty `diff` → 400 (Zod), unknown `backend` → 400 (`z.enum`), `model` omitted falls back to the settings model, and `{ ok: false }` service result → 502. Also add `validation.test.js` assertions that `featureProviderConfigSchema.parse({ providerId:'', model:'' })` yields `undefined`s and `codeReviewSettingsSchema` rejects unknown keys (`.strict()`). (Batch-3 IMPROVEMENT/NIT.)diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 4721929dcd..da24f9c4e9 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -20,6 +20,18 @@ export const refineImagePixelCap = (d) =>!(d.width && d.height) || d.width * d.height <= MAX_IMAGE_PIXELS;export const PIXEL_CAP_MESSAGE = `Total pixels (width × height) must be ≤ ${MAX_IMAGE_PIXELS.toLocaleString()}`;+// Reject a record id that isn't a bare filename segment. Use before a+// peer-supplied / externally-sourced id is interpolated into a filesystem path+// (e.g. the sharing importer's raw `join(bucket, …, `${id}.json`)` reads, or+// the conflict journal's `recordDir(id)`), so a `../`-bearing id can't turn the+// read/delete into a path-traversal oracle. Records persisted through a+// collectionStore are already gated by its `idPattern`; this guards the raw+// path sites that don't go through a store.+export const isSafeRecordId = (id) =>+ typeof id === 'string' && id.length > 0+ && id !== '.' && id !== '..'+ && !id.includes('/') && !id.includes('\\') && !id.includes('\0');+// Build a sparse-map Zod shape from a string array of boolean-typed keys.// Returns the raw record so callers can either spread it (...optionalBooleanMap(KEYS))// into a larger object schema or wrap it directly (z.object(optionalBooleanMap(KEYS))).diff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex 6a25fe12fa..f02e22631b 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -25,6 +25,7 @@*/import { existsSync } from 'fs';+import { isSafeRecordId } from '../lib/validation.js';import { conflictJournalStore, RESTORABLE_FIELDS } from '../lib/conflictJournal.js';import { updateUniverse, ERR_NOT_FOUND as UNIVERSE_NOT_FOUND } from './universeBuilder.js';import { updateSeries, ERR_NOT_FOUND as SERIES_NOT_FOUND } from './pipeline/series.js';@@ -114,6 +115,10 @@ export async function resolveConflict(id, { action, fields = [] } = {}) {/** Permanently remove a journal entry (the "dismiss / clear" action). */export async function deleteConflict(id) {+ // Validate the id BEFORE interpolating it into recordDir(id) — getConflict()+ // (which we no longer call) used to enforce this via the store's isValidId;+ // an unguarded id would make recordDir a path-traversal existence oracle.+ if (!isSafeRecordId(id)) throw makeErr(`Conflict entry not found: ${id}`, ERR_NOT_FOUND);// Don't gate on getConflict() — it requires a successful parse, so a corrupt// journal entry would 404 here and become permanently undeletable. Check raw// directory existence instead, then hard-delete (deleteOne is idempotent).diff --git a/server/services/conflictJournalResolver.test.js b/server/services/conflictJournalResolver.test.jsindex 5b3b799c74..5ca87af8c0 100644--- a/server/services/conflictJournalResolver.test.js+++ b/server/services/conflictJournalResolver.test.js@@ -106,4 +106,9 @@ describe('conflictJournalResolver', () => {expect(await resolver.listConflicts()).toHaveLength(0);await expect(resolver.getConflict(e1)).rejects.toMatchObject({ code: resolver.ERR_NOT_FOUND });});++ it('deleteConflict rejects a path-traversal id without probing the filesystem', async () => {+ await expect(resolver.deleteConflict('../../etc/passwd')).rejects.toMatchObject({ code: resolver.ERR_NOT_FOUND });+ await expect(resolver.deleteConflict('..')).rejects.toMatchObject({ code: resolver.ERR_NOT_FOUND });+ });});diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 99e8b2341f..f53a644a5b 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -26,6 +26,7 @@ import { copyFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { EventEmitter } from 'events';import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';+import { isSafeRecordId } from '../../lib/validation.js';import { getBucket, bucketBlobPath, bucketBlobSidecarPath, imageSidecarName, isHexHash } from './buckets.js';import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';@@ -300,15 +301,6 @@ async function copyAssetsLocally(bucketPath, assetRefs) {return { copied, available, missing };}-// Peer-supplied record ids index into `join(bucketPath, …, `${id}.json`)`. A-// `../`-bearing id from a buggy/malicious federation peer would turn those reads-// into a path-traversal existence/parse oracle on the host. Reject anything that-// isn't a bare filename segment before it reaches a join. (Write-side idPattern-// already blocks persistence; this closes the read side.)-const isSafeRecordId = (id) =>- typeof id === 'string' && id.length > 0 && basename(id) === id- && !id.includes('/') && !id.includes('\\') && !id.includes('\0');-async function processAnnotationManifest(bucket, manifest) {const recordId = (manifest.recordIds || [])[0] || manifest.senderInstanceId;if (!recordId) return { applied: 0, missing: true, reason: 'no-record-id' };