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
fix: validate memory list/timeline query strings with their Zod schemas (#3867)
[._.]/ Adam Eivyac6f84a96029
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b173fd04df..4f2b5a641f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -38,3 +38,4 @@- The remaining trigger-anchored dropdowns — "Run on App" on a scheduled task, and the Share and Sync buttons on series and universe cards — now use the same shared popover-positioning hook as the notification panel. "Run on App" opened a panel pinned to its button's left edge that merely got narrower on a phone rather than moving, so it ran off the right edge; the Share and Sync menus always opened downward even with no room below. All three now clamp into the viewport, flip when there is no room, and stay attached to their button as the page scrolls.- The theme switcher, the media collection picker, and the Shell photo composer now dismiss through the shared click-outside hook instead of three private copies of the same two-ref check, so the rule that a portaled panel counts as "inside" its own trigger lives in one place. Escape still closes each of them.- Collapsible section headers in the canon cards, the character detail editor, and the digital-twin interview analysis card now announce their open/closed state to a screen reader. They were five separate hand-rolled copies of the same header, none of which reported that state, and all five now share one primitive so a layout fix lands in one place instead of three.+- The memory list and timeline endpoints now validate their query strings against the Zod schemas that were written for them. Both handlers had been hand-parsing `req.query`, so the declared bounds went unenforced: an unknown memory type, a garbled `limit`, or a nonsense date range was quietly accepted and passed to the database. Both schemas now also accept the comma-separated, string-valued form a query string actually arrives in, and the list `limit` ceiling is 500 — the bound the route has always enforced in practice — rather than the 100 its schema claimed.diff --git a/server/lib/memoryValidation.js b/server/lib/memoryValidation.jsindex 6c21a323b9..7a62175927 100644--- a/server/lib/memoryValidation.js+++ b/server/lib/memoryValidation.js@@ -74,25 +74,64 @@ export const memorySearchSchema = z.object({offset: z.number().int().min(0).optional().default(0)});-// List/filter query schema+// ---------------------------------------------------------------------------+// Query-string coercion+//+// The list/timeline schemas below validate `req.query`, where every value+// arrives as a string: arrays are comma-separated (`?types=fact,learning`, the+// shape `client/src/services/apiMemory.js` sends) and numbers are digits. These+// preprocessors accept both the query form and the already-parsed form so the+// same schema still validates a JSON body. An empty param (`?types=`) becomes+// `undefined` — "not filtered" — rather than an empty list or a NaN.+// ---------------------------------------------------------------------------++const csvList = (inner) => z.preprocess((v) => {+ if (typeof v !== 'string') return v;+ const parts = v.split(',').map((s) => s.trim()).filter(Boolean);+ return parts.length > 0 ? parts : undefined;+}, inner);++const numeric = (inner) => z.preprocess((v) => {+ if (typeof v !== 'string') return v;+ const trimmed = v.trim();+ if (trimmed === '') return undefined;+ const parsed = Number(trimmed);+ return Number.isFinite(parsed) ? parsed : v;+}, inner);++const emptyToUndefined = (inner) => z.preprocess(+ (v) => (typeof v === 'string' && v.trim() === '' ? undefined : v),+ inner+);++// `startDate`/`endDate` reach Postgres as `created_at >= $n` bind params, so a+// bare calendar date is as usable as a full timestamp — accept either.+const dateBoundary = z.union([+ z.string().datetime(),+ z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'must be an ISO datetime or YYYY-MM-DD date')+]);++// List/filter query schema (GET /api/memory — validated against req.query).+// `limit` caps at 500 to match the timeline schema and the ceiling this route+// has always enforced via parsePagination's maxLimit.export const memoryListSchema = z.object({- types: z.array(memoryTypeEnum).optional(),- categories: z.array(z.string()).optional(),- tags: z.array(z.string()).optional(),- status: memoryStatusEnum.optional().default('active'),- appId: z.string().max(100).optional(),- limit: z.number().int().min(1).max(100).optional().default(50),- offset: z.number().int().min(0).optional().default(0),- sortBy: z.enum(['createdAt', 'updatedAt', 'importance', 'accessCount']).optional().default('createdAt'),- sortOrder: z.enum(['asc', 'desc']).optional().default('desc')+ types: csvList(z.array(memoryTypeEnum).optional()),+ categories: csvList(z.array(z.string()).optional()),+ tags: csvList(z.array(z.string()).optional()),+ status: emptyToUndefined(memoryStatusEnum.optional().default('active')),+ appId: emptyToUndefined(z.string().max(100).optional()),+ limit: numeric(z.number().int().min(1).max(500).optional().default(50)),+ offset: numeric(z.number().int().min(0).optional().default(0)),+ sortBy: emptyToUndefined(z.enum(['createdAt', 'updatedAt', 'importance', 'accessCount']).optional().default('createdAt')),+ sortOrder: emptyToUndefined(z.enum(['asc', 'desc']).optional().default('desc'))});-// Timeline query schema+// Timeline query schema (GET /api/memory/timeline — validated against req.query)export const memoryTimelineSchema = z.object({- startDate: z.string().datetime().optional(),- endDate: z.string().datetime().optional(),- types: z.array(memoryTypeEnum).optional(),- limit: z.number().int().min(1).max(500).optional().default(100)+ startDate: emptyToUndefined(dateBoundary.optional()),+ endDate: emptyToUndefined(dateBoundary.optional()),+ types: csvList(z.array(memoryTypeEnum).optional()),+ limit: numeric(z.number().int().min(1).max(500).optional().default(100))});// Memory extraction request schema (from agent output)diff --git a/server/lib/memoryValidation.test.js b/server/lib/memoryValidation.test.jsindex af94793dfb..8aa4cd2e47 100644--- a/server/lib/memoryValidation.test.js+++ b/server/lib/memoryValidation.test.js@@ -307,6 +307,51 @@ describe('memoryValidation.js', () => {it('should reject invalid sortOrder', () => {expect(memoryListSchema.safeParse({ sortOrder: 'random' }).success).toBe(false);});++ it('should coerce query-string values', () => {+ const result = memoryListSchema.safeParse({+ types: 'fact,learning',+ categories: 'codebase, workflow',+ tags: 'a,b',+ limit: '25',+ offset: '10'+ });+ expect(result.success).toBe(true);+ expect(result.data.types).toEqual(['fact', 'learning']);+ expect(result.data.categories).toEqual(['codebase', 'workflow']);+ expect(result.data.tags).toEqual(['a', 'b']);+ expect(result.data.limit).toBe(25);+ expect(result.data.offset).toBe(10);+ });++ it('should treat empty query params as unset', () => {+ const result = memoryListSchema.safeParse({+ types: '', categories: '', tags: '', status: '', appId: '', limit: '', offset: '', sortBy: '', sortOrder: ''+ });+ expect(result.success).toBe(true);+ expect(result.data.types).toBeUndefined();+ expect(result.data.appId).toBeUndefined();+ expect(result.data.status).toBe('active');+ expect(result.data.limit).toBe(50);+ expect(result.data.sortBy).toBe('createdAt');+ });++ it('should reject a non-numeric limit', () => {+ expect(memoryListSchema.safeParse({ limit: 'abc' }).success).toBe(false);+ });++ it('should reject limit over 500', () => {+ expect(memoryListSchema.safeParse({ limit: 501 }).success).toBe(false);+ expect(memoryListSchema.safeParse({ limit: '501' }).success).toBe(false);+ });++ it('should accept limit at the 500 ceiling', () => {+ expect(memoryListSchema.safeParse({ limit: '500' }).data.limit).toBe(500);+ });++ it('should reject an unknown memory type in the csv list', () => {+ expect(memoryListSchema.safeParse({ types: 'fact,nonsense' }).success).toBe(false);+ });});describe('memoryTimelineSchema', () => {@@ -329,6 +374,23 @@ describe('memoryValidation.js', () => {it('should reject limit over 500', () => {expect(memoryTimelineSchema.safeParse({ limit: 501 }).success).toBe(false);});++ it('should coerce query-string values', () => {+ const result = memoryTimelineSchema.safeParse({ types: 'fact', limit: '7' });+ expect(result.success).toBe(true);+ expect(result.data.types).toEqual(['fact']);+ expect(result.data.limit).toBe(7);+ });++ it('should accept a bare calendar date boundary', () => {+ const result = memoryTimelineSchema.safeParse({ startDate: '2026-01-01', endDate: '2026-01-31' });+ expect(result.success).toBe(true);+ expect(result.data.startDate).toBe('2026-01-01');+ });++ it('should reject a malformed date boundary', () => {+ expect(memoryTimelineSchema.safeParse({ startDate: 'last tuesday' }).success).toBe(false);+ });});describe('memoryExtractSchema', () => {diff --git a/server/routes/memory.js b/server/routes/memory.jsindex 04092b907c..7133c46e96 100644--- a/server/routes/memory.js+++ b/server/routes/memory.js@@ -25,18 +25,7 @@ const router = Router();// GET /api/memory - List memories with filtersrouter.get('/', asyncHandler(async (req, res) => {- const { limit, offset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 500 });- const options = {- types: req.query.types ? req.query.types.split(',') : undefined,- categories: req.query.categories ? req.query.categories.split(',') : undefined,- tags: req.query.tags ? req.query.tags.split(',') : undefined,- status: req.query.status || 'active',- appId: req.query.appId || undefined,- limit,- offset,- sortBy: req.query.sortBy || 'createdAt',- sortOrder: req.query.sortOrder || 'desc'- };+ const options = validateRequest(memoryListSchema, req.query);const result = await memory.getMemories(options);res.json(result);@@ -62,13 +51,7 @@ router.get('/tags', asyncHandler(async (req, res) => {// GET /api/memory/timeline - Get timeline viewrouter.get('/timeline', asyncHandler(async (req, res) => {- const { limit } = parsePagination(req.query, { defaultLimit: 100, maxLimit: 500 });- const options = {- startDate: req.query.startDate,- endDate: req.query.endDate,- types: req.query.types ? req.query.types.split(',') : undefined,- limit- };+ const options = validateRequest(memoryTimelineSchema, req.query);const timeline = await memory.getTimeline(options);res.json(timeline);diff --git a/server/routes/memory.test.js b/server/routes/memory.test.jsindex 0b3509997e..7d7a307f82 100644--- a/server/routes/memory.test.js+++ b/server/routes/memory.test.js@@ -45,7 +45,7 @@ vi.mock('../services/memorySync.js', () => ({applyRemoteChanges: vi.fn()}));-import { ensureBackend } from '../services/memoryBackend.js';+import { ensureBackend, getMemories, getTimeline } from '../services/memoryBackend.js';import { checkHealth } from '../lib/db.js';import * as memorySync from '../services/memorySync.js';@@ -205,4 +205,112 @@ describe('Memory Routes', () => {);});});++ // ===========================================================================+ // LIST+ // ===========================================================================++ describe('GET /api/memory', () => {+ it('should pass schema defaults through when no filters are given', async () => {+ getMemories.mockResolvedValue({ memories: [], total: 0 });++ const response = await request(app).get('/api/memory');++ expect(response.status).toBe(200);+ expect(getMemories).toHaveBeenCalledWith({+ status: 'active',+ limit: 50,+ offset: 0,+ sortBy: 'createdAt',+ sortOrder: 'desc'+ });+ });++ it('should split csv filters and coerce numeric params', async () => {+ getMemories.mockResolvedValue({ memories: [], total: 0 });++ const response = await request(app)+ .get('/api/memory?types=fact,learning&categories=codebase&tags=a,b&status=archived&appId=brain&limit=10&offset=5&sortBy=importance&sortOrder=asc');++ expect(response.status).toBe(200);+ expect(getMemories).toHaveBeenCalledWith({+ types: ['fact', 'learning'],+ categories: ['codebase'],+ tags: ['a', 'b'],+ status: 'archived',+ appId: 'brain',+ limit: 10,+ offset: 5,+ sortBy: 'importance',+ sortOrder: 'asc'+ });+ });++ it('should reject a limit above the 500 ceiling', async () => {+ const response = await request(app).get('/api/memory?limit=501');++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/Validation failed/);+ expect(getMemories).not.toHaveBeenCalled();+ });++ it('should reject an unknown memory type', async () => {+ const response = await request(app).get('/api/memory?types=fact,nonsense');++ expect(response.status).toBe(400);+ expect(getMemories).not.toHaveBeenCalled();+ });++ it('should reject a non-numeric limit instead of silently defaulting', async () => {+ const response = await request(app).get('/api/memory?limit=abc');++ expect(response.status).toBe(400);+ expect(getMemories).not.toHaveBeenCalled();+ });+ });++ // ===========================================================================+ // TIMELINE+ // ===========================================================================++ describe('GET /api/memory/timeline', () => {+ it('should pass the default limit through', async () => {+ getTimeline.mockResolvedValue({});++ const response = await request(app).get('/api/memory/timeline');++ expect(response.status).toBe(200);+ expect(getTimeline).toHaveBeenCalledWith({ limit: 100 });+ });++ it('should pass validated date range, types and limit', async () => {+ getTimeline.mockResolvedValue({});++ const response = await request(app)+ .get('/api/memory/timeline?startDate=2026-01-01T00:00:00.000Z&endDate=2026-01-31&types=fact&limit=5');++ expect(response.status).toBe(200);+ expect(getTimeline).toHaveBeenCalledWith({+ startDate: '2026-01-01T00:00:00.000Z',+ endDate: '2026-01-31',+ types: ['fact'],+ limit: 5+ });+ });++ it('should reject a malformed date boundary', async () => {+ const response = await request(app).get('/api/memory/timeline?startDate=yesterday');++ expect(response.status).toBe(400);+ expect(response.body.error).toMatch(/Validation failed/);+ expect(getTimeline).not.toHaveBeenCalled();+ });++ it('should reject a limit above the 500 ceiling', async () => {+ const response = await request(app).get('/api/memory/timeline?limit=501');++ expect(response.status).toBe(400);+ expect(getTimeline).not.toHaveBeenCalled();+ });+ });});