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 round 2 (claude+codex): sanitize typed mirror columns + parity test
Adam Eivy2af8e298500e
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 953fca5869..286763117e 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -163,6 +163,17 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {expect(/type VARCHAR\(32\)/i.test(extractCreateTable(DB_JS, 'catalog_ingredients'))).toBe(true);});+ // Non-catalog table that nonetheless lives in BOTH DDL sources (fresh-install+ // init-db.sql + upgrade-path ensureSchema) and so has the same drift risk.+ it('creative_director_projects has the same columns in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'creative_director_projects');+ const jsBody = extractCreateTable(DB_JS, 'creative_director_projects');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE creative_director_projects').toBeTruthy();+ expect(jsBody, 'db.js missing CREATE TABLE creative_director_projects').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ });+it('search_tsv payload field set matches', () => {// Both files re-declare the GENERATED ALWAYS expression character-for-// character today. If one side adds a payload key (e.g. voiceNotes) anddiff --git a/server/scripts/migrateCreativeDirectorToDB.js b/server/scripts/migrateCreativeDirectorToDB.jsindex b89dd4ca2d..06d451fd09 100644--- a/server/scripts/migrateCreativeDirectorToDB.js+++ b/server/scripts/migrateCreativeDirectorToDB.js@@ -33,6 +33,7 @@ import { readFile, writeFile, rename } from 'fs/promises';import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';import { query } from '../lib/db.js';+import { mirrorStatus, mirrorTimestamp } from '../services/creativeDirector/projectsLogic.js';const LEGACY_FILENAME = 'creative-director-projects.json';const IMPORTED_SUFFIX = '.imported';@@ -87,18 +88,22 @@ export async function migrateCreativeDirectorToDB() {skipped += 1;continue;}- // Import verbatim — including the full runs[] history. The cap is enforced- // by the live store on the next write, not here, so the migration is lossless.+ // Import verbatim — the full record (runs[] included) goes into `data`. The+ // typed mirror columns are sanitized via the shared helpers so a legacy+ // record with a malformed timestamp or over-long status can't make the+ // INSERT throw and abort the whole import (which runs during backend init).+ const now = new Date().toISOString();+ const createdAt = mirrorTimestamp(project.createdAt, now);const result = await query(`INSERT INTO creative_director_projects (id, status, data, created_at, updated_at)VALUES ($1, $2, $3::jsonb, $4, $5)ON CONFLICT (id) DO NOTHING`,[project.id,- project.status || 'draft',+ mirrorStatus(project.status),JSON.stringify(project),- project.createdAt || new Date().toISOString(),- project.updatedAt || project.createdAt || new Date().toISOString(),+ createdAt,+ mirrorTimestamp(project.updatedAt, createdAt),],);if (result.rowCount > 0) imported += 1;diff --git a/server/scripts/migrateCreativeDirectorToDB.test.js b/server/scripts/migrateCreativeDirectorToDB.test.jsindex e85bbded3b..0ea1f79e01 100644--- a/server/scripts/migrateCreativeDirectorToDB.test.js+++ b/server/scripts/migrateCreativeDirectorToDB.test.js@@ -113,6 +113,24 @@ describe('migrateCreativeDirectorToDB', () => {expect(table.get('cd-1').data.runs).toHaveLength(350);});+ it('sanitizes malformed status/timestamp mirror columns without dropping the row', async () => {+ // A legacy record with a junk timestamp or over-long status must still+ // import (data verbatim) — the typed mirror columns get safe fallbacks so+ // the INSERT can't throw and block backend init on upgrade.+ files[LEGACY] = JSON.stringify([+ { id: 'cd-1', status: 'x'.repeat(80), createdAt: 'not-a-date', updatedAt: 12345, data: 'keep' },+ ]);+ const result = await migrateCreativeDirectorToDB();+ expect(result.imported).toBe(1);+ const inserted = query.mock.calls.find((c) => /INSERT/.test(c[0]));+ const [, status, , createdAt, updatedAt] = inserted[1];+ expect(status.length).toBeLessThanOrEqual(32);+ expect(Number.isNaN(Date.parse(createdAt))).toBe(false);+ expect(Number.isNaN(Date.parse(updatedAt))).toBe(false);+ // The full record (including the bad fields) is preserved verbatim in data.+ expect(table.get('cd-1').data.createdAt).toBe('not-a-date');+ });+it('does NOT stamp the marker when the legacy rename fails (retries next boot)', async () => {files[LEGACY] = JSON.stringify([{ id: 'cd-1', status: 'draft' }]);renameShouldFail = true;diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.jsindex 0c7095bf70..c78a29da74 100644--- a/server/services/creativeDirector/projectsDB.js+++ b/server/services/creativeDirector/projectsDB.js@@ -23,6 +23,8 @@ import { ServerError } from '../../lib/errorHandler.js';import { createCollection } from '../mediaCollections.js';import {trimRuns,+ mirrorStatus,+ mirrorTimestamp,buildProjectRecord,applyProjectPatch,applyTreatment,@@ -47,6 +49,11 @@ async function persist(exec, project) {// Cap runs[] at the single write chokepoint (mirrors the file backend's// saveAll) so legacy over-cap rows shrink on first write.if (Array.isArray(project.runs)) project.runs = trimRuns(project.runs);+ // `data` is written verbatim (lossless); the typed mirror columns are+ // sanitized so a malformed status/timestamp on a legacy record can't make+ // the INSERT throw (which, during boot init, would block the whole backend).+ const now = new Date().toISOString();+ const createdAt = mirrorTimestamp(project.createdAt, now);await exec(`INSERT INTO creative_director_projects (id, status, data, created_at, updated_at)VALUES ($1, $2, $3::jsonb, $4, $5)@@ -54,7 +61,13 @@ async function persist(exec, project) {status = EXCLUDED.status,data = EXCLUDED.data,updated_at = EXCLUDED.updated_at`,- [project.id, project.status, JSON.stringify(project), project.createdAt, project.updatedAt],+ [+ project.id,+ mirrorStatus(project.status),+ JSON.stringify(project),+ createdAt,+ mirrorTimestamp(project.updatedAt, createdAt),+ ],);return project;}diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 7aa047cfa5..60bfe344ca 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -51,6 +51,26 @@ export function trimRuns(runs) {return kept.reverse();}+// Postgres `status` column is VARCHAR(32) and created_at/updated_at are+// TIMESTAMPTZ. A legacy/hand-edited project with an over-long status or a+// malformed timestamp would make the INSERT throw — and because the PG backend+// inits (and imports) during boot, one bad record could block the whole backend+// from coming up. The JSONB `data` is always written verbatim (lossless); these+// helpers only sanitize the typed MIRROR columns so they can never reject a row+// the file backend would have tolerated as plain JSON.+const STATUS_COLUMN_MAX = 32;++/** Safe value for the `status` mirror column — bounded, never null. */+export function mirrorStatus(status) {+ return (typeof status === 'string' && status ? status : 'draft').slice(0, STATUS_COLUMN_MAX);+}++/** Safe ISO timestamp for a TIMESTAMPTZ mirror column, falling back to `now`. */+export function mirrorTimestamp(value, fallback) {+ if (typeof value === 'string' && !Number.isNaN(Date.parse(value))) return value;+ return fallback;+}+/*** Build a fresh project record. The caller supplies the already-created media* collection id (collection creation is a side effect both backends performdiff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.jsindex 5c71cc277d..10c24ac970 100644--- a/server/services/creativeDirector/projectsLogic.test.js+++ b/server/services/creativeDirector/projectsLogic.test.js@@ -8,6 +8,8 @@ import { describe, it, expect } from 'vitest';import {MAX_PERSISTED_RUNS,trimRuns,+ mirrorStatus,+ mirrorTimestamp,buildProjectRecord,applyProjectPatch,applyTreatment,@@ -112,6 +114,22 @@ describe('appendRun / applyRunUpdate', () => {});});+describe('mirrorStatus / mirrorTimestamp (typed-column safety)', () => {+ it('mirrorStatus bounds to 32 chars and falls back to draft', () => {+ expect(mirrorStatus('rendering')).toBe('rendering');+ expect(mirrorStatus('x'.repeat(80)).length).toBe(32);+ expect(mirrorStatus('')).toBe('draft');+ expect(mirrorStatus(null)).toBe('draft');+ expect(mirrorStatus(undefined)).toBe('draft');+ });+ it('mirrorTimestamp passes valid ISO through and falls back otherwise', () => {+ expect(mirrorTimestamp('2026-01-01T00:00:00.000Z', 'fb')).toBe('2026-01-01T00:00:00.000Z');+ expect(mirrorTimestamp('not-a-date', 'fb')).toBe('fb');+ expect(mirrorTimestamp(12345, 'fb')).toBe('fb');+ expect(mirrorTimestamp(null, 'fb')).toBe('fb');+ });+});+describe('trimRuns', () => {it('is a no-op under the cap', () => {const runs = [{ runId: 'a', status: 'completed' }];