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

test: require a schema when a route handler reads req.query (#10024)

Adam Eivy77f7a512a858
diff --git a/server/AGENTS.md b/server/AGENTS.md
index d2661dffeb..4b77ad88d0 100644
--- a/server/AGENTS.md
+++ b/server/AGENTS.md
@@ -8,6 +8,8 @@ These apply to Express/service/model code. Universal constraints (no try/catch o
- **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).
+- **A handler that reads `req.query` must validate the query object with a schema.** Same spellings and same trees, on GET/POST/PUT/PATCH/DELETE: `validateRequest(schema, req.query)` (or `validate` / `parseBody` / `safeParse` / `Schema.parse`), and the data argument must be the query object or a name assigned from it — not one field, and not `req.params`. `parsePagination(req.query)` only clamps limit/offset, so it does not satisfy the guard. `UNVALIDATED_QUERY_BASELINE` in that same test is the burn-down of handlers that already skip this; it may only shrink. Delete a line when the handler validates or disappears, and do not add one — a new reader gets a schema (#10024).
+
## 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/routeValidationConventions.test.js b/server/routeValidationConventions.test.js
index 73807a63e6..1d3b371041 100644
--- a/server/routeValidationConventions.test.js
+++ b/server/routeValidationConventions.test.js
@@ -1,5 +1,5 @@
/**
- * Repo-wide guard: a body-bearing route handler must validate `req.body`.
+ * Repo-wide guard: a route handler must validate the `req.body` or `req.query` it reads.
*
* Root `AGENTS.md` says every route input is validated through
* `lib/validation.js`, but a hand-rolled `if (!path) throw …` is easy to write
@@ -38,7 +38,17 @@
* and it only sees `router.<verb>(…)` call sites (not `router.route(…).post`).
* 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).
+ *
+ * ## Query strings (#10024)
+ *
+ * The same rule applies to `req.query` on `get|post|put|patch|delete` handlers in
+ * the same trees: the validation call's data argument must be the query object
+ * (or a name assigned from it, including a `...rest` copy), not one field.
+ * `parsePagination(req.query)` only clamps limit/offset, so it does not count.
+ * `UNVALIDATED_QUERY_BASELINE` is the burn-down of handlers that already read
+ * `req.query` without that call. It may only SHRINK — delete a line when the
+ * handler validates or disappears. A new reader gets a schema, not a new line.
+ * The lexer limits above apply to this scan too.
*/
import { describe, it, expect } from 'vitest';
@@ -61,16 +71,16 @@ 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|app|[A-Za-z]*Router)\.(post|put|patch)\s*\(/g;
-const READS_BODY = /\breq\.body\b/;
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;
-/** Names (besides `req.body`) bound to the raw body or to a rest-copy of it. */
-function bodyAliases(text) {
+/** Names bound to `source` (`req.body` / `req.query`) or to a rest-copy of it. */
+function inputAliases(text, source) {
+ const alias = new RegExp(
+ `\\b(?:const|let|var)\\s+(\\{[^}]*\\}|[A-Za-z_$][\\w$]*)\\s*=\\s*${source.replace('.', '\\.')}\\b`,
+ 'g',
+ );
const names = [];
- for (const m of text.matchAll(BODY_ALIAS)) {
+ for (const m of text.matchAll(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]);
}
@@ -89,35 +99,40 @@ function topLevelComma(args) {
return -1;
}
-/** True when some validation call in `text` receives the body as its DATA argument. */
-function validatesBody(text) {
- // A whole-body expression only: `req.body.name` is one field, not the body.
- const carriesBody = new RegExp(`\\b(?:req\\.body|${bodyAliases(text).join('|') || '(?!)'})\\b(?!\\s*(?:\\?\\.|\\.|\\[))`);
+/**
+ * True when some validation call in `text` receives `source` (`req.body` or
+ * `req.query`) as its DATA argument. A field read (`req.body.name`) does not count.
+ */
+function validatesInput(text, source) {
+ const escaped = source.replace('.', '\\.');
+ const carries = new RegExp(`\\b(?:${escaped}|${inputAliases(text, source).join('|') || '(?!)'})\\b(?!\\s*(?:\\?\\.|\\.|\\[))`);
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)` / `parseBody(schema, data, label)` take the data second, so
- // a body mentioned inside the schema expression does not count. `.safeParse(data)` /
+ // a value mentioned inside the schema expression does not count. `.safeParse(data)` /
// `Schema.parse(data)` take it first.
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;
+ if (carries.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) {
+/** `<VERB> <path>` for every matching handler that reads `source` without validating it. */
+function findUnvalidatedHandlers(src, { verbs, source }) {
+ const routeCall = new RegExp(`\\b(?:router|app|[A-Za-z]*Router)\\.(${verbs})\\s*\\(`, 'g');
+ const reads = new RegExp(`\\b${source.replace('.', '\\.')}\\b`);
const blanked = blankLiterals(src);
const hits = [];
- for (const match of blanked.matchAll(ROUTE_CALL)) {
+ for (const match of blanked.matchAll(routeCall)) {
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) || validatesBody(text)) continue;
+ if (!reads.test(text) || validatesInput(text, source)) 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}`);
@@ -125,6 +140,16 @@ export function findUnvalidatedBodyHandlers(src) {
return hits;
}
+/** `<VERB> <path>` for every handler in one file's source that reads `req.body` without validating it. */
+export function findUnvalidatedBodyHandlers(src) {
+ return findUnvalidatedHandlers(src, { verbs: 'post|put|patch', source: 'req.body' });
+}
+
+/** `<VERB> <path>` for every handler that reads `req.query` without validating the query object. */
+export function findUnvalidatedQueryHandlers(src) {
+ return findUnvalidatedHandlers(src, { verbs: 'get|post|put|patch|delete', source: 'req.query' });
+}
+
// `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'];
@@ -135,10 +160,173 @@ const trackedRouteSources = () => execFileSync('git', ['ls-files', ...SCANNED_PA
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}`)
+const scanWith = (finder) => trackedRouteSources().flatMap((file) => (
+ finder(readFileSync(join(SERVER_ROOT, file), 'utf8')).map((hit) => `${file} ${hit}`)
));
+const scanTree = () => scanWith(findUnvalidatedBodyHandlers);
+const scanQueries = () => scanWith(findUnvalidatedQueryHandlers);
+
+// Handlers that already read `req.query` without a schema call on the query
+// object. Shrink-only: delete a line when it validates or disappears; never add
+// one. Keyed by file + verb + path so an unrelated edit above the handler does
+// not churn the list (#10024).
+const UNVALIDATED_QUERY_BASELINE = [
+ 'lib/aiToolkit/routes/runs.js DELETE /',
+ 'lib/aiToolkit/routes/runs.js GET /',
+ 'routes/agentPersonalities.js GET /',
+ 'routes/agentTools.js DELETE /drafts/:draftId',
+ 'routes/agentTools.js GET /drafts',
+ 'routes/agentTools.js GET /feed',
+ 'routes/agentTools.js GET /post/:postId',
+ 'routes/agentTools.js GET /published',
+ 'routes/agentTools.js GET /rate-limits',
+ 'routes/agentTools.js GET /relevant-posts',
+ 'routes/agentTools.js GET /submolts',
+ 'routes/agentTools.js PUT /drafts/:draftId',
+ 'routes/albums.js GET /',
+ 'routes/appleHealth.js GET /correlation',
+ 'routes/appleHealth.js GET /metrics/:metricName',
+ 'routes/appleHealth.js GET /metrics/:metricName/daily',
+ 'routes/appleHealth.js GET /metrics/latest',
+ 'routes/apps/agents.js GET /:id/agents',
+ 'routes/apps/taskTypes.js GET /:id/work-items',
+ 'routes/apps/viteTls.js GET /:id/vite-host-check',
+ 'routes/artists.js GET /',
+ 'routes/authors.js GET /',
+ 'routes/autobiography.js GET /prompt',
+ 'routes/autobiography.js GET /stories',
+ 'routes/automationSchedules.js GET /',
+ 'routes/avatar.js GET /model.glb',
+ 'routes/brainCrud.js GET /admin',
+ 'routes/brainCrud.js GET /ideas',
+ 'routes/brainCrud.js GET /projects',
+ 'routes/brainDailyLog.js GET /daily-log',
+ 'routes/brainDigest.js GET /digests',
+ 'routes/brainDigest.js GET /reviews',
+ 'routes/brainImport.js GET /chatgpt/archive/:name',
+ 'routes/brainOnThisDay.js GET /on-this-day',
+ 'routes/browser.js GET /downloads/:name',
+ 'routes/calendar.js GET /agenda',
+ 'routes/calendar.js GET /events',
+ 'routes/calendar.js GET /google/oauth/callback',
+ 'routes/calendar.js GET /review/history',
+ 'routes/catalog.js DELETE /types/:id',
+ 'routes/catalog.js GET /ingredients/:id',
+ 'routes/catalog.js GET /ingredients/:id/details',
+ 'routes/catalog.js GET /scraps',
+ 'routes/catalog.js GET /sync',
+ 'routes/codeAnimation.js GET /accepted-assets',
+ 'routes/codeAnimation.js GET /projects',
+ 'routes/codeAnimation.js GET /projects/:id/history',
+ 'routes/cosInsightRoutes.js GET /activity-calendar',
+ 'routes/cosInsightRoutes.js GET /decisions',
+ 'routes/cosInsightRoutes.js GET /recent-tasks',
+ 'routes/cosLearningRoutes.js GET /digest/compare',
+ 'routes/cosLearningRoutes.js GET /learning/insights',
+ 'routes/cosScheduleRoutes.js GET /upcoming',
+ 'routes/cosTaskRoutes.js DELETE /tasks/:id',
+ 'routes/cosTemplateRoutes.js GET /templates/popular',
+ 'routes/cosWorkflowRoutes.js GET /workflow',
+ 'routes/creativeCommissions.js GET /',
+ 'routes/creativeDirector.js GET /:id',
+ 'routes/digital-twin/documents.js GET /documents',
+ 'routes/digital-twin/feedback.js GET /feedback/recent',
+ 'routes/eidoverseWorldRoutes.js DELETE /foundations/:id',
+ 'routes/eidoverseWorldRoutes.js GET /foundations/:id',
+ 'routes/eidoverseWorldRoutes.js POST /foundations/:id/adopt',
+ 'routes/featureAgents.js GET /:id/runs',
+ 'routes/feeds.js GET /items',
+ 'routes/feeds.js POST /items/read-all',
+ 'routes/games.js GET /',
+ 'routes/genome.js GET /epigenetic/compliance',
+ 'routes/genome.js GET /epigenetic/recommendations',
+ 'routes/harnesses.js GET /',
+ 'routes/harnesses.js POST /action',
+ 'routes/harnesses.js POST /models/refresh',
+ 'routes/identity.js GET /goals/:id/calendar-events',
+ 'routes/imageGen.js GET /models/:modelId/download',
+ 'routes/imageGen.js GET /regen/availability',
+ 'routes/imageGen.js GET /status',
+ 'routes/jira.js GET /instances/:instanceId/board-columns/:projectKey',
+ 'routes/jira.js GET /instances/:instanceId/projects/:projectKey/epics',
+ 'routes/jira.js GET /reports',
+ 'routes/localLlm.js GET /catalog',
+ 'routes/localLlm.js GET /loaded',
+ 'routes/loraTraining.js DELETE /runs/:id',
+ 'routes/loras.js GET /',
+ 'routes/loras.js GET /suggestions',
+ 'routes/meatspaceAlcoholRoutes.js GET /alcohol/daily',
+ 'routes/meatspaceNicotineRoutes.js GET /nicotine/daily',
+ 'routes/meatspacePostRoutes.js GET /post/morse/progress',
+ 'routes/meatspacePostRoutes.js GET /post/recommendations',
+ 'routes/meatspacePostRoutes.js GET /post/review/reps',
+ 'routes/meatspacePostRoutes.js GET /post/sessions',
+ 'routes/meatspacePostRoutes.js GET /post/stats',
+ 'routes/meatspacePostRoutes.js GET /post/training/entries',
+ 'routes/meatspacePostRoutes.js GET /post/training/stats',
+ 'routes/mediaCollections.js GET /',
+ 'routes/memory.js DELETE /:id',
+ 'routes/memory.js GET /:id/related',
+ 'routes/memory.js GET /sync',
+ 'routes/messages.js GET /drafts',
+ 'routes/messages.js POST /debug/test-token',
+ 'routes/moltworldTools.js GET /balance',
+ 'routes/moltworldTools.js GET /rate-limits',
+ 'routes/moltworldTools.js GET /status',
+ 'routes/moodBoard.js GET /',
+ 'routes/music.js POST /setup/runtime-install',
+ 'routes/musicVideo.js GET /',
+ 'routes/notifications.js GET /',
+ 'routes/openclaw.js GET /sessions/:id/messages',
+ 'routes/peerSync.js GET /cos-agent-archive',
+ 'routes/peerSync.js GET /integrity',
+ 'routes/peerSync.js GET /manifest',
+ 'routes/peerSync.js GET /record',
+ 'routes/peerSync.js GET /subscriptions',
+ 'routes/pipeline/covers.js GET /issues/:id/comic.pdf',
+ 'routes/pipeline/covers.js GET /series/:id/seasons/:seasonId/volume.pdf',
+ 'routes/pipeline/issues.js GET /issues/recent',
+ 'routes/pipeline/manuscript.js GET /series/:id/manuscript',
+ 'routes/pipeline/series.js GET /series',
+ 'routes/platformAccounts.js GET /',
+ 'routes/prompts.js DELETE /:stage',
+ 'routes/providers.js GET /codex/account',
+ 'routes/providers.js GET /codex/models',
+ 'routes/providers.js GET /fleet-host',
+ 'routes/providers.js GET /readiness',
+ 'routes/providers.js POST /readiness/serve-model',
+ 'routes/providers.js POST /readiness/setup',
+ 'routes/providers.js POST /runtimes/install',
+ 'routes/quotaBurn.js GET /',
+ 'routes/remoteDesktopViewer.js GET /',
+ 'routes/review.js GET /items',
+ 'routes/scaffold.js GET /directories',
+ 'routes/sharing.js GET /subscriptions',
+ 'routes/socialAccounts.js GET /',
+ 'routes/spotify.js GET /oauth/callback',
+ 'routes/sprites.js GET /',
+ 'routes/storyBuilder.js GET /',
+ 'routes/tracks.js GET /',
+ 'routes/tribe.js GET /care',
+ 'routes/tribe.js GET /outreach',
+ 'routes/tribe.js GET /people/:id/touchpoints',
+ 'routes/universeBuilder/canon.js GET /:id/characters/integrity',
+ 'routes/universeBuilder/crud.js GET /',
+ 'routes/uploads.js DELETE /',
+ 'routes/usage.js GET /claude-code',
+ 'routes/videoDownload.js GET /downloads',
+ 'routes/videoGen.js GET /ic-loras/:mode/download',
+ 'routes/videoGen.js GET /models/:modelId/download',
+ 'routes/videoGen.js GET /text-encoder/download',
+ 'routes/videoGen.js GET /text-encoders/:id/download',
+ 'routes/videoGen.js POST /setup/runtime-install',
+ 'routes/videoTimeline.js GET /projects',
+ 'routes/voice.js GET /voices',
+ 'routes/voicePublic.js GET /voices',
+ 'routes/writersRoom.js GET /exercises',
+];
+
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.
@@ -238,3 +426,65 @@ describe('the unvalidated-body recognizer', () => {
.toEqual(['POST /x']);
});
});
+
+describe('route handlers validate req.query (#10024)', () => {
+ it('has no unvalidated req.query read outside the burn-down baseline', () => {
+ const baseline = new Set(UNVALIDATED_QUERY_BASELINE);
+ const offenders = scanQueries().filter((key) => !baseline.has(key));
+ expect(
+ offenders,
+ 'These handlers read `req.query` with no schema on the query object. Add a Zod schema '
+ + 'and call `validateRequest(schema, req.query)` (toolkit routes: `lib/aiToolkit/validation.js`). '
+ + 'Do NOT add a line to UNVALIDATED_QUERY_BASELINE — that list only shrinks.\n'
+ + `Offenders:\n ${offenders.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ it('only baselines handlers that still exist and are still unvalidated', () => {
+ const live = new Set(scanQueries());
+ const stale = UNVALIDATED_QUERY_BASELINE.filter((key) => !live.has(key));
+ expect(
+ stale,
+ `These baseline entries are compliant or gone — delete them from UNVALIDATED_QUERY_BASELINE:\n ${stale.join('\n ')}`,
+ ).toEqual([]);
+ expect(new Set(UNVALIDATED_QUERY_BASELINE).size).toBe(UNVALIDATED_QUERY_BASELINE.length);
+ expect([...UNVALIDATED_QUERY_BASELINE].sort()).toEqual(UNVALIDATED_QUERY_BASELINE);
+ });
+});
+
+describe('the unvalidated-query recognizer', () => {
+ it('flags a query read that validates req.params, one field, or only the body (#10024)', () => {
+ expect(findUnvalidatedQueryHandlers("router.get('/x', (req, res) => { use(req.query.limit); });"))
+ .toEqual(['GET /x']);
+ expect(findUnvalidatedQueryHandlers("router.delete('/x/:id', (req, res) => { use(req.query.force); });"))
+ .toEqual(['DELETE /x/:id']);
+ expect(findUnvalidatedQueryHandlers("router.get('/x/:id', (req, res) => { validateRequest(idSchema, req.params); use(req.query.view); });"))
+ .toEqual(['GET /x/:id']);
+ expect(findUnvalidatedQueryHandlers("router.get('/x', (req, res) => { validateRequest(limitSchema, req.query.limit); });"))
+ .toEqual(['GET /x']);
+ expect(findUnvalidatedQueryHandlers("router.post('/x', (req, res) => { validateRequest(bodySchema, req.body); use(req.query.dryRun); });"))
+ .toEqual(['POST /x']);
+ // limit/offset clamping is not a schema for the query object.
+ expect(findUnvalidatedQueryHandlers("router.get('/x', (req, res) => { const page = parsePagination(req.query); });"))
+ .toEqual(['GET /x']);
+ });
+
+ it('accepts a query object validated directly, through an alias, a spread, or a rest copy', () => {
+ for (const call of [
+ 'validateRequest(fooSchema, req.query)',
+ 'validate(fooSchema, req.query)',
+ 'fooSchema.safeParse(req.query)',
+ 'fooQuerySchema.parse(req.query)',
+ 'const query = req.query; validateRequest(fooSchema, query);',
+ 'validateRequest(fooSchema, { ...req.query, id: req.params.id });',
+ 'const { token, ...rest } = req.query; validateRequest(fooSchema, rest);',
+ ]) {
+ expect(findUnvalidatedQueryHandlers(`router.get('/x', (req, res) => { ${call}; });`), call).toEqual([]);
+ }
+ });
+
+ it('ignores handlers that never read the query and mentions inside comments or strings', () => {
+ expect(findUnvalidatedQueryHandlers("router.get('/x', (req, res) => { res.json({ ok: true }); });")).toEqual([]);
+ expect(findUnvalidatedQueryHandlers("router.get('/x', (req, res) => { // req.query is ignored\n res.json('req.query'); });")).toEqual([]);
+ });
+});