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

fix: return 400 VALIDATION_ERROR instead of 500 for schema failures in five routes (#9606)

Adam Eivy396b59080d6b
diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.js
index ea3f10b382..ec1a0878e4 100644
--- a/server/lib/errorHandler.js
+++ b/server/lib/errorHandler.js
@@ -293,6 +293,16 @@ export function normalizeError(err) {
return err;
}
+ // Backstop: a raw schema `.parse()` that escaped a route is a client error,
+ // not a server crash. Routes should still use validateRequest().
+ if (err?.name === 'ZodError' && Array.isArray(err.issues)) {
+ return new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: err.issues.map(i => ({ path: i.path.join('.'), message: i.message })) }
+ });
+ }
+
if (err instanceof Error) {
const status = err.status || 500;
const code = err.code || getErrorCode(status);
diff --git a/server/lib/errorHandler.test.js b/server/lib/errorHandler.test.js
index 5fda203548..8b011190e1 100644
--- a/server/lib/errorHandler.test.js
+++ b/server/lib/errorHandler.test.js
@@ -138,6 +138,15 @@ describe('errorHandler.js', () => {
expect(normalized.originalMessage).toContain('/private/install/data/example.json');
});
+ it('maps a raw ZodError to a 400 VALIDATION_ERROR', async () => {
+ const { z } = await import('zod');
+ const parsed = z.object({ a: z.string() }).safeParse({});
+ const normalized = normalizeError(parsed.error);
+ expect(normalized.status).toBe(400);
+ expect(normalized.code).toBe('VALIDATION_ERROR');
+ expect(normalized.context.details[0].path).toBe('a');
+ });
+
it('should convert string to ServerError', () => {
const normalized = normalizeError('String error');
expect(normalized instanceof ServerError).toBe(true);
diff --git a/server/routes/apps/documents.js b/server/routes/apps/documents.js
index b061cd2012..272614bcf7 100644
--- a/server/routes/apps/documents.js
+++ b/server/routes/apps/documents.js
@@ -18,7 +18,7 @@ import { dirname, join } from 'path';
import { atomicWrite, listDirectoryByExtension } from '../../lib/fileUtils.js';
import { isGitStageableFilePath } from '../../lib/gitArgs.js';
import { isPathInsideDir, isSafeFilename, isTopLevelEntryName } from '../../lib/pathSafety.js';
-import { documentUpdateSchema } from '../../lib/validation.js';
+import { documentUpdateSchema, validateRequest } from '../../lib/validation.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
import * as git from '../../services/git.js';
import { loadApp, pathExists } from './shared.js';
@@ -190,7 +190,7 @@ router.put('/:id/documents/*docPath', loadApp, asyncHandler(async (req, res) =>
});
}
- const { content, commitMessage } = documentUpdateSchema.parse(req.body);
+ const { content, commitMessage } = validateRequest(documentUpdateSchema, req.body);
const created = !await pathExists(resolved);
await atomicWrite(resolved, content);
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.js
index 0d67491237..86e889c2e9 100644
--- a/server/routes/dataSync.js
+++ b/server/routes/dataSync.js
@@ -42,6 +42,7 @@ import { sweepTombstones, getSweepStatus, TOMBSTONE_GRACE_MS } from '../services
import { authorizePeerPull } from '../services/sharing/peerPullAuthorization.js';
import { MAX_MANIFEST_SLOTS } from '../lib/syncManifest.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
const router = Router();
@@ -130,7 +131,7 @@ const slotsOf = (req) => {
// 404 an older peer returns for the whole route) as "no manifest" and falls
// back to the whole snapshot.
router.get('/:category/manifest', asyncHandler(async (req, res) => {
- const category = categoryParam.parse(req.params.category);
+ const category = validateRequest(categoryParam, req.params.category);
// Same gate as the other two reads — a manifest is a fingerprint of the same
// payload, so it must never become the weaker door.
await authorizeSyncPull(req, category);
@@ -141,7 +142,7 @@ router.get('/:category/manifest', asyncHandler(async (req, res) => {
// GET /api/sync/:category/checksum — return checksum only (lightweight)
router.get('/:category/checksum', asyncHandler(async (req, res) => {
- const category = categoryParam.parse(req.params.category);
+ const category = validateRequest(categoryParam, req.params.category);
await authorizeSyncPull(req, category);
const result = await dataSync.getChecksum(category, { forPeerId: forPeerOf(req) });
if (!result) throw new ServerError('Category not found', { status: 404 });
@@ -150,7 +151,7 @@ router.get('/:category/checksum', asyncHandler(async (req, res) => {
// GET /api/sync/:category/snapshot — return category data + checksum
router.get('/:category/snapshot', asyncHandler(async (req, res) => {
- const category = categoryParam.parse(req.params.category);
+ const category = validateRequest(categoryParam, req.params.category);
await authorizeSyncPull(req, category);
const snapshot = await dataSync.getSnapshot(category, { forPeerId: forPeerOf(req), slots: slotsOf(req) });
if (!snapshot) throw new ServerError('Category not found', { status: 404 });
@@ -173,7 +174,7 @@ const applyBodySchema = z.object({
}).passthrough().optional(),
});
router.post('/:category/apply', asyncHandler(async (req, res) => {
- const category = categoryParam.parse(req.params.category);
+ const category = validateRequest(categoryParam, req.params.category);
const parsed = applyBodySchema.safeParse(req.body || {});
if (!parsed.success) {
throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });
diff --git a/server/routes/gsd.js b/server/routes/gsd.js
index eb40f2cc4e..e2c7bdf14e 100644
--- a/server/routes/gsd.js
+++ b/server/routes/gsd.js
@@ -12,7 +12,7 @@ import { readFile } from 'fs/promises'
import { join, resolve } from 'path'
import { asyncHandler, ServerError } from '../lib/errorHandler.js'
import { atomicWrite } from '../lib/fileUtils.js'
-import { documentUpdateSchema } from '../lib/validation.js'
+import { documentUpdateSchema, validateRequest } from '../lib/validation.js'
import * as gsdService from '../services/gsdService.js'
import { addTask } from '../services/cos.js'
import { getActiveApps } from '../services/apps.js'
@@ -102,7 +102,7 @@ router.get('/projects/:appId/phases/:phaseId', asyncHandler(async (req, res) =>
// POST /projects/:appId/concerns/tasks — create CoS tasks from selected concerns
router.post('/projects/:appId/concerns/tasks', asyncHandler(async (req, res) => {
- const body = concernIdsSchema.parse(req.body)
+ const body = validateRequest(concernIdsSchema, req.body)
const allTasks = await gsdService.generateConcernTasks(req.params.appId)
if (allTasks.length === 0) {
@@ -125,7 +125,7 @@ router.post('/projects/:appId/concerns/tasks', asyncHandler(async (req, res) =>
// POST /projects/:appId/phases/:phaseId/action — trigger plan/execute/verify as CoS task
router.post('/projects/:appId/phases/:phaseId/action', asyncHandler(async (req, res) => {
- const { action } = phaseActionSchema.parse(req.body)
+ const { action } = validateRequest(phaseActionSchema, req.body)
const { appId, phaseId } = req.params
const project = await gsdService.getGsdProject(appId)
@@ -194,7 +194,7 @@ router.put('/projects/:appId/documents/:docName', asyncHandler(async (req, res)
throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' })
}
- const { content, commitMessage } = documentUpdateSchema.parse(req.body)
+ const { content, commitMessage } = validateRequest(documentUpdateSchema, req.body)
const created = !existsSync(resolved)
await atomicWrite(resolved, content)
diff --git a/server/routes/instances.js b/server/routes/instances.js
index fce68095f7..6f3151a973 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -175,7 +175,7 @@ const syncStatusQuerySchema = z.object({
)
});
router.get('/sync-status', asyncHandler(async (req, res) => {
- const { forPeer } = syncStatusQuerySchema.parse(req.query);
+ const { forPeer } = validateRequest(syncStatusQuerySchema, req.query);
const status = await getSyncStatus({ includeChecksums: true, forPeer });
res.json({
brainSeq: status.local.brainSeq,
@@ -228,7 +228,7 @@ const updateSelfSchema = z.object({
message: 'Provide name and/or defaultPeerFullSync'
});
router.put('/self', asyncHandler(async (req, res) => {
- const data = updateSelfSchema.parse(req.body);
+ const data = validateRequest(updateSelfSchema, req.body);
const updated = await updateSelf(data.name, { defaultPeerFullSync: data.defaultPeerFullSync });
if (!updated) throw new ServerError('Self identity not initialized', { status: 500 });
res.json(updated);
@@ -236,7 +236,7 @@ router.put('/self', asyncHandler(async (req, res) => {
// POST /api/instances/peers/announce — receive announcement from remote peer
router.post('/peers/announce', asyncHandler(async (req, res) => {
- const data = announceSchema.parse(req.body);
+ const data = validateRequest(announceSchema, req.body);
// Derive caller IP from req.ip, stripping ::ffff: prefix for IPv4-mapped addresses
const rawIp = req.ip || req.socket.remoteAddress || '';
const address = rawIp.replace(/^::ffff:/, '');
@@ -487,7 +487,7 @@ router.get('/peers/:id/full-sync-coverage', asyncHandler(async (req, res) => {
// GET /api/instances/peers/:id/query — proxy GET to peer
router.get('/peers/:id/query', asyncHandler(async (req, res) => {
- const { path } = querySchema.parse(req.query);
+ const { path } = validateRequest(querySchema, req.query);
const result = await instances.queryPeer(req.params.id, path);
if (result.error) throw new ServerError(result.error, { status: 502 });
res.json(result.data);
diff --git a/server/routes/media.js b/server/routes/media.js
index 2a8ff7a564..ee16f18b73 100644
--- a/server/routes/media.js
+++ b/server/routes/media.js
@@ -2,6 +2,7 @@ import express from 'express';
import { z } from 'zod';
import mediaService from '../services/mediaService.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
const router = express.Router();
@@ -29,7 +30,7 @@ router.get('/status', (req, res) => {
// Start media streaming
router.post('/start', asyncHandler(async (req, res) => {
- const { videoDeviceId = '0', audioDeviceId = '0', video = true, audio = true } = startMediaSchema.parse(req.body);
+ const { videoDeviceId = '0', audioDeviceId = '0', video = true, audio = true } = validateRequest(startMediaSchema, req.body);
if (video) {
mediaService.startVideoStream(videoDeviceId);