A local-first multi-agent app development platform, built on PenguinHarness
fix(server): paging params reject trailing garbage; drop dead design-doc codes (#410)
Myriad-Dreamind98208b4badc
diff --git a/changelog/unreleased/2026-08-23-paging-params-reject-trailing-garbage.md b/changelog/unreleased/2026-08-23-paging-params-reject-trailing-garbage.mdnew file mode 100644index 00000000..1e99ef92--- /dev/null+++ b/changelog/unreleased/2026-08-23-paging-params-reject-trailing-garbage.md@@ -0,0 +1,29 @@+# Paging query params reject trailing garbage, and route comments drop their design-doc codes++- **Date:** 2026-08-23+- **Type:** fix+- **Scope:** `server`+- **PR:** [#410](https://github.com/Prism-Shadow/penguin-harness/pull/410)++[中文版](2026-08-23-paging-params-reject-trailing-garbage.zh.md)++`offset` and `limit` were parsed with `Number.parseInt` and then only range-checked, so a+value that merely started with digits was accepted: `?limit=200abc` paged at 200 and+`?limit=1e3` paged at 1. Both now go through the same digits-only parse+`positiveIntParam` already used, and answer 400 instead. Thirteen route comments that+cited design-session item codes (`FD-1`, `FD-3`, `FD-4`) were rewritten to state the rule+they were pointing at.++## Details++- `paginationQuery` and `optionalPagingQuery` share one `parseNonNegativeInt` helper with+ `positiveIntParam`: a decimal digit run that lands on a safe integer, or a 400. Leading+ signs, whitespace, decimal points, hex and exponent forms are all rejected.+- The accepted ranges are unchanged — `offset` >= 0 (default 0), `limit` 1–1000 (default+ 200 for the Trace pagination helper) — as is the "offset requires limit" rule and the+ both-absent `null` return.+- Affected endpoints: the Trace message and event pages, the usage error detail table, and+ the Session and Trace list endpoints.+- The route comments now name the invariant directly ("id validation happens before any+ path construction: prevents agentId path traversal for cross-Project privilege+ escalation") rather than deferring to a code no reader at `HEAD` can resolve.diff --git a/changelog/unreleased/2026-08-23-paging-params-reject-trailing-garbage.zh.md b/changelog/unreleased/2026-08-23-paging-params-reject-trailing-garbage.zh.mdnew file mode 100644index 00000000..457eaa2e--- /dev/null+++ b/changelog/unreleased/2026-08-23-paging-params-reject-trailing-garbage.zh.md@@ -0,0 +1,24 @@+# 分页查询参数拒绝尾随垃圾字符,路由注释去掉设计文档编号++- **Date:** 2026-08-23+- **Type:** fix+- **Scope:** `server`+- **PR:** [#410](https://github.com/Prism-Shadow/penguin-harness/pull/410)++[English](2026-08-23-paging-params-reject-trailing-garbage.md)++`offset` 和 `limit` 此前用 `Number.parseInt` 解析后只做范围检查,因此只要开头是数字就会被接受:+`?limit=200abc` 按 200 分页,`?limit=1e3` 按 1 分页。两者现在都走 `positiveIntParam` 早已使用的+纯数字解析,改为返回 400。十三处引用设计会话条目编号(`FD-1`、`FD-3`、`FD-4`)的路由注释被改写为+直接陈述它们所指向的规则。++## 细节++- `paginationQuery` 和 `optionalPagingQuery` 与 `positiveIntParam` 共用同一个+ `parseNonNegativeInt`:要么是落在安全整数范围内的十进制数字串,要么返回 400。前导正负号、+ 空白、小数点、十六进制和指数写法一律拒绝。+- 接受的取值范围不变——`offset` >= 0(默认 0),`limit` 1–1000(Trace 分页助手默认 200)——+ "给了 offset 就必须给 limit" 的规则和两者都缺省时返回 `null` 的行为同样不变。+- 受影响的端点:Trace 消息与事件分页、用量错误明细表,以及 Session 和 Trace 列表端点。+- 路由注释现在直接点明不变量("id 校验发生在任何路径拼接之前:防止 agentId 路径穿越导致的+ 跨 Project 提权"),而不是转而引用一个在 `HEAD` 上无从解析的编号。diff --git a/packages/server/src/http/routes/agent-config.ts b/packages/server/src/http/routes/agent-config.tsindex b8c48981..35fc84b1 100644--- a/packages/server/src/http/routes/agent-config.ts+++ b/packages/server/src/http/routes/agent-config.ts@@ -29,7 +29,7 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();app.get("/", async (c) => {- // Id validation happens before any path construction (FD-4: prevents agentId path traversal for cross-Project privilege escalation).+ // Id validation happens before any path construction: prevents agentId path traversal for cross-Project privilege escalation.const projectId = requireValidId(c, "projectId");const agentId = requireValidId(c, "agentId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);diff --git a/packages/server/src/http/routes/agent-traces.ts b/packages/server/src/http/routes/agent-traces.tsindex 758c480e..0bcea8c7 100644--- a/packages/server/src/http/routes/agent-traces.ts+++ b/packages/server/src/http/routes/agent-traces.ts@@ -14,7 +14,7 @@* The listing consults the sessions table read-only (titles, archived, workspace,* client); discovery itself still comes from the Trace directory tree via the index.* - GET /api/projects/:p/agents/:a/traces/:sessionId/:index (including /analysis, /download) —- * read-only Trace detail endpoints (FD-3): locate the Trace file directly by+ * read-only Trace detail endpoints: locate the Trace file directly by* (projectId, agentId, sessionId), without depending on the sessions table for* tracking — any entry visible in the directory tree (subagent child Sessions,* CLI-created Sessions) can be opened and read; access is enforced by requireProjectAccess.@@ -52,7 +52,7 @@ export function agentTracesRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();app.get("/", async (c) => {- // Id validation happens before any path construction (FD-4: prevents agentId path traversal for cross-Project privilege escalation).+ // Id validation happens before any path construction: prevents agentId path traversal for cross-Project privilege escalation.const projectId = requireValidId(c, "projectId");const agentId = requireValidId(c, "agentId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);diff --git a/packages/server/src/http/routes/agents.ts b/packages/server/src/http/routes/agents.tsindex 5cee38ef..adb99e4e 100644--- a/packages/server/src/http/routes/agents.ts+++ b/packages/server/src/http/routes/agents.ts@@ -27,7 +27,7 @@ export function agentsRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();app.get("/", async (c) => {- // Defensive id validation (FD-4): don't rely on the implicit invariant that requireProjectAccess always runs before path construction.+ // Defensive id validation: don't rely on the implicit invariant that requireProjectAccess always runs before path construction.const projectId = requireValidId(c, "projectId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);const items = await deps.agentService.listAgents(projectId);diff --git a/packages/server/src/http/routes/chat-defaults.ts b/packages/server/src/http/routes/chat-defaults.tsindex c3184bf2..67771556 100644--- a/packages/server/src/http/routes/chat-defaults.ts+++ b/packages/server/src/http/routes/chat-defaults.ts@@ -18,7 +18,7 @@ export function chatDefaultsRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();app.get("/", async (c) => {- // Defensive id validation (FD-4).+ // Defensive id validation.const projectId = requireValidId(c, "projectId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);return c.json(await deps.projectConfigService.getChatDefaults(projectId));diff --git a/packages/server/src/http/routes/members.ts b/packages/server/src/http/routes/members.tsindex ff75c6c4..c0a66d0b 100644--- a/packages/server/src/http/routes/members.ts+++ b/packages/server/src/http/routes/members.ts@@ -17,7 +17,7 @@ export function membersRoutes(deps: AppDeps): Hono<AppEnv> {app.use("*", rejectInDesktopMode(deps));app.get("/", (c) => {- // Defensive id validation (FD-4).+ // Defensive id validation.const members = deps.projectService.listMembers(c.var.user.userId,requireValidId(c, "projectId"),diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.tsindex ca7e8722..300115a2 100644--- a/packages/server/src/http/routes/models.ts+++ b/packages/server/src/http/routes/models.ts@@ -161,7 +161,7 @@ export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();app.get("/", async (c) => {- // Defensive id validation (FD-4).+ // Defensive id validation.const projectId = requireValidId(c, "projectId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);return c.json(await deps.projectConfigService.getModels(projectId));diff --git a/packages/server/src/http/routes/projects.ts b/packages/server/src/http/routes/projects.tsindex b64bfda8..2bf8aeb7 100644--- a/packages/server/src/http/routes/projects.ts+++ b/packages/server/src/http/routes/projects.ts@@ -47,7 +47,7 @@ export function projectsRoutes(deps: AppDeps): Hono<AppEnv> {});app.delete("/:projectId", async (c) => {- // Defensive id validation (FD-4): deleteProject constructs the project directory path and recursively deletes it.+ // Defensive id validation: deleteProject constructs the project directory path and recursively deletes it.await deps.projectService.deleteProject(c.var.user.userId, requireValidId(c, "projectId"));return c.body(null, 204);});diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 55bd9e3f..4625474f 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -432,7 +432,7 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {// `cli=1` widens the list to CLI-created Sessions (Trace-directory discovery + adoption);// the default serves web rows straight from the DB (see SessionService.listSessions).app.get("/", async (c) => {- // Id validity is checked before any path is constructed (FD-4: guards against agentId path traversal across Projects).+ // Id validity is checked before any path is constructed: guards against agentId path traversal across Projects.const projectId = requireValidId(c, "projectId");const agentId = requireValidId(c, "agentId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);@@ -841,7 +841,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {app.get("/:sessionId/stream", (c) => {const row = resolveSession(c);const channel = deps.channels.get(row.sessionId);- // FD-1: the first event of every new subscription (including reconnects and resync+ // The first event of every new subscription (including reconnects and resync// rebuilds) is always a snapshot of the current running state — the frontend treats// this as authoritative, eliminating input-area lockup or premature Task closure// caused by a stale running/idle in the list; followed by replaying all still-pendingdiff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.tsindex 2377a210..5782aff2 100644--- a/packages/server/src/http/routes/skills.ts+++ b/packages/server/src/http/routes/skills.ts@@ -226,7 +226,7 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {});app.get("/", async (c) => {- // Defensive id validation happens before any path construction (FD-4: prevents path traversal for cross-Project privilege escalation).+ // Defensive id validation happens before any path construction: prevents path traversal for cross-Project privilege escalation.const projectId = requireValidId(c, "projectId");const agentId = requireValidId(c, "agentId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.tsindex 6ddc1f63..9c00cadc 100644--- a/packages/server/src/http/routes/usage.ts+++ b/packages/server/src/http/routes/usage.ts@@ -34,7 +34,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();app.get("/", async (c) => {- // Defensive id validation (FD-4).+ // Defensive id validation.const projectId = requireValidId(c, "projectId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);const groupByRaw = c.req.query("groupBy") ?? "date";diff --git a/packages/server/src/http/routes/vault.ts b/packages/server/src/http/routes/vault.tsindex 2ea5f43a..37dd4dd9 100644--- a/packages/server/src/http/routes/vault.ts+++ b/packages/server/src/http/routes/vault.ts@@ -37,7 +37,7 @@ export function vaultRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();app.get("/", async (c) => {- // Defensive id validation happens before any path construction (FD-4: prevents agentId path traversal for cross-Project privilege escalation).+ // Defensive id validation happens before any path construction: prevents agentId path traversal for cross-Project privilege escalation.const projectId = requireValidId(c, "projectId");const agentId = requireValidId(c, "agentId");deps.projectService.requireProjectAccess(c.var.user.userId, projectId);diff --git a/packages/server/src/http/validate.ts b/packages/server/src/http/validate.tsindex 7401b5cf..98f9e008 100644--- a/packages/server/src/http/validate.ts+++ b/packages/server/src/http/validate.ts@@ -42,28 +42,49 @@ export function requireValidId(c: Context, name: string): string {return v;}+/**+ * Parse a decimal non-negative integer, or null when the text is not exactly one.+ *+ * Digits only: Number.parseInt accepts trailing garbage ("12abc" -> 12, "1e3" -> 1), so a+ * caller that only range-checks the result silently honours a request it never validated.+ * isSafeInteger (not isInteger) additionally rejects overlong runs like+ * "99999999999999999999", which parse to an imprecise float (1e20).+ */+function parseNonNegativeInt(raw: string): number | null {+ if (!/^\d+$/.test(raw)) return null;+ const v = Number.parseInt(raw, 10);+ return Number.isSafeInteger(v) ? v : null;+}+/** Parse a positive-integer path parameter (e.g. Trace file index). */export function positiveIntParam(c: Context, name: string): number {- // Match digits only: Number.parseInt would accept trailing garbage ("12abc" -> 12).- const raw = pathParam(c, name);- if (!/^\d+$/.test(raw)) throw badRequest(`${name} must be a positive integer.`);- const v = Number.parseInt(raw, 10);- // isSafeInteger (not isInteger) also rejects overlong indices like "99999999999999999999"- // that would otherwise parse to an imprecise float (1e20).- if (!Number.isSafeInteger(v) || v < 1) throw badRequest(`${name} must be a positive integer.`);+ const v = parseNonNegativeInt(pathParam(c, name));+ if (v === null || v < 1) throw badRequest(`${name} must be a positive integer.`);return v;}-/** Parse Trace pagination query params: offset >= 0 (default 0), limit 1-1000 (default 200). */-export function paginationQuery(c: Context): { offset: number; limit: number } {- const offset = Number.parseInt(c.req.query("offset") ?? "0", 10);- const limit = Number.parseInt(c.req.query("limit") ?? "200", 10);- if (!Number.isInteger(offset) || offset < 0)- throw badRequest("offset must be a non-negative integer.");- if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {+/** Parse an already-defaulted offset query param (>= 0). */+function offsetQuery(raw: string): number {+ const v = parseNonNegativeInt(raw);+ if (v === null) throw badRequest("offset must be a non-negative integer.");+ return v;+}++/** Parse an already-defaulted limit query param (1-1000). */+function limitQuery(raw: string): number {+ const v = parseNonNegativeInt(raw);+ if (v === null || v < 1 || v > 1000) {throw badRequest("limit must be an integer between 1 and 1000.");}- return { offset, limit };+ return v;+}++/** Parse Trace pagination query params: offset >= 0 (default 0), limit 1-1000 (default 200). */+export function paginationQuery(c: Context): { offset: number; limit: number } {+ return {+ offset: offsetQuery(c.req.query("offset") ?? "0"),+ limit: limitQuery(c.req.query("limit") ?? "200"),+ };}/**@@ -77,14 +98,8 @@ export function optionalPagingQuery(c: Context): { offset: number; limit: numberconst rawOffset = c.req.query("offset");if (rawLimit === undefined && rawOffset === undefined) return null;if (rawLimit === undefined) throw badRequest("offset requires limit.");- const limit = Number.parseInt(rawLimit, 10);- if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {- throw badRequest("limit must be an integer between 1 and 1000.");- }- const offset = Number.parseInt(rawOffset ?? "0", 10);- if (!Number.isInteger(offset) || offset < 0) {- throw badRequest("offset must be a non-negative integer.");- }+ const limit = limitQuery(rawLimit);+ const offset = offsetQuery(rawOffset ?? "0");return { offset, limit };}diff --git a/packages/server/test/validate.test.ts b/packages/server/test/validate.test.tsindex 60005dd3..071cee08 100644--- a/packages/server/test/validate.test.ts+++ b/packages/server/test/validate.test.ts@@ -1,12 +1,18 @@/**- * Request-validation helper unit tests: positiveIntParam rejects trailing garbage,- * optionalDateParam rejects impossible calendar dates (shape-only checks let these through),- * and optionalNumber enforces the agent runtime-parameter rule (integer, > 0 or exactly -1)- * used for max_turns and friends.+ * Request-validation helper unit tests: positiveIntParam and the two paging helpers reject+ * trailing garbage, optionalDateParam rejects impossible calendar dates (shape-only checks+ * let these through), and optionalNumber enforces the agent runtime-parameter rule+ * (integer, > 0 or exactly -1) used for max_turns and friends.*/import { describe, expect, it } from "vitest";import type { Context } from "hono";-import { optionalDateParam, optionalNumber, positiveIntParam } from "../src/http/validate.js";+import {+ optionalDateParam,+ optionalNumber,+ optionalPagingQuery,+ paginationQuery,+ positiveIntParam,+} from "../src/http/validate.js";import { HttpError } from "../src/http/errors.js";/** Minimal Context stub exposing a single path parameter. */@@ -95,3 +101,59 @@ describe("optionalNumber with the agent runtime-parameter rule (integer, > 0 or}});});++/** Minimal Context stub exposing query parameters. */+function ctxWithQuery(query: Record<string, string>): Context {+ return { req: { query: (n: string) => query[n] } } as unknown as Context;+}++describe("paginationQuery", () => {+ it("defaults to offset 0 / limit 200", () => {+ expect(paginationQuery(ctxWithQuery({}))).toEqual({ offset: 0, limit: 200 });+ });++ it("parses plain integers", () => {+ expect(paginationQuery(ctxWithQuery({ offset: "40", limit: "20" }))).toEqual({+ offset: 40,+ limit: 20,+ });+ });++ it("rejects trailing garbage and exponent notation (parseInt would accept both)", () => {+ // "200abc" parsed to 200 and "1e3" to 1, both landing inside the range check.+ for (const bad of ["200abc", "1e3", "0x10", " 20", "20 ", "1.5", "+20", "-1"]) {+ expect(() => paginationQuery(ctxWithQuery({ limit: bad }))).toThrow(HttpError);+ expect(() => paginationQuery(ctxWithQuery({ offset: bad }))).toThrow(HttpError);+ }+ });++ it("enforces the limit range", () => {+ for (const bad of ["0", "1001"]) {+ expect(() => paginationQuery(ctxWithQuery({ limit: bad }))).toThrow(HttpError);+ }+ expect(paginationQuery(ctxWithQuery({ limit: "1000" })).limit).toBe(1000);+ });+});++describe("optionalPagingQuery", () => {+ it("returns null when neither param is present", () => {+ expect(optionalPagingQuery(ctxWithQuery({}))).toBeNull();+ });++ it("requires limit when only offset is given", () => {+ expect(() => optionalPagingQuery(ctxWithQuery({ offset: "10" }))).toThrow(HttpError);+ });++ it("defaults offset to 0 when only limit is given", () => {+ expect(optionalPagingQuery(ctxWithQuery({ limit: "50" }))).toEqual({ offset: 0, limit: 50 });+ });++ it("rejects trailing garbage and exponent notation (parseInt would accept both)", () => {+ for (const bad of ["50abc", "1e3", "0x10", "1.5", "-1"]) {+ expect(() => optionalPagingQuery(ctxWithQuery({ limit: bad }))).toThrow(HttpError);+ expect(() => optionalPagingQuery(ctxWithQuery({ limit: "50", offset: bad }))).toThrow(+ HttpError,+ );+ }+ });+});