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
refactor: share meatspace index validation (#4885)
[._.]/ Adam Eivyeac75b27d3bf
diff --git a/server/lib/README.md b/server/lib/README.mdindex e3d7306935..440acf7b0a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -24,7 +24,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. |-| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |+| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parseIndexParam`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. || `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). || `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). || `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |diff --git a/server/lib/validation.js b/server/lib/validation.jsindex c96b686f74..890f1cc409 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1187,6 +1187,19 @@ export const clientErrorReportSchema = z.object({// PAGINATION HELPERS// =============================================================================+/**+ * Parse a zero-based array index from an Express route parameter.+ * @param {unknown} raw - Route parameter value+ * @returns {number}+ */+export function parseIndexParam(raw) {+ const index = Number(raw);+ if (typeof raw !== 'string' || !/^\d+$/.test(raw) || !Number.isSafeInteger(index)) {+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });+ }+ return index;+}+/*** Parse limit/offset pagination from query params with defaults and clamping.* @param {object} query - req.query objectdiff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex bc3a957c8d..9e533a5f6c 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -40,6 +40,7 @@ import {subdirFilterSchema,isPaginationRequested,paginateArray,+ parseIndexParam,parsePagination,seriesAutopilotSettingsSchema,portsCheckSchema,@@ -71,6 +72,24 @@ import {} from './brainValidation.js';describe('validation.js', () => {+ describe('parseIndexParam', () => {+ it('returns a non-negative integer route parameter', () => {+ expect(parseIndexParam('0')).toBe(0);+ expect(parseIndexParam('42')).toBe(42);+ });++ it.each(['', ' ', '-1', '1.5', '1abc', '1e2', 'abc', '9007199254740992'])(+ 'rejects invalid index %j',+ (raw) => {+ expect(() => parseIndexParam(raw)).toThrow(expect.objectContaining({+ message: 'Invalid index',+ status: 400,+ code: 'INVALID_INDEX',+ }));+ },+ );+ });+describe('isPaginationRequested', () => {it('is false when neither limit nor offset is present', () => {expect(isPaginationRequested({})).toBe(false);diff --git a/server/routes/meatspaceAlcoholRoutes.js b/server/routes/meatspaceAlcoholRoutes.jsindex 9d6556acbd..4df098cc2f 100644--- a/server/routes/meatspaceAlcoholRoutes.js+++ b/server/routes/meatspaceAlcoholRoutes.js@@ -6,7 +6,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { parseIndexParam, validateRequest } from '../lib/validation.js';import {drinkLogSchema,drinkUpdateSchema,@@ -56,10 +56,7 @@ router.post('/alcohol/log', asyncHandler(async (req, res) => {router.put('/alcohol/log/:date/:index', asyncHandler(async (req, res) => {const { date, index } = req.params;const data = validateRequest(drinkUpdateSchema, req.body);- const parsedIndex = parseInt(index, 10);- if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const parsedIndex = parseIndexParam(index);const result = await alcoholService.updateDrink(date, parsedIndex, data);if (!result) {throw new ServerError('Drink entry not found', { status: 404, code: 'NOT_FOUND' });@@ -73,10 +70,7 @@ router.put('/alcohol/log/:date/:index', asyncHandler(async (req, res) => {*/router.delete('/alcohol/log/:date/:index', asyncHandler(async (req, res) => {const { date, index } = req.params;- const parsedIndex = parseInt(index, 10);- if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const parsedIndex = parseIndexParam(index);const removed = await alcoholService.removeDrink(date, parsedIndex);if (!removed) {throw new ServerError('Drink entry not found', { status: 404, code: 'NOT_FOUND' });@@ -112,10 +106,7 @@ router.post('/alcohol/custom-drinks', asyncHandler(async (req, res) => {* Update a custom drink button*/router.put('/alcohol/custom-drinks/:index', asyncHandler(async (req, res) => {- const index = Number(req.params.index);- if (!Number.isInteger(index) || index < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const index = parseIndexParam(req.params.index);const data = validateRequest(customDrinkUpdateSchema, req.body);const drink = await alcoholService.updateCustomDrink(index, data);if (!drink) {@@ -129,10 +120,7 @@ router.put('/alcohol/custom-drinks/:index', asyncHandler(async (req, res) => {* Remove a custom drink button*/router.delete('/alcohol/custom-drinks/:index', asyncHandler(async (req, res) => {- const index = Number(req.params.index);- if (!Number.isInteger(index) || index < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const index = parseIndexParam(req.params.index);const removed = await alcoholService.removeCustomDrink(index);if (!removed) {throw new ServerError('Custom drink not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/routes/meatspaceHealthRoutes.js b/server/routes/meatspaceHealthRoutes.jsindex f182efe20a..f4d9279e3f 100644--- a/server/routes/meatspaceHealthRoutes.js+++ b/server/routes/meatspaceHealthRoutes.js@@ -6,7 +6,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { parseIndexParam, validateRequest } from '../lib/validation.js';import {bloodTestSchema,bodyEntrySchema,@@ -143,10 +143,7 @@ router.post('/eyes', asyncHandler(async (req, res) => {* Update an eye exam*/router.put('/eyes/:index', asyncHandler(async (req, res) => {- const index = parseInt(req.params.index, 10);- if (!Number.isInteger(index) || index < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const index = parseIndexParam(req.params.index);const data = validateRequest(eyeExamUpdateSchema, req.body);const exam = await healthService.updateEyeExam(index, data);if (!exam) {@@ -160,10 +157,7 @@ router.put('/eyes/:index', asyncHandler(async (req, res) => {* Remove an eye exam*/router.delete('/eyes/:index', asyncHandler(async (req, res) => {- const index = parseInt(req.params.index, 10);- if (!Number.isInteger(index) || index < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const index = parseIndexParam(req.params.index);const removed = await healthService.removeEyeExam(index);if (!removed) {throw new ServerError('Eye exam not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/routes/meatspaceNicotineRoutes.js b/server/routes/meatspaceNicotineRoutes.jsindex 6d3b3bf117..148c8e6a5c 100644--- a/server/routes/meatspaceNicotineRoutes.js+++ b/server/routes/meatspaceNicotineRoutes.js@@ -6,7 +6,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';+import { parseIndexParam, validateRequest } from '../lib/validation.js';import {nicotineLogSchema,nicotineUpdateSchema,@@ -56,10 +56,7 @@ router.post('/nicotine/log', asyncHandler(async (req, res) => {router.put('/nicotine/log/:date/:index', asyncHandler(async (req, res) => {const { date, index } = req.params;const data = validateRequest(nicotineUpdateSchema, req.body);- const parsedIndex = parseInt(index, 10);- if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const parsedIndex = parseIndexParam(index);const result = await nicotineService.updateNicotine(date, parsedIndex, data);if (!result) {throw new ServerError('Nicotine entry not found', { status: 404, code: 'NOT_FOUND' });@@ -73,10 +70,7 @@ router.put('/nicotine/log/:date/:index', asyncHandler(async (req, res) => {*/router.delete('/nicotine/log/:date/:index', asyncHandler(async (req, res) => {const { date, index } = req.params;- const parsedIndex = parseInt(index, 10);- if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const parsedIndex = parseIndexParam(index);const removed = await nicotineService.removeNicotine(date, parsedIndex);if (!removed) {throw new ServerError('Nicotine entry not found', { status: 404, code: 'NOT_FOUND' });@@ -112,10 +106,7 @@ router.post('/nicotine/custom-products', asyncHandler(async (req, res) => {* Update a custom nicotine product button*/router.put('/nicotine/custom-products/:index', asyncHandler(async (req, res) => {- const index = Number(req.params.index);- if (!Number.isInteger(index) || index < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const index = parseIndexParam(req.params.index);const data = validateRequest(customNicotineProductUpdateSchema, req.body);const product = await nicotineService.updateCustomProduct(index, data);if (!product) {@@ -129,10 +120,7 @@ router.put('/nicotine/custom-products/:index', asyncHandler(async (req, res) =>* Remove a custom nicotine product button*/router.delete('/nicotine/custom-products/:index', asyncHandler(async (req, res) => {- const index = Number(req.params.index);- if (!Number.isInteger(index) || index < 0) {- throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });- }+ const index = parseIndexParam(req.params.index);const removed = await nicotineService.removeCustomProduct(index);if (!removed) {throw new ServerError('Custom product not found', { status: 404, code: 'NOT_FOUND' });