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: route-validation guard requires the validation call to receive req.body (#10024)
[._.]/ Adam Eivy72094fc89e13
diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 9f80502c64..ab63732faf 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -917,6 +917,8 @@ export const socialAccountSchema = z.object({notes: z.string().max(2000).optional().default('')});+// Bulk create: each entry is validated per-account (a bad one is reported, not fatal).+export const socialAccountBulkBodySchema = z.object({ accounts: z.array(z.unknown()).min(1, 'accounts array is required') });export const socialAccountUpdateSchema = partialWithoutDefaults(socialAccountSchema);// =============================================================================@@ -2318,6 +2320,7 @@ export * from './agentValidation.js';export * from './cosValidation.js';export * from './mediaValidation.js';export * from './pipelineValidation.js';+import { stageConfigUpdateSchema } from './pipelineValidation.js';export * from './quotaBurnValidation.js';export * from './spriteValidation.js';export * from './agentContextValidation.js';@@ -2723,6 +2726,17 @@ export const brainJournalReplaceBodySchema = z.object({ content: z.string(), ifM// Prompts (routes/prompts.js)export const promptVariableUpdateBodySchema = z.object({ name: optionalString, category: optionalString, content: optionalString });+export const promptVariableCreateBodySchema = z.object({ key: promptVariableKeySchema, name: optionalString, category: optionalString, content: nonEmptyString });+export const promptStageCreateBodySchema = z.object({+ stageName: promptStageNameSchema,+ name: nonEmptyString,+ description: optionalString,+ model: z.string().default('default'),+ returnsJson: z.boolean().default(false),+ variables: z.array(z.string()).default([]),+ template: z.string().default(''),+});+export const promptStageUpdateBodySchema = stageConfigUpdateSchema.extend({ template: z.string().optional() });export const promptJobSkillBodySchema = z.object({ content: nonEmptyString });export const promptPreviewBodySchema = z.object({ testData: z.record(z.string(), z.unknown()).default({}) });diff --git a/server/routeValidationConventions.test.js b/server/routeValidationConventions.test.jsindex 05fc256ccc..3ac2d6ecf2 100644--- a/server/routeValidationConventions.test.js+++ b/server/routeValidationConventions.test.js@@ -27,14 +27,15 @@* ## 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;+ * It checks that the validation call's DATA argument carries `req.body` (or a+ * name assigned from it, incl. a `...rest` copy), so validating `req.params` while+ * reading `req.body` raw is flagged. It cannot see a body validated field-by-field+ * through a helper. 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.+ * separate process with its own spawn API). `req.query` reads and the+ * aiToolkit/cos-runner trees are follow-ups (#10024).*/import { describe, it, expect } from 'vitest';@@ -51,13 +52,56 @@ const SERVER_ROOT = dirname(fileURLToPath(import.meta.url));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/imageClean.js POST /', 'raw image bytes (express.raw Buffer); the JSON-shaped options are validated from req.query'],['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*\(/;+const VALIDATE_CALL = /\bvalidateRequest\s*\(|\bvalidate\s*\(|\.safeParse\s*\(|[Ss]chema\w*\.parse\s*\(/g;+// `const body = req.body`, `const { a, ...rest } = req.body`: a name that carries the raw body.+const BODY_ALIAS = /\b(?:const|let|var)\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s*=\s*req\.body\b/g;++/** Names (besides `req.body`) bound to the raw body or to a rest-copy of it. */+function bodyAliases(text) {+ const names = [];+ for (const m of text.matchAll(BODY_ALIAS)) {+ if (!m[1].startsWith('{')) names.push(m[1]);+ else for (const rest of m[1].matchAll(/\.\.\.\s*([A-Za-z_$][\w$]*)/g)) names.push(rest[1]);+ }+ return names;+}++/** Index of the first comma outside any bracket pair, or -1 (→ the whole string is one argument). */+function topLevelComma(args) {+ let depth = 0;+ for (let i = 0; i < args.length; i += 1) {+ const ch = args[i];+ if ('([{'.includes(ch)) depth += 1;+ else if (')]}'.includes(ch)) depth -= 1;+ else if (ch === ',' && depth === 0) return i;+ }+ return -1;+}++/** True when some validation call in `text` receives the body as its DATA argument. */+function validatesBody(text) {+ const carriesBody = new RegExp(`\\breq\\.body\\b|\\b(?:${bodyAliases(text).join('|') || '(?!)'})\\b`);+ for (const call of text.matchAll(VALIDATE_CALL)) {+ const open = call.index + call[0].length - 1;+ const end = matchBracket(text, open);+ if (end === -1) continue;+ const args = text.slice(open + 1, end);+ // `validateRequest(schema, data)` / `validate(schema, data)` take the data second, so+ // a body mentioned inside the schema expression does not count. `.safeParse(data)` /+ // `Schema.parse(data)` take it first.+ const schemaFirst = /^(?:validateRequest|validate)\b/.test(call[0].trim());+ const dataArg = schemaFirst ? args.slice(topLevelComma(args) + 1) : args;+ if (carriesBody.test(dataArg)) return true;+ }+ return false;+}/** `<VERB> <path>` for every handler in one file's source that reads `req.body` without validating it. */export function findUnvalidatedBodyHandlers(src) {@@ -68,7 +112,7 @@ export function findUnvalidatedBodyHandlers(src) {const end = matchBracket(blanked, open);if (end === -1) continue;const text = blanked.slice(open, end);- if (!READS_BODY.test(text) || VALIDATES.test(text)) continue;+ if (!READS_BODY.test(text) || validatesBody(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}`);@@ -142,6 +186,26 @@ describe('the unvalidated-body recognizer', () => {}});+ it('flags a handler that validates req.params or a mere field but reads req.body raw (#10024)', () => {+ expect(findUnvalidatedBodyHandlers("router.post('/x/:id', asyncHandler(async (req, res) => { validateRequest(idSchema, req.params); use(req.body.name); }));"))+ .toEqual(['POST /x/:id']);+ expect(findUnvalidatedBodyHandlers("router.post('/x', asyncHandler(async (req, res) => { const { key, content } = req.body; validateRequest(keySchema, key); }));"))+ .toEqual(['POST /x']);+ expect(findUnvalidatedBodyHandlers("router.post('/x', asyncHandler(async (req, res) => { validateRequest(schemaFor(req.body.kind), req.params); }));"))+ .toEqual(['POST /x']);+ });++ it('accepts a body validated through an alias, a spread, or a rest copy (#10024)', () => {+ for (const body of [+ 'const body = req.body; validateRequest(fooSchema, body);',+ 'validateRequest(fooSchema, { ...req.body, id: req.params.id });',+ 'validateRequest(fooSchema.partial(), req.body || {});',+ 'const { password, ...rest } = req.body; validateRequest(fooSchema, rest);',+ ]) {+ expect(findUnvalidatedBodyHandlers(`router.put('/x', asyncHandler(async (req, res) => { ${body} }));`), body).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([]);diff --git a/server/routes/prompts.js b/server/routes/prompts.jsindex 9e89a63b6a..800ebcf278 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, promptVariableUpdateBodySchema, promptJobSkillBodySchema, promptPreviewBodySchema } from '../lib/validation.js';+import { promptStageNameSchema, promptVariableKeySchema, promptStageCreateBodySchema, promptStageUpdateBodySchema, promptVariableCreateBodySchema, validateRequest, promptVariableUpdateBodySchema, promptJobSkillBodySchema, promptPreviewBodySchema } from '../lib/validation.js';import {SYSTEM_STAGE_KEYS,isProtectedStage,@@ -61,11 +61,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {// POST /api/prompts/variables - Create a variablerouter.post('/variables', asyncHandler(async (req, res) => {- const { key, name, category, content } = req.body;- if (!key || !content) {- throw new ServerError('key and content are required', { status: 400, code: 'VALIDATION_ERROR' });- }- validateRequest(promptVariableKeySchema, key);+ const { key, name, category, content } = validateRequest(promptVariableCreateBodySchema, req.body);if (promptsService.getVariable(key)) {throw new ServerError(`Variable ${key} already exists`, { status: 409, code: 'CONFLICT' });}@@ -150,11 +146,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {// POST /api/prompts - Create a new stagerouter.post('/', asyncHandler(async (req, res) => {- const { stageName, name, description, model = 'default', returnsJson = false, variables = [], template = '' } = req.body;- if (!stageName || !name) {- throw new ServerError('stageName and name are required', { status: 400, code: 'VALIDATION_ERROR' });- }- validateRequest(promptStageNameSchema, stageName);+ const { stageName, name, description, model, returnsJson, variables, template } = validateRequest(promptStageCreateBodySchema, req.body);if (promptsService.getStage(stageName)) {throw new ServerError(`Stage ${stageName} already exists`, { status: 409, code: 'CONFLICT' });}@@ -173,13 +165,10 @@ export function createPortOSPromptsRoutes(aiToolkit) {if (!promptsService.getStage(req.params.stage)) {throw new ServerError('Stage not found', { status: 404, code: 'NOT_FOUND' });}- const { template, ...rawConfig } = req.body;+ const { template, ...config } = validateRequest(promptStageUpdateBodySchema, req.body ?? {});- if (Object.keys(rawConfig).length > 0) {- const config = validateRequest(stageConfigUpdateSchema, rawConfig);- if (Object.keys(config).length > 0) {- await promptsService.updateStageConfig(req.params.stage, config);- }+ if (Object.keys(config).length > 0) {+ await promptsService.updateStageConfig(req.params.stage, config);}if (template !== undefined) {await promptsService.updateStageTemplate(req.params.stage, template);diff --git a/server/routes/socialAccounts.js b/server/routes/socialAccounts.jsindex 86a42212d7..68d3213772 100644--- a/server/routes/socialAccounts.js+++ b/server/routes/socialAccounts.js@@ -7,7 +7,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validate, validateRequest, socialAccountSchema, socialAccountUpdateSchema } from '../lib/validation.js';+import { validate, validateRequest, socialAccountSchema, socialAccountBulkBodySchema, socialAccountUpdateSchema } from '../lib/validation.js';import * as socialAccounts from '../services/socialAccounts.js';const router = Router();@@ -58,13 +58,7 @@ router.post('/', asyncHandler(async (req, res) => {// POST /bulk - Create multiple social accounts at oncerouter.post('/bulk', asyncHandler(async (req, res) => {- const { accounts: accountsData } = req.body;- if (!Array.isArray(accountsData) || accountsData.length === 0) {- throw new ServerError('accounts array is required', {- status: 400,- code: 'VALIDATION_ERROR'- });- }+ const { accounts: accountsData } = validateRequest(socialAccountBulkBodySchema, req.body);const results = [];for (const accountData of accountsData) {