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
feat: guard POST/PUT/PATCH routes against unvalidated req.body and burn down 37 offenders (#9950)
Adam Eivy4ee4d66924af
diff --git a/server/AGENTS.md b/server/AGENTS.mdindex 68011e4f0e..706594d7af 100644--- a/server/AGENTS.md+++ b/server/AGENTS.md@@ -6,6 +6,8 @@ These apply to Express/service/model code. Universal constraints (no try/catch o- **Schema parity when adding fields.** When you add a field to a sanitizer, `createXxx`, or a payload shape, update the corresponding Zod schema (`server/lib/aiToolkit/validation.js` for toolkit shapes, `server/lib/validation.js` for PortOS routes) in the same change. Wire validation into POST and PUT (PUT can use `schema.partial()`); the PortOS convention is *all* inputs validated — an exported-but-unwired sub-schema creates false confidence. For polymorphic stores like `PUT /api/settings` that accept any sub-object, validate the relevant slice with `schema.partial()` when its key is present in the request body (see `server/routes/settings.js` for the `backupConfigSchema.partial()` pattern). Tolerate UI sentinels (`endpoint: ''` for CLI providers) with `z.preprocess(v => v === '' ? undefined : v, …)`. When a service migrates legacy keys on read, the schema must still accept the legacy shape so older clients don't 400 before the migration runs.+- **A POST/PUT/PATCH handler that reads `req.body` must validate it with a schema.** `validateRequest(schema, req.body ?? {})` is the default; put the schema in `server/lib/validation.js` (or the domain's `*Validation.js`). A hand-rolled `if (!path) throw …` lets a wrong-typed field reach the service layer. `server/routeValidationConventions.test.js` scans `server/routes/` for this; its `ALLOWED_UNVALIDATED` list (raw-binary and multipart-upload bodies, each with a reason) may only shrink — the test fails when an entry is compliant or gone. Do not add a JSON-body handler to it (#9950).+## Offering models vs running them- **A caller that OFFERS a model choice reads providers through `getSelectableProviders()` / `listSelectableProviders()`; a caller that EXECUTES, ACCOUNTS or WRITES reads `getAllProviders()` / `listProviders()`.** The scoped pair narrows each record's `models` to the install's declared entitlement — which of a vendor's advertised catalog this account can actually run, a thing no `/models` response reports (see `docs/MODEL_ACCESS.md` and `lib/aiToolkit/internal/modelAccess.js`). Picking the wrong one is silent both ways: a picker on the unscoped list offers models the account cannot run, and a *write* path on the scoped list persists a truncated catalog over the real one, which no refresh restores until the policy is cleared. Two methods rather than a flag, because the answer is a property of the caller's purpose and has to be visible at the call site. Route payloads shaped by `presentProvider` are already scoped; anything reading the service directly is not.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex fbf1ff052f..ee7fad67bc 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2666,3 +2666,85 @@ export const jiraTicketKeySchema = z.string().max(64).regex(/^([A-Za-z][A-Za-z0-// variables.json key, so they must be a single safe path segment (#9152).export const promptStageNameSchema = z.string().regex(/^[a-z0-9][a-z0-9_-]*$/, 'invalid stage name').max(80);export const promptVariableKeySchema = z.string().regex(/^[A-Za-z0-9_-]+$/, 'invalid variable key').max(80);++// =============================================================================+// ROUTE BODY SCHEMAS (#9950) — handlers that used to read `req.body` by hand.+// `routeValidationConventions.test.js` fails any body-bearing POST/PUT/PATCH+// handler that skips `validateRequest`. A bodyless POST (a bare "run now"+// button) still parses an optional-field object: pass `req.body ?? {}`.+// =============================================================================++const nonEmptyString = z.string().min(1);+const optionalString = z.string().optional();+const nullishString = z.string().nullish();++// Project detection (routes/detect.js)+export const detectRepoBodySchema = z.object({ path: nonEmptyString });+export const detectPortBodySchema = z.object({ port: z.coerce.number().int().min(1).max(65535) });+export const detectPm2BodySchema = z.object({ name: nonEmptyString });+export const detectAiBodySchema = z.object({ path: nonEmptyString, providerId: nullishString });++// Messages (routes/messages.js)+export const MESSAGE_TOKEN_PROVIDERS = ['outlook', 'teams'];+export const messageSyncBodySchema = z.object({ mode: z.enum(['unread', 'full']).optional() });+export const messageFetchFullBodySchema = z.object({ force: z.boolean().default(false) });+export const messageActionBodySchema = z.object({ action: z.enum(['archive', 'delete']) });+export const messageTokenProviderBodySchema = z.object({ provider: z.enum(MESSAGE_TOKEN_PROVIDERS).optional() });++// CoS agents / tasks / schedule+export const cosAgentFeedbackBodySchema = z.object({+ rating: z.enum(['positive', 'negative', 'neutral']),+ comment: nullishString,+});+export const cosAgentBtwBodySchema = z.object({ message: z.string().trim().min(1).max(5000) });+export const cosTaskReorderBodySchema = z.object({ taskIds: z.array(nonEmptyString) });+export const cosScheduleTargetBodySchema = z.object({ taskType: nonEmptyString, appId: nullishString });++// Per-app task-type overrides (routes/apps/taskTypes.js)+export const appTaskTypeToggleBodySchema = z.object({ enabled: z.boolean() });+export const appTaskTypeOverrideBodySchema = z.object({+ enabled: z.boolean().optional(),+ interval: nullishString,+ intervalMs: z.number().positive().finite().nullish(),+ providerId: nullishString,+ model: nullishString,+ taskMetadata: z.record(z.string(), z.unknown()).nullish(),+}).refine((body) => Object.values(body).some((value) => value !== undefined), {+ message: 'enabled (boolean), interval (string|null), intervalMs (number|null), providerId (string|null), model (string|null), or taskMetadata (object|null) required',+});++// Brain journal / inbox+export const brainInboxRetryBodySchema = z.object({ providerOverride: nullishString, modelOverride: nullishString });+export const brainJournalAppendBodySchema = z.object({+ text: z.string().refine((text) => text.trim().length > 0, 'text is required'),+ source: nullishString,+});+export const brainJournalReplaceBodySchema = z.object({ content: z.string(), ifMatchUpdatedAt: nullishString });++// Prompts (routes/prompts.js)+export const promptVariableUpdateBodySchema = z.object({ name: optionalString, category: optionalString, content: optionalString });+export const promptJobSkillBodySchema = z.object({ content: nonEmptyString });+export const promptPreviewBodySchema = z.object({ testData: z.record(z.string(), z.unknown()).default({}) });++// Smaller single-purpose bodies+export const calendarAutoConfigureBodySchema = z.object({ email: optionalString });+export const commandExecuteBodySchema = z.object({ command: nonEmptyString, workspacePath: nullishString });+export const dataArchiveBodySchema = z.object({+ daysToKeep: z.preprocess((value) => (value == null ? undefined : value), z.coerce.number().finite().min(0).optional()),+});+export const imageVisibilityBodySchema = z.object({ hidden: z.boolean().default(false) });+export const moltworldQueueFailBodySchema = z.object({ error: nullishString });+export const referenceRepoReviewedBodySchema = z.object({ sha: z.string().trim().default('') });+export const scaffoldTemplateCreateBodySchema = z.object({ templateId: nonEmptyString, name: nonEmptyString, targetPath: nonEmptyString });+export const screenshotUploadBodySchema = z.object({ data: nonEmptyString, filename: nullishString });+export const standardizeTargetBodySchema = z.object({ repoPath: nullishString, appId: nullishString, providerId: nullishString });+export const systemHealthThresholdsBodySchema = z.object({+ memoryWarn: z.coerce.number().finite(),+ memoryCritical: z.coerce.number().finite(),+ diskWarn: z.coerce.number().finite(),+ diskCritical: z.coerce.number().finite(),+});+export const voicePiperFetchBodySchema = z.object({ voice: nonEmptyString });+export const writersRoomSceneImageBodySchema = z.object({+ sceneId: nullishString, filename: nullishString, jobId: nullishString, prompt: nullishString,+});diff --git a/server/routeValidationConventions.test.js b/server/routeValidationConventions.test.jsnew file mode 100644index 0000000000..05fc256ccc--- /dev/null+++ b/server/routeValidationConventions.test.js@@ -0,0 +1,152 @@+/**+ * Repo-wide guard: a body-bearing route handler must validate `req.body`.+ *+ * Root `AGENTS.md` says every route input is validated through+ * `lib/validation.js`, but a hand-rolled `if (!path) throw …` is easy to write+ * and nothing noticed (#9950): ~50 POST/PUT/PATCH handlers read `req.body` with+ * no schema, so a wrong-typed field (`path: {}`, `enabled: "yes"`) reached the+ * service layer instead of bouncing as a 400.+ *+ * ## The rule+ *+ * Every `router.post|put|patch(…)` call under `server/routes/` whose handler+ * text mentions `req.body` must also contain one of+ *+ * - `validateRequest(schema, …)` (the default — throws the 400),+ * - `validate(schema, …)` (the non-throwing sibling providers/social routes use), or+ * - `<name>Schema….safeParse(…)` / `<name>Schema….parse(…)`.+ *+ * ## Allowlist+ *+ * `ALLOWED_UNVALIDATED` holds the handlers that are exempt, each with a+ * one-line reason. It may only SHRINK: the test fails when an entry names a+ * handler that no longer exists or now validates, so a fixed handler is pruned+ * here in the same change. A genuinely new violation is a bug to fix with a+ * schema in `lib/validation.js`, not an entry to add.+ *+ * ## What this guard CANNOT see+ *+ * It is a lexer-assisted source scan (`lib/sourceScan.js`), not an AST pass.+ * It cannot tell WHICH value a `validateRequest(…)` call validates, so a handler+ * that validates `req.params` and reads `req.body` raw reads as compliant; it+ * does not follow a handler delegated to a named function declared elsewhere;+ * and it only sees `router.<verb>(…)` call sites (not `router.route(…).post`).+ * Out of scope on purpose: `lib/aiToolkit/routes/` (the vendored toolkit is+ * self-contained and cannot import `lib/validation.js`) and `cos-runner/` (a+ * separate process with its own spawn API). `req.query` reads are a follow-up+ * rule once this body list is empty.+ */++import { describe, it, expect } from 'vitest';+import { execFileSync } from 'child_process';+import { readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { blankLiterals, matchBracket } from './lib/sourceScan.js';++const SERVER_ROOT = dirname(fileURLToPath(import.meta.url));++// Key: `<file> <VERB> <path>` — the declaring file plus the handler's semantic+// identity, never a line number, so unrelated edits above it do not churn the list.+const ALLOWED_UNVALIDATED = new Map([+ ['routes/brainImport.js POST /chatgpt/zip', 'multipart upload: req.body only carries optional text fields beside the ZIP'],+ ['routes/federatedMedia.js POST /assets', 'raw binary body (express.raw); authenticated and byte-validated by storeFederatedMediaAsset'],+ ['routes/imageTo3d.js POST /models/:id/usdz', 'raw binary body (express.raw); validated by byte checks (non-empty, size cap, zip magic)'],+ ['routes/pipeline/audio.js POST /issues/:id/stages/audio/music/upload', 'multipart upload: req.body only carries an optional label text field'],+]);++const ROUTE_CALL = /\b(?:router|[A-Za-z]*Router)\.(post|put|patch)\s*\(/g;+const READS_BODY = /\breq\.body\b/;+const VALIDATES = /\bvalidateRequest\s*\(|\bvalidate\s*\(|\.safeParse\s*\(|[Ss]chema\w*\.parse\s*\(/;++/** `<VERB> <path>` for every handler in one file's source that reads `req.body` without validating it. */+export function findUnvalidatedBodyHandlers(src) {+ const blanked = blankLiterals(src);+ const hits = [];+ for (const match of blanked.matchAll(ROUTE_CALL)) {+ const open = match.index + match[0].length - 1;+ const end = matchBracket(blanked, open);+ if (end === -1) continue;+ const text = blanked.slice(open, end);+ if (!READS_BODY.test(text) || VALIDATES.test(text)) continue;+ // `blankLiterals` keeps offsets, so the path literal is read from the real source.+ const routePath = /^\(\s*(['"`])(.*?)\1/.exec(src.slice(open, end))?.[2] ?? '<dynamic>';+ hits.push(`${match[1].toUpperCase()} ${routePath}`);+ }+ return hits;+}++const trackedRouteSources = () => execFileSync('git', ['ls-files', 'routes'], {+ cwd: SERVER_ROOT,+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+}).split('\n').filter((f) => f.endsWith('.js') && !f.includes('.test.'));++const scanTree = () => trackedRouteSources().flatMap((file) => (+ findUnvalidatedBodyHandlers(readFileSync(join(SERVER_ROOT, file), 'utf8')).map((hit) => `${file} ${hit}`)+));++describe('route handlers validate req.body (#9950)', () => {+ it('scans the route tree', () => {+ // A broken `git ls-files` would otherwise let the assertions below pass by scanning nothing.+ expect(trackedRouteSources().length).toBeGreaterThan(100);+ });++ it('has no unvalidated req.body read outside the allowlist', () => {+ const offenders = scanTree().filter((key) => !ALLOWED_UNVALIDATED.has(key));+ expect(+ offenders,+ 'These POST/PUT/PATCH handlers read `req.body` with no schema. Add a Zod schema to '+ + '`lib/validation.js` and call `validateRequest(schema, req.body)` (root AGENTS.md: '+ + 'all route inputs are validated). Do NOT add an allowlist entry for a JSON body.\n'+ + `Offenders:\n ${offenders.join('\n ')}`,+ ).toEqual([]);+ });++ it('only allowlists handlers that still exist and are still unvalidated', () => {+ const live = new Set(scanTree());+ const stale = [...ALLOWED_UNVALIDATED.keys()].filter((key) => !live.has(key));+ expect(+ stale,+ `These allowlist entries are compliant or gone — delete them from ALLOWED_UNVALIDATED:\n ${stale.join('\n ')}`,+ ).toEqual([]);+ for (const reason of ALLOWED_UNVALIDATED.values()) expect(reason.length).toBeGreaterThan(10);+ });+});++// Guards the guard: if the recognizer stops seeing the broken shape, the scan+// above goes green and the bug class walks straight back in.+describe('the unvalidated-body recognizer', () => {+ it('flags a handler that reads req.body with no schema', () => {+ expect(findUnvalidatedBodyHandlers(`+ router.post('/probe', asyncHandler(async (req, res) => {+ const { path } = req.body;+ res.json({ path });+ }));+ `)).toEqual(['POST /probe']);+ expect(findUnvalidatedBodyHandlers("router.put('/x/:id', mw, asyncHandler(async (req, res) => { use(req.body?.a); }));"))+ .toEqual(['PUT /x/:id']);+ expect(findUnvalidatedBodyHandlers("appsRouter.patch('/x', (req, res) => res.json(req.body));"))+ .toEqual(['PATCH /x']);+ });++ it('accepts each validation spelling', () => {+ for (const call of [+ 'validateRequest(fooSchema, req.body)',+ 'validate(fooSchema, req.body)',+ 'fooSchema.safeParse(req.body)',+ 'fooBodySchema.parse(req.body)',+ ]) {+ expect(findUnvalidatedBodyHandlers(`router.post('/x', asyncHandler(async (req, res) => { ${call}; }));`), call)+ .toEqual([]);+ }+ });++ it('ignores handlers that never read the body and mentions inside comments or strings', () => {+ expect(findUnvalidatedBodyHandlers("router.post('/x', (req, res) => { res.json({ ok: true }); });")).toEqual([]);+ expect(findUnvalidatedBodyHandlers("router.post('/x', (req, res) => { // req.body is ignored\n res.json('req.body'); });")).toEqual([]);+ // `JSON.parse` is not a schema parse.+ expect(findUnvalidatedBodyHandlers("router.post('/x', (req, res) => { JSON.parse(req.body.raw); });"))+ .toEqual(['POST /x']);+ });+});diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.jsindex ed2f6c8027..52366a8e62 100644--- a/server/routes/apps/taskTypes.js+++ b/server/routes/apps/taskTypes.js@@ -23,7 +23,7 @@ import { Router } from 'express';import { logCosScheduleUpdate } from '../../services/userActionScheduleLog.js';import * as appsService from '../../services/apps.js';import { PORTOS_APP_ID } from '../../services/apps.js';-import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS, validateRequest, qualitySchedulePlanSchema } from '../../lib/validation.js';+import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS, validateRequest, qualitySchedulePlanSchema, appTaskTypeToggleBodySchema, appTaskTypeOverrideBodySchema } from '../../lib/validation.js';import { buildQualitySchedulePlan, applyQualitySchedulePlan } from '../../services/appQualitySchedule.js';import { listWorkItems } from '../../services/workItems.js';import { resolveClaimWorkMetadata, resolveClaimAuthorFilter, resolveAppClaimReviewers } from '../../services/cosTaskGenerator.js';@@ -45,10 +45,7 @@ const OUTCOMES_DASHBOARD_LIMIT = 25;// PUT /api/apps/bulk-task-type/:taskType - Enable/disable a task type for all active appsrouter.put('/bulk-task-type/:taskType', asyncHandler(async (req, res) => {- const { enabled } = req.body;- if (typeof enabled !== 'boolean') {- throw new ServerError('enabled (boolean) is required', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { enabled } = validateRequest(appTaskTypeToggleBodySchema, req.body);if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });}@@ -262,10 +259,7 @@ router.post('/:id/quality-schedule/apply', loadApp, asyncHandler(async (req, res// PUT /api/apps/:id/task-types/all - Toggle all task types for an approuter.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {- const { enabled } = req.body;- if (typeof enabled !== 'boolean') {- throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { enabled } = validateRequest(appTaskTypeToggleBodySchema, req.body);const result = await appsService.toggleAllAppTaskTypes(req.params.id, enabled);if (!result) {throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });@@ -282,44 +276,23 @@ router.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {// PUT /api/apps/:id/task-types/:taskType - Update a task type override for an approuter.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {- const { enabled, intervalMs, providerId, model, taskMetadata } = req.body;- let { interval } = req.body;if (!SELF_IMPROVEMENT_TASK_TYPES.includes(req.params.taskType)) {throw new ServerError(`Unknown task type '${req.params.taskType}'`, { status: 400, code: 'INVALID_TASK_TYPE' });}- if (enabled !== undefined && typeof enabled !== 'boolean') {- throw new ServerError('enabled must be a boolean', { status: 400, code: 'VALIDATION_ERROR' });- }- if (typeof enabled !== 'boolean' && interval === undefined && intervalMs === undefined &&- providerId === undefined && model === undefined && taskMetadata === undefined) {- throw new ServerError('enabled (boolean), interval (string|null), intervalMs (number|null), providerId (string|null), model (string|null), or taskMetadata (object|null) required', { status: 400, code: 'VALIDATION_ERROR' });- }-// Per-app scheduling fields for handler-backed tasks (layered-intelligence).- // `null`/'' clears back to inherit; a numeric intervalMs must be a positive+ // `null` clears back to inherit; a numeric intervalMs must be a positive// finite number (a sub-daily cadence the string interval enum can't express).- if (intervalMs !== undefined && intervalMs !== null) {- if (typeof intervalMs !== 'number' || !Number.isFinite(intervalMs) || intervalMs <= 0) {- throw new ServerError('intervalMs must be a positive number or null', { status: 400, code: 'VALIDATION_ERROR' });- }- }- if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {- throw new ServerError('providerId must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });- }- if (model !== undefined && model !== null && typeof model !== 'string') {- throw new ServerError('model must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { enabled, intervalMs, providerId, model, taskMetadata, interval: requestedInterval } =+ validateRequest(appTaskTypeOverrideBodySchema, req.body);+ let interval = requestedInterval;- // Validate and sanitize taskMetadata to allowed agent-option keys only+ // Sanitize taskMetadata to allowed agent-option keys onlylet sanitizedTaskMetadata;if (taskMetadata === undefined) {sanitizedTaskMetadata = undefined;} else if (taskMetadata === null) {sanitizedTaskMetadata = null;} else {- if (typeof taskMetadata !== 'object' || Array.isArray(taskMetadata)) {- throw new ServerError('taskMetadata must be an object or null', { status: 400, code: 'VALIDATION_ERROR' });- }sanitizedTaskMetadata = sanitizeTaskMetadata(taskMetadata);if (sanitizedTaskMetadata === null) {throw new ServerError('Invalid taskMetadata: unrecognized keys or values', { status: 400, code: 'VALIDATION_ERROR' });@@ -331,9 +304,6 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {// custom) from an older client is rewritten onto that model rather than// rejected, so an install upgrading mid-session keeps working.if (interval !== undefined) {- if (interval !== null && typeof interval !== 'string') {- throw new ServerError('interval must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });- }if (typeof interval === 'string') {if (isCronExpression(interval)) {// Syntax + field ranges only. The walker returns null (never throws) fordiff --git a/server/routes/brainCapture.js b/server/routes/brainCapture.jsindex 3f4245d53b..a8e634f329 100644--- a/server/routes/brainCapture.js+++ b/server/routes/brainCapture.js@@ -8,7 +8,7 @@ import { Router } from 'express';import * as brainService from '../services/brain.js';import { recordUserAction } from '../services/userActions.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { validateRequest, brainInboxRetryBodySchema } from '../lib/validation.js';import {captureInputSchema,resolveReviewInputSchema,@@ -109,7 +109,7 @@ router.post('/fix', asyncHandler(async (req, res) => {* Retry AI classification for a needs_review item*/router.post('/inbox/:id/retry', asyncHandler(async (req, res) => {- const { providerOverride, modelOverride } = req.body || {};+ const { providerOverride, modelOverride } = validateRequest(brainInboxRetryBodySchema, req.body ?? {});const result = await brainService.retryClassification(req.params.id, providerOverride, modelOverride);res.json(result);}));diff --git a/server/routes/brainDailyLog.js b/server/routes/brainDailyLog.jsindex 4175a4f58d..5bbec7a188 100644--- a/server/routes/brainDailyLog.js+++ b/server/routes/brainDailyLog.js@@ -6,7 +6,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, parsePagination } from '../lib/validation.js';+import { validateRequest, parsePagination, brainJournalAppendBodySchema, brainJournalReplaceBodySchema } from '../lib/validation.js';import { dailyLogSettingsSchema, activityDigestSettingsSchema } from '../lib/brainValidation.js';import * as journal from '../services/brainJournal.js';import * as activityDigest from '../services/activityDigest.js';@@ -101,13 +101,10 @@ router.get('/daily-log/:date', asyncHandler(async (req, res) => {*/router.post('/daily-log/:date/append', asyncHandler(async (req, res) => {const date = await resolveJournalDate(req.params.date);- const { text, source } = req.body || {};- // Trim-check here too so a whitespace-only payload doesn't no-op all the+ // The schema trim-checks so a whitespace-only payload doesn't no-op all the// way through appendJournal() and still return a 200 — clients would read// that as a successful append.- if (typeof text !== 'string' || text.trim().length === 0) {- throw new ServerError('text is required', { status: 400, code: 'BAD_REQUEST' });- }+ const { text, source } = validateRequest(brainJournalAppendBodySchema, req.body ?? {});const entry = await journal.appendJournal(date, text, { source });res.json({ date, entry });}));@@ -136,11 +133,8 @@ router.post('/daily-log/:date/draft', asyncHandler(async (req, res) => {*/router.put('/daily-log/:date', asyncHandler(async (req, res) => {const date = await resolveJournalDate(req.params.date);- const { content, ifMatchUpdatedAt } = req.body || {};- if (typeof content !== 'string') {- throw new ServerError('content is required', { status: 400, code: 'BAD_REQUEST' });- }- const match = typeof ifMatchUpdatedAt === 'string' ? ifMatchUpdatedAt : null;+ const { content, ifMatchUpdatedAt } = validateRequest(brainJournalReplaceBodySchema, req.body ?? {});+ const match = ifMatchUpdatedAt ?? null;const entry = await journal.setJournalContent(date, content, { ifMatchUpdatedAt: match });res.json({ date, entry });}));diff --git a/server/routes/calendar.js b/server/routes/calendar.jsindex 610649d22a..7805650ba4 100644--- a/server/routes/calendar.js+++ b/server/routes/calendar.js@@ -1,7 +1,7 @@import express from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, parsePagination } from '../lib/validation.js';+import { validateRequest, parsePagination, calendarAutoConfigureBodySchema } from '../lib/validation.js';import { UUID_RE } from '../lib/fileUtils.js';import { MEETING_URL_MAX } from '../lib/meetingUrl.js';import * as calendarAccounts from '../services/calendarAccounts.js';@@ -381,7 +381,7 @@ router.post('/google/auto-configure/capture', asyncHandler(async (req, res) => {router.post('/google/auto-configure/run', asyncHandler(async (req, res) => {const io = req.app.get('io');- const email = req.body?.email || '';+ const { email = '' } = validateRequest(calendarAutoConfigureBodySchema, req.body ?? {});const result = await googleOAuthAutoConfig.runAutomatedSetup(email, io);res.json(result);}));diff --git a/server/routes/commands.js b/server/routes/commands.jsindex 0897a316ad..8841589570 100644--- a/server/routes/commands.js+++ b/server/routes/commands.js@@ -6,26 +6,20 @@ import * as commands from '../services/commands.js';import { requireHostControl } from '../services/authGate.js';import * as pm2Service from '../services/pm2.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest, commandExecuteBodySchema } from '../lib/validation.js';import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaceRoots.js';const router = Router();// POST /api/commands/execute - Execute a commandrouter.post('/execute', requireHostControl, asyncHandler(async (req, res) => {- const { command, workspacePath } = req.body;-- if (!command) {- throw new ServerError('Command is required', { status: 400, code: 'MISSING_COMMAND' });- }+ const { command, workspacePath } = validateRequest(commandExecuteBodySchema, req.body);// Validate workspacePath if provided: must exist, be a directory, and — after// symlinks are followed — resolve within an allowed root. Using realpath here// prevents a symlink like /tmp/escape -> /etc from tricking the containment// check (which only sees /tmp/escape).if (workspacePath !== undefined && workspacePath !== null && workspacePath !== '') {- if (typeof workspacePath !== 'string') {- throw new ServerError('workspacePath must be a string', { status: 400, code: 'INVALID_PATH' });- }const resolvedPath = resolve(workspacePath);if (!existsSync(resolvedPath)) {throw new ServerError('workspacePath does not exist', { status: 400, code: 'INVALID_PATH' });diff --git a/server/routes/commands.test.js b/server/routes/commands.test.jsindex 22163a32ad..9578c38b0a 100644--- a/server/routes/commands.test.js+++ b/server/routes/commands.test.js@@ -294,7 +294,7 @@ describe('commands routes', () => {.send({ workspacePath: WORKSPACE_PATH });expect(response.status).toBe(400);- expect(response.body.code).toBe('MISSING_COMMAND');+ expect(response.body.code).toBe('VALIDATION_ERROR');expect(existsSync).not.toHaveBeenCalled();expect(spawnMock).not.toHaveBeenCalled();});diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex 6b60d351d7..6e72f71b7b 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -9,7 +9,7 @@ import * as cos from '../services/cos.js';import * as agentOrchestrator from '../services/agentOrchestrator.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { toAgentListItems } from '../lib/cosAgentListProjection.js';-import { validateRequest, resumeCosAgentSchema, relaunchCosAgentSchema } from '../lib/validation.js';+import { validateRequest, resumeCosAgentSchema, relaunchCosAgentSchema, cosAgentFeedbackBodySchema, cosAgentBtwBodySchema } from '../lib/validation.js';const router = Router();@@ -210,11 +210,7 @@ router.delete('/agents/:id', asyncHandler(async (req, res) => {// POST /api/cos/agents/:id/feedback - Submit feedback for completed agentrouter.post('/agents/:id/feedback', asyncHandler(async (req, res) => {- const { rating, comment } = req.body;-- if (rating === undefined || !['positive', 'negative', 'neutral'].includes(rating)) {- throw new ServerError('rating must be positive, negative, or neutral', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { rating, comment } = validateRequest(cosAgentFeedbackBodySchema, req.body);// The service throws a ServerError — 404 when the agent is missing, 400// (INVALID_STATE) when it isn't completed — so no result-shape mapping here.@@ -224,20 +220,12 @@ router.post('/agents/:id/feedback', asyncHandler(async (req, res) => {// POST /api/cos/agents/:id/btw - Send additional context to a running agentrouter.post('/agents/:id/btw', asyncHandler(async (req, res) => {- const { message } = req.body;-- if (!message || typeof message !== 'string' || message.trim().length === 0) {- throw new ServerError('message is required and must be a non-empty string', { status: 400, code: 'VALIDATION_ERROR' });- }-- if (message.length > 5000) {- throw new ServerError('message must be 5000 characters or less', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { message } = validateRequest(cosAgentBtwBodySchema, req.body);// The service throws a ServerError — 404 when the agent is missing, 400// (INVALID_STATE) for the not-running / not-a-Claude-TUI refusals — so no// result-shape string-matching here.- const result = await cos.sendBtwToAgent(req.params.id, message.trim());+ const result = await cos.sendBtwToAgent(req.params.id, message);res.json(result);}));diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 391516df55..8c732e9ba2 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -8,7 +8,7 @@ import { z } from 'zod';import * as taskSchedule from '../services/taskSchedule.js';import { logCosScheduleUpdate } from '../services/userActionScheduleLog.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePagination } from '../lib/validation.js';+import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePagination, cosScheduleTargetBodySchema } from '../lib/validation.js';import { promptSourceSchema, PROMPT_SOURCES, scheduleExecutionFieldsSchema } from '../lib/cosValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../services/taskScheduleConstants.js';@@ -76,8 +76,7 @@ const SCHEDULE_FIELDS = ['type', 'autoStart', 'perpetual', 'enabled', 'intervalM* is the row being written, so a field that must not name itself (the advisory* `suggestedAfter`) can be cleaned here rather than again at the call site.*/-function pickScheduleSettings(body, taskType) {- const executionFields = validateRequest(scheduleExecutionFieldsSchema, body);+function pickScheduleSettings(body, executionFields, taskType) {const settings = {};for (const key of SCHEDULE_FIELDS) {if (body[key] !== undefined) settings[key] = body[key];@@ -242,7 +241,8 @@ router.get('/schedule/task/:taskType', asyncHandler(async (req, res) => {// PUT /api/cos/schedule/task/:taskType - Update interval for a task type (unified)router.put('/schedule/task/:taskType', asyncHandler(async (req, res) => {const { taskType } = req.params;- const settings = pickScheduleSettings(req.body, taskType);+ const executionFields = validateRequest(scheduleExecutionFieldsSchema, req.body);+ const settings = pickScheduleSettings(req.body, executionFields, taskType);// Filter self-references from runAfter to prevent permanent blockingif (Array.isArray(settings.runAfter)) {settings.runAfter = settings.runAfter.filter(dep => dep !== taskType);@@ -277,11 +277,7 @@ router.get('/schedule/due/:appId', asyncHandler(async (req, res) => {// POST /api/cos/schedule/trigger - Trigger an on-demand taskrouter.post('/schedule/trigger', asyncHandler(async (req, res) => {- const { taskType, appId } = req.body;-- if (!taskType) {- throw new ServerError('taskType is required', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { taskType, appId } = validateRequest(cosScheduleTargetBodySchema, req.body);const request = await taskSchedule.triggerOnDemandTask(taskType, appId);if (request?.error) {@@ -338,11 +334,7 @@ router.delete('/schedule/on-demand/:requestId', asyncHandler(async (req, res) =>// POST /api/cos/schedule/reset - Reset execution history for a task typerouter.post('/schedule/reset', asyncHandler(async (req, res) => {- const { taskType, appId } = req.body;-- if (!taskType) {- throw new ServerError('taskType is required', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { taskType, appId } = validateRequest(cosScheduleTargetBodySchema, req.body);const result = await taskSchedule.resetExecutionHistory(taskType, appId);if (result.error) {diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsindex 5ea766ebde..bb9954dd24 100644--- a/server/routes/cosScheduleRoutes.test.js+++ b/server/routes/cosScheduleRoutes.test.js@@ -35,6 +35,11 @@ vi.mock('../lib/validation.js', () => ({: { success: false };}},+ cosScheduleTargetBodySchema: {+ safeParse: (body) => (typeof body?.taskType === 'string' && body.taskType+ ? { success: true, data: { taskType: body.taskType, appId: body.appId } }+ : { success: false }),+ },validateRequest: vi.fn((schema, data) => {const result = schema.safeParse(data);if (!result.success) {diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex d0c9934555..f7b3580383 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -29,6 +29,7 @@ import {resolveChallengeSchema,goalFidelityFalsePositiveSchema,validateRequest,+ cosTaskReorderBodySchema,isPaginationRequested,parsePagination,} from '../lib/validation.js';@@ -228,11 +229,7 @@ router.post('/tasks/refresh', asyncHandler(async (req, res) => {// POST /api/cos/tasks/reorder - Reorder tasksrouter.post('/tasks/reorder', asyncHandler(async (req, res) => {- const { taskIds } = req.body;-- if (!taskIds || !Array.isArray(taskIds)) {- throw new ServerError('taskIds array is required', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { taskIds } = validateRequest(cosTaskReorderBodySchema, req.body);const result = await cos.reorderTasks(taskIds);res.json(result);diff --git a/server/routes/dataManager.js b/server/routes/dataManager.jsindex a78ed6c64e..48142f794e 100644--- a/server/routes/dataManager.js+++ b/server/routes/dataManager.js@@ -1,7 +1,7 @@import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, dataPurgeSchema } from '../lib/validation.js';+import { validateRequest, dataPurgeSchema, dataArchiveBodySchema } from '../lib/validation.js';import {getDataOverview,getCategoryDetail,@@ -70,11 +70,7 @@ router.get('/:category', asyncHandler(async (req, res) => {// POST /api/data/:category/archive — archive a category to backuprouter.post('/:category/archive', asyncHandler(async (req, res) => {- const rawDays = req.body?.daysToKeep;- const daysToKeep = rawDays != null ? Number(rawDays) : undefined;- if (daysToKeep != null && (!Number.isFinite(daysToKeep) || daysToKeep < 0)) {- throw new ServerError('daysToKeep must be a non-negative number', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { daysToKeep } = validateRequest(dataArchiveBodySchema, req.body ?? {});const result = await archiveCategory(req.params.category, { daysToKeep });res.json(result);}));diff --git a/server/routes/detect.js b/server/routes/detect.jsindex fac9b4279c..28a70aefb0 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -8,6 +8,7 @@ import { listProcessesStrict } from '../services/pm2.js';import { detectAppWithAi } from '../services/aiDetect.js';import { requestHasHostControl } from '../services/authGate.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest, detectRepoBodySchema, detectPortBodySchema, detectPm2BodySchema, detectAiBodySchema } from '../lib/validation.js';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { isWithinAllowedRoots, outsideAllowedRootsMessage, WORKSPACE_ROOTS_CONFIGURED } from '../lib/workspaceRoots.js';@@ -69,11 +70,7 @@ const checkWorkspacePathAllowed = (path) => {// unrestricted, matching the pre-existing behavior. POST /ai enforces the same// allow-list via the shared `checkWorkspacePathAllowed` helper above.router.post('/repo', asyncHandler(async (req, res) => {- const { path } = req.body;-- if (!path) {- throw new ServerError('Path is required', { status: 400, code: 'MISSING_PATH' });- }+ const { path } = validateRequest(detectRepoBodySchema, req.body);// Check if path existsif (!existsSync(path)) {@@ -190,23 +187,15 @@ router.post('/repo', asyncHandler(async (req, res) => {// POST /api/detect/port - Detect what process is running on a portrouter.post('/port', asyncHandler(async (req, res) => {- const { port } = req.body;-- if (!port || isNaN(port)) {- throw new ServerError('Valid port number is required', { status: 400, code: 'INVALID_PORT' });- }+ const { port: safePort } = validateRequest(detectPortBodySchema, req.body);const result = {- port: parseInt(port, 10),+ port: safePort,inUse: false,process: null};// Use lsof on macOS/Linux to find process- const safePort = parseInt(port, 10);- if (!Number.isInteger(safePort) || safePort < 1 || safePort > 65535) {- throw new ServerError(`Invalid port number: ${port}`, { status: 400 });- }const command = process.platform === 'darwin'? `lsof -i :${safePort} -P -n | grep LISTEN`: `ss -lntp | grep :${safePort}`;@@ -234,11 +223,7 @@ router.post('/port', asyncHandler(async (req, res) => {// POST /api/detect/pm2 - Check if a PM2 process exists with given namerouter.post('/pm2', asyncHandler(async (req, res) => {- const { name } = req.body;-- if (!name) {- throw new ServerError('Process name is required', { status: 400, code: 'MISSING_NAME' });- }+ const { name } = validateRequest(detectPm2BodySchema, req.body);// `listProcessesStrict()` returns `null` when the PM2 read itself FAILED (vs// `[]` for a successful read with no processes) — the absent-vs-empty@@ -272,11 +257,7 @@ router.post('/pm2', asyncHandler(async (req, res) => {// A provider that cannot run tool-free needs host control (#9008): a remote// caller on a password-free install gets 403 HOST_CONTROL_FORBIDDEN instead.router.post('/ai', asyncHandler(async (req, res) => {- const { path, providerId } = req.body;-- if (!path) {- throw new ServerError('Path is required', { status: 400, code: 'MISSING_PATH' });- }+ const { path, providerId } = validateRequest(detectAiBodySchema, req.body);const confinement = checkWorkspacePathAllowed(path);if (!confinement.ok) {diff --git a/server/routes/detect.test.js b/server/routes/detect.test.jsindex 2d67a5e576..de74256a1e 100644--- a/server/routes/detect.test.js+++ b/server/routes/detect.test.js@@ -88,6 +88,16 @@ describe('POST /api/detect/pm2', () => {vi.clearAllMocks();});+ it('rejects a wrong-typed process name before reading PM2', async () => {+ const response = await request(app)+ .post('/api/detect/pm2')+ .send({ name: { $ne: 'x' } });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('VALIDATION_ERROR');+ expect(listProcessesStrict).not.toHaveBeenCalled();+ });+it('reports exists:false only for a successful read with no matching process', async () => {listProcessesStrict.mockResolvedValue([{ name: 'other-app', status: 'online', pid: 123, pm_id: 0 }]);diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex e6a20debb3..3e9792b435 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -14,7 +14,7 @@ import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import {- validateRequest, imageCancelBodySchema, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,+ validateRequest, imageCancelBodySchema, imageVisibilityBodySchema, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,} from '../lib/validation.js';import { optionalUploadFields, optionalUpload } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';@@ -929,7 +929,7 @@ router.get('/:filename/variants', asyncHandler(async (req, res) => {}));router.post('/:filename/visibility', asyncHandler(async (req, res) => {- res.json(await local.setImageHidden(req.params.filename, !!req.body?.hidden));+ res.json(await local.setImageHidden(req.params.filename, validateRequest(imageVisibilityBodySchema, req.body ?? {}).hidden));}));router.patch('/:filename/prompt', asyncHandler(async (req, res) => {diff --git a/server/routes/messages.js b/server/routes/messages.jsindex ccd3633fa1..f6495041ee 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -2,7 +2,10 @@ import { messageInboxRead, messageDetailRead, messageParamsSchema } from './messimport express from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import {+ validateRequest, MESSAGE_TOKEN_PROVIDERS, messageSyncBodySchema, messageFetchFullBodySchema,+ messageActionBodySchema, messageTokenProviderBodySchema,+} from '../lib/validation.js';import { UUID_RE } from '../lib/fileUtils.js';import { sendViaForAccountType } from '../lib/messageTransport.js';import * as messageAccounts from '../services/messageAccounts.js';@@ -138,9 +141,9 @@ router.post('/sync/:accountId', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {throw new ServerError('Invalid account ID format', { status: 400 });}- // An omitted/unrecognized mode stays undefined so syncAccount selects the account's- // supported default; an explicit one is validated against the account there.- const mode = ['unread', 'full'].includes(req.body?.mode) ? req.body.mode : undefined;+ // An omitted mode stays undefined so syncAccount selects the account's supported+ // default; an explicit one is validated against the account there.+ const { mode } = validateRequest(messageSyncBodySchema, req.body ?? {});const io = req.app.get('io');const result = await messageSync.syncAccount(req.params.accountId, io, { mode });if (result.error) throw new ServerError(result.error, { status: result.status || 404 });@@ -410,7 +413,7 @@ router.post('/fetch-full/:accountId', asyncHandler(async (req, res) => {if (!account) throw new ServerError('Account not found', { status: 404 });if (account.type !== 'outlook') return res.json({ updated: 0, total: 0 });- const force = req.body?.force === true;+ const { force } = validateRequest(messageFetchFullBodySchema, req.body ?? {});const allResult = await messageSync.getMessages({ accountId, limit: FULL_BODY_REFRESH_LIMIT });const truncated = allResult.messages.length >= FULL_BODY_REFRESH_LIMIT;const toRefresh = force ? allResult.messages : allResult.messages.filter(m => m.bodyFull === false);@@ -435,17 +438,14 @@ router.post('/:accountId/:messageId/action', asyncHandler(async (req, res) => {const parsed = messageParamsSchema.safeParse(req.params);if (!parsed.success) throw new ServerError('Invalid accountId or messageId format', { status: 400 });const { accountId, messageId } = parsed.data;- const action = req.body?.action;- if (!['archive', 'delete'].includes(action)) {- throw new ServerError('Invalid action — must be "archive" or "delete"', { status: 400 });- }+ const { action } = validateRequest(messageActionBodySchema, req.body);const result = await executeAction(accountId, messageId, action);req.app.get('io')?.emit('messages:changed', {});res.json(result);}));// === Debug: Token Extraction & API Testing ===-const ALLOWED_TOKEN_PROVIDERS = ['outlook', 'teams'];+const ALLOWED_TOKEN_PROVIDERS = MESSAGE_TOKEN_PROVIDERS;router.get('/debug/token-status', asyncHandler(async (req, res) => {const statuses = ALLOWED_TOKEN_PROVIDERS.map(p => getTokenStatus(p));@@ -453,7 +453,7 @@ router.get('/debug/token-status', asyncHandler(async (req, res) => {}));router.post('/debug/test-token', asyncHandler(async (req, res) => {- const provider = ALLOWED_TOKEN_PROVIDERS.includes(req.body?.provider) ? req.body.provider : 'outlook';+ const { provider = 'outlook' } = validateRequest(messageTokenProviderBodySchema, req.body ?? {});const tokenResult = await getToken(provider);if (tokenResult.error) {throw new ServerError(tokenResult.message || tokenResult.error, {@@ -489,7 +489,7 @@ router.post('/debug/test-token', asyncHandler(async (req, res) => {}));router.post('/debug/clear-token', asyncHandler(async (req, res) => {- const provider = ALLOWED_TOKEN_PROVIDERS.includes(req.body?.provider) ? req.body.provider : null;+ const { provider = null } = validateRequest(messageTokenProviderBodySchema, req.body ?? {});clearTokenCache(provider);res.json({ cleared: true, provider: provider || 'all' });}));diff --git a/server/routes/messages.test.js b/server/routes/messages.test.jsindex 43d4fc15cd..0833954d2f 100644--- a/server/routes/messages.test.js+++ b/server/routes/messages.test.js@@ -279,6 +279,14 @@ describe('Messages Routes', () => {expect(response.body.error).toContain('unread');});+ it('rejects an unknown sync mode instead of silently syncing unread', async () => {+ const response = await request(app).post(`/api/messages/sync/${VALID_UUID}`).send({ mode: 'everything' });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('VALIDATION_ERROR');+ expect(messageSync.syncAccount).not.toHaveBeenCalled();+ });+it('should return 400 for invalid UUID', async () => {const response = await request(app).post(`/api/messages/sync/${INVALID_UUID}`);diff --git a/server/routes/moltworldTools.js b/server/routes/moltworldTools.jsindex 0579828578..9afa0cb1b8 100644--- a/server/routes/moltworldTools.js+++ b/server/routes/moltworldTools.js@@ -7,7 +7,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, moltworldJoinSchema, moltworldBuildSchema, moltworldExploreSchema, moltworldThinkSchema, moltworldSaySchema, moltworldQueueAddSchema } from '../lib/validation.js';+import { validateRequest, moltworldJoinSchema, moltworldBuildSchema, moltworldExploreSchema, moltworldThinkSchema, moltworldSaySchema, moltworldQueueAddSchema, moltworldQueueFailBodySchema } from '../lib/validation.js';import * as platformAccounts from '../services/platformAccounts.js';import * as agentPersonalities from '../services/agentPersonalities.js';import * as agentActivity from '../services/agentActivity.js';@@ -277,7 +277,7 @@ router.post('/queue/:id/complete', asyncHandler(async (req, res) => {// POST /queue/:id/fail — Mark queue item as failed (used by explore script)router.post('/queue/:id/fail', asyncHandler(async (req, res) => {const { id } = req.params;- const { error } = req.body || {};+ const { error } = validateRequest(moltworldQueueFailBodySchema, req.body ?? {});const item = moltworldQueue.markFailed(id, error || 'Unknown error');if (!item) {throw new ServerError('Queue item not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/routes/prompts.js b/server/routes/prompts.jsindex 76912c6ad4..9e89a63b6a 100644--- a/server/routes/prompts.js+++ b/server/routes/prompts.js@@ -1,6 +1,6 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { promptStageNameSchema, promptVariableKeySchema, stageConfigUpdateSchema, validateRequest } from '../lib/validation.js';+import { promptStageNameSchema, promptVariableKeySchema, stageConfigUpdateSchema, validateRequest, promptVariableUpdateBodySchema, promptJobSkillBodySchema, promptPreviewBodySchema } from '../lib/validation.js';import {SYSTEM_STAGE_KEYS,isProtectedStage,@@ -75,7 +75,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {// PUT /api/prompts/variables/:key - Update a variablerouter.put('/variables/:key', asyncHandler(async (req, res) => {- const { name, category, content } = req.body;+ const { name, category, content } = validateRequest(promptVariableUpdateBodySchema, req.body);await promptsService.updateVariable(req.params.key, { name, category, content });res.json({ success: true });}));@@ -117,10 +117,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {// PUT /api/prompts/skills/jobs/:name - Update a job skill templaterouter.put('/skills/jobs/:name', asyncHandler(async (req, res) => {- const { content } = req.body;- if (!content) {- throw new ServerError('content is required', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { content } = validateRequest(promptJobSkillBodySchema, req.body);await saveJobSkillTemplate(req.params.name, content);res.json({ success: true });}));@@ -232,7 +229,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {// POST /api/prompts/:stage/preview - Preview compiled promptrouter.post('/:stage/preview', asyncHandler(async (req, res) => {- const { testData = {} } = req.body;+ const { testData } = validateRequest(promptPreviewBodySchema, req.body ?? {});const preview = await promptsService.previewPrompt(req.params.stage, testData);res.json({ preview });}));diff --git a/server/routes/referenceRepos.js b/server/routes/referenceRepos.jsindex 43d1841eb7..4dc540761d 100644--- a/server/routes/referenceRepos.js+++ b/server/routes/referenceRepos.js@@ -15,7 +15,7 @@import { Router } from 'express';import { asyncHandler, failValidation } from '../lib/errorHandler.js';-import { referenceRepoCreateSchema, referenceRepoUpdateSchema } from '../lib/validation.js';+import { referenceRepoCreateSchema, referenceRepoUpdateSchema, referenceRepoReviewedBodySchema, validateRequest } from '../lib/validation.js';import {listReferenceRepos,addReferenceRepo,@@ -82,7 +82,7 @@ router.post('/:refId/check', asyncHandler(async (req, res) => {}));router.post('/:refId/reviewed', asyncHandler(async (req, res) => {- const sha = (req.body?.sha || '').trim();+ const { sha } = validateRequest(referenceRepoReviewedBodySchema, req.body ?? {});const ref = await markReferenceRepoReviewed(req.params.appId, req.params.refId, sha);res.json(ref);}));diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex 7622a4ddb9..810bea466c 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -8,7 +8,7 @@ import { promisify } from 'util';import { platform } from 'os';import { createApp, getReservedPorts, notifyAppsChanged } from '../services/apps.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, scaffoldSchema } from '../lib/validation.js';+import { validateRequest, scaffoldSchema, scaffoldTemplateCreateBodySchema } from '../lib/validation.js';import { ensureDir, expandHome } from '../lib/fileUtils.js';import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaceRoots.js';import { scaffoldVite } from './scaffoldVite.js';@@ -162,14 +162,7 @@ router.get('/templates', asyncHandler(async (req, res) => {// POST /api/scaffold/templates/create - User-friendly template creationrouter.post('/templates/create', asyncHandler(async (req, res) => {- const { templateId, name, targetPath } = req.body;-- if (!templateId || !name || !targetPath) {- throw new ServerError('templateId, name, and targetPath are required', {- status: 400,- code: 'VALIDATION_ERROR'- });- }+ const { templateId, name, targetPath } = validateRequest(scaffoldTemplateCreateBodySchema, req.body);// Map to scaffold endpoint formatconst scaffoldData = {diff --git a/server/routes/screenshots.js b/server/routes/screenshots.jsindex c1f9d54e95..3881b27980 100644--- a/server/routes/screenshots.js+++ b/server/routes/screenshots.js@@ -2,7 +2,8 @@ import { Router } from 'express';import { existsSync } from 'fs';import { resolve } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest, screenshotUploadBodySchema } from '../lib/validation.js';import { PATHS, sanitizeFilename, isPathInsideDir, saveImageUpload } from '../lib/fileUtils.js';import { MAX_SCREENSHOT_BYTES } from '../lib/uploadLimits.js';@@ -15,11 +16,7 @@ const MAX_FILE_SIZE = MAX_SCREENSHOT_BYTES;// POST /api/screenshots - Upload a screenshot (base64)router.post('/', asyncHandler(async (req, res) => {- const { data, filename } = req.body;-- if (!data) {- throw new ServerError('data is required (base64)', { status: 400, code: 'VALIDATION_ERROR' });- }+ const { data, filename } = validateRequest(screenshotUploadBodySchema, req.body);const id = uuidv4();// The server UUID always prefixes the stored name: clients (camera roll,diff --git a/server/routes/standardize.js b/server/routes/standardize.jsindex 5994b9fe79..1d20a53ec4 100644--- a/server/routes/standardize.js+++ b/server/routes/standardize.js@@ -2,7 +2,7 @@ import { Router } from 'express';import { realpath } from 'fs/promises';import { resolve } from 'path';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { standardizeApplySchema, validateRequest } from '../lib/validation.js';+import { standardizeApplySchema, standardizeTargetBodySchema, validateRequest } from '../lib/validation.js';import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaceRoots.js';import * as pm2Standardizer from '../services/pm2Standardizer.js';import * as appsService from '../services/apps.js';@@ -72,7 +72,7 @@ async function resolveStandardizeTarget({ repoPath, appId }) {// POST /api/standardize/analyze - Analyze app and generate standardization planrouter.post('/analyze', asyncHandler(async (req, res) => {- const { repoPath, appId, providerId } = req.body;+ const { repoPath, appId, providerId } = validateRequest(standardizeTargetBodySchema, req.body);const path = await resolveStandardizeTarget({ repoPath, appId });@@ -126,7 +126,7 @@ router.get('/template', asyncHandler(async (req, res) => {// POST /api/standardize/backup - Create git backup onlyrouter.post('/backup', asyncHandler(async (req, res) => {- const { repoPath, appId } = req.body;+ const { repoPath, appId } = validateRequest(standardizeTargetBodySchema, req.body);const path = await resolveStandardizeTarget({ repoPath, appId });diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex c05ce9c50f..b6e821f034 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -7,7 +7,7 @@ import { getSelf } from '../services/instanceIdentity.js';import { getCurrentVersion } from '../services/updateChecker.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, systemHealthWarningParamsSchema, systemHealthWarningDismissSchema } from '../lib/validation.js';+import { validateRequest, systemHealthWarningParamsSchema, systemHealthWarningDismissSchema, systemHealthThresholdsBodySchema } from '../lib/validation.js';import { getSettingsWithStatus, updateSettingsWith } from '../services/settings.js';import { isAuthEnabled } from '../services/auth.js';@@ -143,18 +143,7 @@ router.delete('/health/warnings/:type/dismiss', asyncHandler(async (req, res) =>const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));router.put('/health/thresholds', asyncHandler(async (req, res) => {- const body = req.body || {};- const incoming = {- memoryWarn: Number(body.memoryWarn),- memoryCritical: Number(body.memoryCritical),- diskWarn: Number(body.diskWarn),- diskCritical: Number(body.diskCritical)- };- for (const [k, v] of Object.entries(incoming)) {- if (!Number.isFinite(v)) {- throw new ServerError(`Invalid threshold value for ${k}`, { status: 400 });- }- }+ const incoming = validateRequest(systemHealthThresholdsBodySchema, req.body ?? {});const next = {memoryWarn: clamp(Math.round(incoming.memoryWarn), 50, 99),memoryCritical: clamp(Math.round(incoming.memoryCritical), 50, 99),diff --git a/server/routes/voice.js b/server/routes/voice.jsindex b3b88d98df..ec154cc863 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -10,7 +10,7 @@ import { Router } from 'express';import { TTS_ENGINE_IDS } from '../lib/voiceEngines.js';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { validateRequest, voicePiperFetchBodySchema } from '../lib/validation.js';import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';import { checkAll, invalidateHealthCache } from '../services/voice/health.js';@@ -474,7 +474,7 @@ router.post('/qwen3/download-model', asyncHandler(async (req, res) => {// POST /api/voice/piper/fetchrouter.post('/piper/fetch', asyncHandler(async (req, res) => {- const voice = (req.body?.voice || '').toString();+ const { voice } = validateRequest(voicePiperFetchBodySchema, req.body ?? {});if (!findPiperVoice(voice)) {throw new ServerError(`unknown piper voice: ${voice}`, { status: 400 });}@@ -484,14 +484,15 @@ router.post('/piper/fetch', asyncHandler(async (req, res) => {}));// POST /api/voice/test+const voiceTestBodySchema = z.object({+ text: z.string().trim().min(1).max(MAX_VOICE_TEXT_LEN),+ voice: z.string().trim().default(''),+ engine: z.string().trim().default(''),+});router.post('/test', asyncHandler(async (req, res) => {- const text = (req.body?.text || '').toString().trim();- if (!text) throw new ServerError('text is required', { status: 400 });- if (text.length > MAX_VOICE_TEXT_LEN) {- throw new ServerError(`text too long (${text.length} > ${MAX_VOICE_TEXT_LEN} chars)`, { status: 400 });- }- const voice = (req.body?.voice || '').toString().trim() || undefined;- const engine = validEngine((req.body?.engine || '').toString().trim());+ const { text, voice: requestedVoice, engine: requestedEngine } = validateRequest(voiceTestBodySchema, req.body ?? {});+ const voice = requestedVoice || undefined;+ const engine = validEngine(requestedEngine);const { wav, latencyMs } = await synthesize(text, { voice, engine });res.setHeader('Content-Type', 'audio/wav');res.setHeader('X-TTS-Latency-Ms', String(latencyMs));diff --git a/server/routes/voice.test.js b/server/routes/voice.test.jsindex d1275be6d5..1e6194a5f1 100644--- a/server/routes/voice.test.js+++ b/server/routes/voice.test.js@@ -467,7 +467,7 @@ describe('Voice Routes', () => {it('requires text', async () => {const res = await request(buildApp()).post('/api/voice/test').send({});expect(res.status).toBe(400);- expect(res.body.error).toMatch(/text is required/);+ expect(res.body.code).toBe('VALIDATION_ERROR');});it('returns WAV bytes on success', async () => {diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsindex 866cc9d1f0..937855db31 100644--- a/server/routes/writersRoom.js+++ b/server/routes/writersRoom.js@@ -29,6 +29,7 @@ import {writersRoomObjectCreateSchema,writersRoomObjectUpdateSchema,writersRoomWorksQuerySchema,+ writersRoomSceneImageBodySchema,} from '../lib/validation.js';import {listFolders, createFolder, deleteFolder,@@ -393,7 +394,7 @@ router.delete('/works/:id/objects/:objectId', asyncHandler(async (req, res) => {// `writersRoomSceneImageHook` listens to (#1363); the async local/Codex lanes// now file durably via that hook instead.router.post('/works/:id/analysis/:analysisId/scene-image', asyncHandler(async (req, res) => {- const { sceneId, filename, jobId, prompt } = req.body || {};+ const { sceneId, filename, jobId, prompt } = validateRequest(writersRoomSceneImageBodySchema, req.body ?? {});const { analysis, collectionId } = await persistSceneImage(req.params.id, req.params.analysisId, { sceneId, filename, jobId, prompt },);