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: validate request bodies on the aiToolkit prompt/provider-status routes and the CoS runner (#10024)

Adam Eivye81d19005c7f
diff --git a/server/AGENTS.md b/server/AGENTS.md
index 706594d7af..d2661dffeb 100644
--- a/server/AGENTS.md
+++ b/server/AGENTS.md
@@ -6,7 +6,7 @@ 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).
+- **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/`, the toolkit's `lib/aiToolkit/routes/` (schemas in `lib/aiToolkit/validation.js`, which cannot import `lib/validation.js`) and the CoS runner's `cos-runner/index.js` (`requestSchemas.js`, answering its own `{ error }` 400) 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
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 3430b52af4..69581788e4 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -36,6 +36,7 @@ import { usableAgentPid, runnerAgentLivenessFields } from '../lib/runnerAgentLiv
import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';
import { armForceKill as armForceKillShared } from './forceKill.js';
import { createTuiExitHandler } from './tuiExit.js';
+import { bodyErrorMessage, btwBodySchema, pauseBodySchema, spawnBodySchema, spawnTuiBodySchema } from './requestSchemas.js';
import { createRunnerShutdown, registerRunnerShutdownSignals } from './shutdown.js';
import { createHttpDrain } from '../lib/httpDrain.js';
import { PORTS } from '../lib/ports.js';
@@ -212,6 +213,8 @@ app.get('/agents', async (req, res) => {
*/
app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
assertDatabaseAdmission();
+ const body = spawnTuiBodySchema.safeParse(req.body ?? {});
+ if (!body.success) return res.status(400).json({ error: bodyErrorMessage(body.error) });
const {
agentId,
taskId,
@@ -226,7 +229,7 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
cols = 80,
rows = 24,
doneSentinelPath = null,
- } = req.body;
+ } = body.data;
// Name the offending field. A single opaque "missing or invalid fields" 400
// sent a grok-tui agent to the zombie reaper with no shell and no clue why —
@@ -242,9 +245,6 @@ app.post('/spawn-tui', lifecycle.spawnRoute(async (req, res) => {
error: `Command not allowed: ${command}. Permitted commands: ${[...ALLOWED_COMMANDS].join(', ')}`
});
}
- if (!Array.isArray(args)) {
- return res.status(400).json({ error: 'Invalid args: expected an array' });
- }
if (activeAgents.has(agentId)) {
return res.status(409).json({ error: `Agent ${agentId} is already running` });
}
@@ -457,6 +457,8 @@ app.get('/agents/:agentId/stats', async (req, res) => {
*/
app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
assertDatabaseAdmission();
+ const body = spawnBodySchema.safeParse(req.body ?? {});
+ if (!body.success) return res.status(400).json({ error: bodyErrorMessage(body.error) });
const {
agentId,
taskId,
@@ -472,7 +474,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
cliArgs,
// Legacy: Claude-specific (deprecated)
claudePath = process.env.CLAUDE_PATH || 'claude'
- } = req.body;
+ } = body.data;
if (!agentId || !taskId || !prompt) {
return res.status(400).json({ error: 'Missing required fields: agentId, taskId, prompt' });
@@ -488,18 +490,10 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {
});
}
command = cliCommand;
- // Default to empty args if cliArgs not provided
+ // cliArgs is an array or a single string (the schema rejects anything else);
+ // default to empty args when not provided.
const args = cliArgs ?? [];
- // Normalize cliArgs to an array
- if (Array.isArray(args)) {
- spawnArgs = args;
- } else if (typeof args === 'string') {
- spawnArgs = [args];
- } else {
- return res.status(400).json({
- error: 'Invalid cliArgs: expected an array or string'
- });
- }
+ spawnArgs = Array.isArray(args) ? args : [args];
} else {
// Legacy: Claude-specific args
command = claudePath;
@@ -803,7 +797,9 @@ app.post('/kill/:agentId', async (req, res) => {
*/
app.post('/pause/:agentId', async (req, res) => {
const { agentId } = req.params;
- const { reason = null } = req.body || {};
+ const body = pauseBodySchema.safeParse(req.body ?? {});
+ if (!body.success) return res.status(400).json({ error: bodyErrorMessage(body.error) });
+ const { reason = null } = body.data;
const agent = activeAgents.get(agentId);
if (!agent) {
@@ -857,16 +853,15 @@ app.post('/terminate-all', async (req, res) => {
*/
app.post('/btw/:agentId', async (req, res) => {
const { agentId } = req.params;
- const { message } = req.body;
const agent = activeAgents.get(agentId);
if (!agent) {
return res.status(404).json({ error: 'Agent not found or not running' });
}
- if (!message || typeof message !== 'string') {
- return res.status(400).json({ error: 'Missing or invalid message' });
- }
+ const body = btwBodySchema.safeParse(req.body ?? {});
+ if (!body.success) return res.status(400).json({ error: bodyErrorMessage(body.error) });
+ const { message } = body.data;
// Derive workspace from the agent's known record, not from request body
const agentWorkspace = agent.workspacePath;
diff --git a/server/cos-runner/requestSchemas.js b/server/cos-runner/requestSchemas.js
new file mode 100644
index 0000000000..95aaa22921
--- /dev/null
+++ b/server/cos-runner/requestSchemas.js
@@ -0,0 +1,62 @@
+/**
+ * Request-body schemas for the CoS runner's HTTP API (#10024).
+ *
+ * The runner is a separate PM2 process with its own Express app, so it cannot
+ * use `validateRequest` (which throws through the main server's error
+ * middleware). Its handlers call `schema.safeParse(req.body)` and answer a
+ * failure with the same `{ error }` 400 shape the hand-written field checks
+ * already used, via `bodyErrorMessage`.
+ *
+ * The schemas pin TYPES only. Presence checks stay in the handlers because
+ * their messages name the missing field (a single opaque "invalid body" once
+ * sent a grok-tui agent to the zombie reaper with no clue why), and
+ * `JSON.stringify` on the server side drops `undefined`, so every field is
+ * absent-or-typed; `null` is tolerated where a caller legitimately sends it.
+ */
+
+import { z } from 'zod';
+
+const optionalString = z.string().nullish();
+// Free-form maps composed server-side (provider env, auth descriptor); the
+// downstream env builder owns their contents, the schema only rejects a
+// wrong-typed top level (array, string).
+const looseRecord = z.record(z.string(), z.unknown()).nullish();
+
+export const spawnTuiBodySchema = z.object({
+ agentId: optionalString,
+ taskId: optionalString,
+ sessionId: optionalString,
+ command: optionalString,
+ args: z.array(z.string()).optional(),
+ workspacePath: optionalString,
+ envVars: looseRecord,
+ providerAuth: looseRecord,
+ cols: z.number().int().min(1).optional(),
+ rows: z.number().int().min(1).optional(),
+ doneSentinelPath: optionalString,
+});
+
+export const spawnBodySchema = z.object({
+ agentId: optionalString,
+ taskId: optionalString,
+ prompt: optionalString,
+ workspacePath: optionalString,
+ model: optionalString,
+ envVars: looseRecord,
+ providerAuth: looseRecord,
+ cliCommand: optionalString,
+ cliArgs: z.union([z.array(z.string()), z.string()]).nullish(),
+ claudePath: optionalString,
+});
+
+export const pauseBodySchema = z.object({ reason: optionalString });
+
+export const btwBodySchema = z.object({ message: z.string().min(1, 'message is required') });
+
+/** One-line 400 message naming every offending field. */
+export function bodyErrorMessage(error) {
+ const detail = error.issues
+ .map((issue) => (issue.path.length ? `${issue.path.join('.')}: ${issue.message}` : issue.message))
+ .join('; ');
+ return `Invalid request body: ${detail}`;
+}
diff --git a/server/cos-runner/requestSchemas.test.js b/server/cos-runner/requestSchemas.test.js
new file mode 100644
index 0000000000..36de59be2d
--- /dev/null
+++ b/server/cos-runner/requestSchemas.test.js
@@ -0,0 +1,27 @@
+import { describe, it, expect } from 'vitest';
+import { bodyErrorMessage, btwBodySchema, spawnBodySchema, spawnTuiBodySchema } from './requestSchemas.js';
+
+// #10024 — the runner spawns processes from these bodies, so a wrong-typed
+// field must bounce as a 400 before it reaches the env builder or the spawn.
+describe('cos-runner request schemas', () => {
+ it('accepts the body the server actually sends (undefined dropped, nulls tolerated)', () => {
+ expect(spawnBodySchema.safeParse({
+ agentId: 'a', taskId: 't', prompt: 'p', workspacePath: null, model: null,
+ envVars: { A: '1' }, providerAuth: { id: 'x' }, cliCommand: 'claude', cliArgs: ['-p'],
+ }).success).toBe(true);
+ expect(spawnTuiBodySchema.safeParse({
+ agentId: 'a', taskId: 't', command: 'claude', args: [], cols: 80, rows: 24, providerAuth: null, doneSentinelPath: null,
+ }).success).toBe(true);
+ });
+
+ it('rejects wrong-typed fields and names them', () => {
+ const bad = spawnBodySchema.safeParse({ agentId: { $ne: 1 }, cliArgs: 5, envVars: ['x'] });
+ expect(bad.success).toBe(false);
+ const message = bodyErrorMessage(bad.error);
+ for (const field of ['agentId:', 'cliArgs:', 'envVars:']) expect(message).toContain(field);
+ expect(spawnTuiBodySchema.safeParse({ args: 'rm -rf' }).success).toBe(false);
+ expect(spawnTuiBodySchema.safeParse({ cols: 0 }).success).toBe(false);
+ expect(btwBodySchema.safeParse({ message: '' }).success).toBe(false);
+ expect(btwBodySchema.safeParse({}).success).toBe(false);
+ });
+});
diff --git a/server/cos-runner/shutdown.test.js b/server/cos-runner/shutdown.test.js
index a1f63e219e..a9054e5a5d 100644
--- a/server/cos-runner/shutdown.test.js
+++ b/server/cos-runner/shutdown.test.js
@@ -13,6 +13,7 @@ import { killProcessTree } from '../lib/bufferedSpawn.js';
import { createRunnerShutdown, registerRunnerShutdownSignals } from './shutdown.js';
import { createTuiExitHandler } from './tuiExit.js';
import { armForceKill } from './forceKill.js';
+import * as requestSchemas from './requestSchemas.js';
import { createHttpDrain } from '../lib/httpDrain.js';
const deferred = () => {
@@ -75,6 +76,7 @@ function runner(assertDatabaseAdmission = vi.fn()) {
readFile: async path => files.get(path) ?? '{}', writeFile,
atomicWrite: (path, data) => writeFile(path, typeof data === 'string' ? data : JSON.stringify(data, null, 2)),
withState, drainState,
+ ...requestSchemas,
createRunnerShutdown, registerRunnerShutdownSignals, createTuiExitHandler, createHttpDrain,
armForceKillShared: armForceKill, killProcessTree, spawn, pty,
createAgentSentinelAccess,
diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.js
index 7f0f1896b9..79b0e8724d 100644
--- a/server/lib/aiToolkit/index.js
+++ b/server/lib/aiToolkit/index.js
@@ -134,8 +134,7 @@ export function createAIToolkit(config = {}) {
let providerStatusRouter = null;
if (providerStatusService) {
- // providerStatus has no 4xx error paths today, so it takes no ServerError.
- providerStatusRouter = createProviderStatusRoutes(providerStatusService, { asyncHandler });
+ providerStatusRouter = createProviderStatusRoutes(providerStatusService, { asyncHandler, ServerError });
}
return {
diff --git a/server/lib/aiToolkit/routes/bodyValidation.test.js b/server/lib/aiToolkit/routes/bodyValidation.test.js
new file mode 100644
index 0000000000..7361b90b97
--- /dev/null
+++ b/server/lib/aiToolkit/routes/bodyValidation.test.js
@@ -0,0 +1,84 @@
+import { describe, it, expect, vi } from 'vitest';
+import express from 'express';
+import { request } from '../../testHelper.js';
+import { createPromptsRoutes } from './prompts.js';
+import { createProviderStatusRoutes } from './providerStatus.js';
+
+// #10024 — the prompt-write and usage-limit routes used to hand `req.body`
+// straight to services that write prompt files / regex-match a string. Pinned
+// through the standalone defaults (no host ServerError), which is also the
+// shape a standalone toolkit consumer sees.
+const appFor = (path, router) => {
+ const app = express();
+ app.use(express.json());
+ app.use(path, router);
+ return app;
+};
+
+const promptsService = () => ({
+ getStage: vi.fn().mockReturnValue({ name: 'x' }),
+ getStageTemplate: vi.fn().mockResolvedValue('tpl'),
+ getVariable: vi.fn().mockReturnValue({ content: 'c' }),
+ updateStageConfig: vi.fn().mockResolvedValue(),
+ updateStageTemplate: vi.fn().mockResolvedValue(),
+ previewPrompt: vi.fn().mockResolvedValue('rendered'),
+ createVariable: vi.fn().mockResolvedValue(),
+ updateVariable: vi.fn().mockResolvedValue(),
+});
+
+describe('toolkit prompts routes validate their bodies', () => {
+ it('rejects wrong-typed bodies with a 400 VALIDATION_ERROR and never reaches the service', async () => {
+ const svc = promptsService();
+ const app = appFor('/api/prompts', createPromptsRoutes(svc));
+
+ const cases = [
+ ['put', '/api/prompts/stages/x', { config: 'nope' }],
+ ['put', '/api/prompts/stages/x', { template: 42 }],
+ ['post', '/api/prompts/stages/x/preview', ['not', 'a', 'map']],
+ ['post', '/api/prompts/variables', { key: 'bad key!', content: 'c' }],
+ ['post', '/api/prompts/variables', { content: 'no key' }],
+ ['put', '/api/prompts/variables/k', ['x']],
+ ];
+ for (const [verb, url, body] of cases) {
+ const res = await request(app)[verb](url).send(body);
+ expect(res.status, `${verb} ${url} ${JSON.stringify(body)}`).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ }
+ expect(svc.updateStageConfig).not.toHaveBeenCalled();
+ expect(svc.updateStageTemplate).not.toHaveBeenCalled();
+ expect(svc.previewPrompt).not.toHaveBeenCalled();
+ expect(svc.createVariable).not.toHaveBeenCalled();
+ expect(svc.updateVariable).not.toHaveBeenCalled();
+ });
+
+ it('still passes valid bodies through, keeping the variable payload beside its key', async () => {
+ const svc = promptsService();
+ const app = appFor('/api/prompts', createPromptsRoutes(svc));
+
+ expect((await request(app).put('/api/prompts/stages/x').send({ config: { model: 'm' }, template: 't' })).status).toBe(200);
+ expect(svc.updateStageConfig).toHaveBeenCalledWith('x', { model: 'm' });
+ expect(svc.updateStageTemplate).toHaveBeenCalledWith('x', 't');
+
+ expect((await request(app).post('/api/prompts/stages/x/preview').send({ a: 1 })).status).toBe(200);
+ expect(svc.previewPrompt).toHaveBeenCalledWith('x', { a: 1 });
+
+ expect((await request(app).post('/api/prompts/variables').send({ key: 'my-var', content: 'c', name: 'N' })).status).toBe(201);
+ expect(svc.createVariable).toHaveBeenCalledWith('my-var', { content: 'c', name: 'N' });
+ });
+});
+
+describe('toolkit provider-status usage-limit route validates its body', () => {
+ it('400s a non-string waitTime instead of letting the status service throw a 500', async () => {
+ const status = { markUsageLimit: vi.fn().mockResolvedValue({ ok: true }) };
+ const app = appFor('/api/status', createProviderStatusRoutes(status));
+
+ const bad = await request(app).post('/api/status/p1/usage-limit').send({ waitTime: { hours: 1 } });
+ expect(bad.status).toBe(400);
+ expect(bad.body.code).toBe('VALIDATION_ERROR');
+ expect(status.markUsageLimit).not.toHaveBeenCalled();
+
+ const ok = await request(app).post('/api/status/p1/usage-limit').send({ message: 'm', waitTime: '2 hours' });
+ expect(ok.status).toBe(200);
+ expect(status.markUsageLimit).toHaveBeenCalledWith('p1', { message: 'm', waitTime: '2 hours' });
+ });
+});
diff --git a/server/lib/aiToolkit/routes/prompts.js b/server/lib/aiToolkit/routes/prompts.js
index 53a27fd417..1eaf801901 100644
--- a/server/lib/aiToolkit/routes/prompts.js
+++ b/server/lib/aiToolkit/routes/prompts.js
@@ -1,5 +1,12 @@
import { Router } from 'express';
import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';
+import {
+ promptPreviewBodySchema,
+ promptStageUpdateBodySchema,
+ promptVariableCreateBodySchema,
+ promptVariableUpdateBodySchema,
+ validate
+} from '../validation.js';
export function createPromptsRoutes(promptsService, options = {}) {
const router = Router();
@@ -9,6 +16,14 @@ export function createPromptsRoutes(promptsService, options = {}) {
// Standalone, the toolkit's own defaults serialize the same envelope.
const { asyncHandler = defaultAsyncHandler, ServerError = ToolkitHttpError } = options;
+ const parseBody = (schema, body, label) => {
+ const result = validate(schema, body);
+ if (!result.success) {
+ throw new ServerError(`Invalid ${label}`, { status: 400, code: 'VALIDATION_ERROR', context: { details: result.errors } });
+ }
+ return result.data;
+ };
+
router.get('/stages', asyncHandler(async (req, res) => {
const stages = promptsService.getStages();
res.json(stages);
@@ -26,7 +41,7 @@ export function createPromptsRoutes(promptsService, options = {}) {
}));
router.put('/stages/:name', asyncHandler(async (req, res) => {
- const { config, template } = req.body;
+ const { config, template } = parseBody(promptStageUpdateBodySchema, req.body, 'stage data');
if (config) {
await promptsService.updateStageConfig(req.params.name, config);
@@ -43,7 +58,7 @@ export function createPromptsRoutes(promptsService, options = {}) {
}));
router.post('/stages/:name/preview', asyncHandler(async (req, res) => {
- const preview = await promptsService.previewPrompt(req.params.name, req.body);
+ const preview = await promptsService.previewPrompt(req.params.name, parseBody(promptPreviewBodySchema, req.body, 'preview data'));
res.json({ preview });
}));
@@ -63,11 +78,7 @@ export function createPromptsRoutes(promptsService, options = {}) {
}));
router.post('/variables', asyncHandler(async (req, res) => {
- const { key, ...data } = req.body;
-
- if (!key) {
- throw new ServerError('Variable key is required', { status: 400 });
- }
+ const { key, ...data } = parseBody(promptVariableCreateBodySchema, req.body, 'variable data');
await promptsService.createVariable(key, data);
const created = promptsService.getVariable(key);
@@ -75,7 +86,7 @@ export function createPromptsRoutes(promptsService, options = {}) {
}));
router.put('/variables/:key', asyncHandler(async (req, res) => {
- await promptsService.updateVariable(req.params.key, req.body);
+ await promptsService.updateVariable(req.params.key, parseBody(promptVariableUpdateBodySchema, req.body, 'variable data'));
const updated = promptsService.getVariable(req.params.key);
res.json(updated);
}));
diff --git a/server/lib/aiToolkit/routes/providerStatus.js b/server/lib/aiToolkit/routes/providerStatus.js
index ff0cb6fb99..96679a92e4 100644
--- a/server/lib/aiToolkit/routes/providerStatus.js
+++ b/server/lib/aiToolkit/routes/providerStatus.js
@@ -1,12 +1,14 @@
import { Router } from 'express';
-import { defaultAsyncHandler } from '../internal/httpError.js';
+import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';
+import { providerUsageLimitBodySchema, validate } from '../validation.js';
export function createProviderStatusRoutes(providerStatusService, options = {}) {
const router = Router();
// Standalone default serializes thrown errors into the canonical envelope;
- // PortOS injects its own asyncHandler. This router has no 4xx throws of its
- // own, but a rejected service call still lands in the same JSON shape.
- const { asyncHandler = defaultAsyncHandler } = options;
+ // PortOS injects its own asyncHandler + ServerError, so a body-validation 400
+ // normalizes into the canonical envelope; standalone, the toolkit defaults
+ // serialize the same shape.
+ const { asyncHandler = defaultAsyncHandler, ServerError = ToolkitHttpError } = options;
router.get('/', asyncHandler(async (req, res) => {
const statuses = providerStatusService.getAllStatuses();
@@ -29,7 +31,11 @@ export function createProviderStatusRoutes(providerStatusService, options = {})
}));
router.post('/:id/usage-limit', asyncHandler(async (req, res) => {
- const { message, waitTime } = req.body;
+ const result = validate(providerUsageLimitBodySchema, req.body ?? {});
+ if (!result.success) {
+ throw new ServerError('Invalid usage-limit data', { status: 400, code: 'VALIDATION_ERROR', context: { details: result.errors } });
+ }
+ const { message, waitTime } = result.data;
const status = await providerStatusService.markUsageLimit(req.params.id, {
message,
waitTime
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 9ede39facd..596b859427 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -352,6 +352,27 @@ export const runSchema = z.object({
timeout: z.number().int().min(MIN_TIMEOUT).max(MAX_TIMEOUT).optional()
});
+// Prompt routes (routes/prompts.js). Free-form maps stay `z.record` because the
+// stage config / variable / preview payloads are user-defined shapes; the point
+// is that a wrong-typed top level (array, string, `config: "x"`) bounces as a
+// 400 instead of reaching the file-writing service.
+export const promptStageUpdateBodySchema = z.object({
+ config: z.record(z.string(), z.unknown()).optional(),
+ template: z.string().optional()
+});
+export const promptPreviewBodySchema = z.record(z.string(), z.unknown());
+export const promptVariableCreateBodySchema = z.object({
+ key: z.string().regex(/^[A-Za-z0-9_-]+$/, 'invalid variable key').max(80)
+}).catchall(z.unknown());
+export const promptVariableUpdateBodySchema = z.record(z.string(), z.unknown());
+
+// POST /api/provider-status/:id/usage-limit — `waitTime` is a display string the
+// status service regex-matches, so a non-string would throw a 500 there.
+export const providerUsageLimitBodySchema = z.object({
+ message: z.string().optional(),
+ waitTime: z.string().optional()
+});
+
export function validate(schema, data) {
const result = schema.safeParse(data);
if (result.success) {
diff --git a/server/routeValidationConventions.test.js b/server/routeValidationConventions.test.js
index fd76ba3886..73807a63e6 100644
--- a/server/routeValidationConventions.test.js
+++ b/server/routeValidationConventions.test.js
@@ -9,12 +9,16 @@
*
* ## The rule
*
- * Every `router.post|put|patch(…)` call under `server/routes/` whose handler
- * text mentions `req.body` must also contain one of
+ * Every `router.post|put|patch(…)` call under `server/routes/` (and the
+ * vendored toolkit's `lib/aiToolkit/routes/`, plus the CoS runner's own
+ * `app.post|put|patch(…)` in `cos-runner/index.js`) 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(…)`.
+ * - `validate(schema, …)` (the non-throwing sibling providers/social routes use),
+ * - `parseBody(schema, …)` (the toolkit prompts router's local wrapper over `validate`), or
+ * - `<name>Schema….safeParse(…)` / `<name>Schema….parse(…)` (the CoS runner's shape:
+ * it is a separate process, so it answers its own `{ error }` 400).
*
* ## Allowlist
*
@@ -32,10 +36,9 @@
* 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 and the
- * aiToolkit/cos-runner trees are follow-ups (#10024).
+ * The toolkit cannot import `lib/validation.js` (self-contained), so its schemas
+ * live in `lib/aiToolkit/validation.js`; the runner's are `cos-runner/requestSchemas.js`.
+ * Out of scope for now: `req.query` reads, a follow-up (#10024).
*/
import { describe, it, expect } from 'vitest';
@@ -58,9 +61,9 @@ const ALLOWED_UNVALIDATED = new Map([
['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 ROUTE_CALL = /\b(?:router|app|[A-Za-z]*Router)\.(post|put|patch)\s*\(/g;
const READS_BODY = /\breq\.body\b/;
-const VALIDATE_CALL = /\bvalidateRequest\s*\(|\bvalidate\s*\(|\.safeParse\s*\(|[Ss]chema\w*\.parse\s*\(/g;
+const VALIDATE_CALL = /\bvalidateRequest\s*\(|\bvalidate\s*\(|\bparseBody\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;
@@ -95,10 +98,10 @@ function validatesBody(text) {
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
+ // `validateRequest(schema, data)` / `validate(schema, data)` / `parseBody(schema, data, label)` 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 schemaFirst = /^(?:validateRequest|validate|parseBody)\b/.test(call[0].trim());
const dataArg = schemaFirst ? args.slice(topLevelComma(args) + 1) : args;
if (carriesBody.test(dataArg)) return true;
}
@@ -122,7 +125,11 @@ export function findUnvalidatedBodyHandlers(src) {
return hits;
}
-const trackedRouteSources = () => execFileSync('git', ['ls-files', 'routes'], {
+// `routes/` plus the two out-of-tree HTTP surfaces (#10024): the vendored toolkit's
+// routers and the CoS runner's standalone Express app.
+const SCANNED_PATHS = ['routes', 'lib/aiToolkit/routes', 'cos-runner/index.js'];
+
+const trackedRouteSources = () => execFileSync('git', ['ls-files', ...SCANNED_PATHS], {
cwd: SERVER_ROOT,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
@@ -132,7 +139,7 @@ const scanTree = () => trackedRouteSources().flatMap((file) => (
findUnvalidatedBodyHandlers(readFileSync(join(SERVER_ROOT, file), 'utf8')).map((hit) => `${file} ${hit}`)
));
-describe('route handlers validate req.body (#9950)', () => {
+describe('route handlers validate req.body (#9950, #10024)', () => {
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);
@@ -212,6 +219,17 @@ describe('the unvalidated-body recognizer', () => {
}
});
+ it('covers the toolkit routers and the CoS runner app (#10024)', () => {
+ const files = trackedRouteSources();
+ expect(files).toContain('lib/aiToolkit/routes/prompts.js');
+ expect(files).toContain('cos-runner/index.js');
+ expect(findUnvalidatedBodyHandlers("app.post('/spawn', lifecycle.spawnRoute(async (req, res) => { const { agentId } = req.body; }));"))
+ .toEqual(['POST /spawn']);
+ for (const call of ['spawnBodySchema.safeParse(req.body ?? {})', "parseBody(promptStageUpdateBodySchema, req.body, 'stage data')"]) {
+ expect(findUnvalidatedBodyHandlers(`router.put('/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([]);