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: address codex review — live /active validation, proto-safety, coercion, schema placement (#2521)

Adam Eivyc3668cd4c66f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6c3ee5f7d1..31809e1204 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,4 +15,4 @@
## Changed
-- **[issue-2521] Validate the remaining ad-hoc route bodies with Zod `validateRequest`.** The ports (`/check`, `/allocate`), database (`switch`/`start`/`stop`/`destroy`/`export`), brain digest/review run, telegram `forward-types`, and AI-toolkit provider (`POST`/`PUT`/`PUT active`) routes parsed `req.body` with hand-rolled `Array.isArray`/`includes` checks. Each now has a named Zod schema (PortOS schemas in `lib/validation.js`, provider schemas in `aiToolkit/validation.js`) wired through `validateRequest`, so invalid bodies return a consistent `400 VALIDATION_ERROR` with per-field `context.details` instead of ad-hoc messages. Port numbers are range-checked, backend/target values are enum-checked, and provider create/update reuse the canonical `providerSchema` (`.partial()` on update).
+- **[issue-2521] Validate the remaining ad-hoc route bodies with Zod `validateRequest`.** The ports (`/check`, `/allocate`), database (`switch`/`start`/`stop`/`destroy`/`export`), brain digest/review run, telegram (`method`/`config`/`test`/`forward-types`), and AI-toolkit provider (`POST`/`PUT`/`PUT active`) routes parsed `req.body` with hand-rolled `Array.isArray`/`includes` checks. Each now has a named Zod schema (PortOS schemas in `lib/validation.js`, brain schema in `brainValidation.js`, provider schemas in `aiToolkit/validation.js`) wired through `validateRequest`, so invalid bodies return a consistent `400 VALIDATION_ERROR` with per-field `context.details` instead of ad-hoc messages. Port numbers are range-checked (and `count` coercion no longer silently accepts booleans/arrays), backend/target values are enum-checked, and provider create/update reuse the canonical `providerSchema` (`.partial()` on update). As part of wiring `PUT /api/providers/active`, the toolkit providers map is now null-prototyped on load so a crafted id (`__proto__`, `constructor`, `toString`) can no longer resolve an inherited `Object.prototype` member as an existing provider and be persisted as the active one.
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 5dea6b839a..bac763db5c 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -295,6 +295,17 @@ export function createProviderService(config = {}) {
let cacheGeneration = 0;
function refreshProvidersCache(data) {
+ // Null-prototype the providers map so a keyed lookup (`data.providers[id]`)
+ // in getProviderById / setActiveProvider / updateProvider / etc. can't
+ // resolve an inherited Object.prototype member (`__proto__`, `constructor`,
+ // `toString`, …) as a "provider that exists". Without this, a crafted id
+ // like `constructor` walks the prototype chain, tests truthy, and gets
+ // treated as a real provider (e.g. persisted as `activeProvider`). Own
+ // enumerable keys still serialize/iterate normally (JSON.stringify,
+ // Object.values, spread, delete all behave identically on a null-proto map).
+ if (data?.providers && Object.getPrototypeOf(data.providers) !== null) {
+ data.providers = Object.assign(Object.create(null), data.providers);
+ }
providersCache = data;
providersCacheAt = Date.now();
cacheGeneration += 1;
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index b0ebd3e29f..ec41923a7d 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -781,4 +781,19 @@ describe('Provider Service', () => {
expect(result).toBeNull();
});
});
+
+ describe('reserved-key prototype safety (#2521)', () => {
+ it('does not resolve Object.prototype members as existing providers', async () => {
+ // The providers map is null-prototyped on load, so a keyed lookup for an
+ // inherited member returns "not found" rather than a truthy prototype fn.
+ for (const key of ['__proto__', 'constructor', 'toString', 'hasOwnProperty']) {
+ expect(await providerService.getProviderById(key)).toBeNull();
+ expect(await providerService.setActiveProvider(key)).toBeNull();
+ expect(await providerService.updateProvider(key, { name: 'x' })).toBeNull();
+ expect(await providerService.deleteProvider(key)).toBe(false);
+ }
+ const { activeProvider } = await providerService.getAllProviders();
+ expect(['__proto__', 'constructor', 'toString', 'hasOwnProperty']).not.toContain(activeProvider);
+ });
+ });
});
diff --git a/server/lib/aiToolkit/routes/errorEnvelope.test.js b/server/lib/aiToolkit/routes/errorEnvelope.test.js
index 71aef78571..b8ddc69944 100644
--- a/server/lib/aiToolkit/routes/errorEnvelope.test.js
+++ b/server/lib/aiToolkit/routes/errorEnvelope.test.js
@@ -61,13 +61,15 @@ describe('issue-1084: toolkit routes emit the PortOS error envelope', () => {
expect(typeof res.body.timestamp).toBe('number');
});
- it('providers 400 (POST missing name) → BAD_REQUEST envelope', async () => {
+ it('providers 400 (POST missing name) → VALIDATION_ERROR envelope with details', async () => {
const providers = { createProvider: vi.fn() };
const app = portosApp('/api/providers', (opts) => createProvidersRoutes(providers, opts));
+ // Missing `name` fails providerSchema → the validation-reject branch.
const res = await request(app).post('/api/providers').send({ type: 'cli' });
expect(res.status).toBe(400);
- expect(res.body).toMatchObject({ error: 'Name is required', code: 'BAD_REQUEST' });
+ expect(res.body).toMatchObject({ error: 'Invalid provider data', code: 'VALIDATION_ERROR' });
+ expect(res.body.context?.details?.some((d) => d.path === 'name')).toBe(true);
expect(providers.createProvider).not.toHaveBeenCalled();
});
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 76c377b03f..1bee184642 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -98,9 +98,13 @@ export const providerSchema = z.object({
tuiMaxRuntimeMs: z.number().int().min(60000).max(43200000).optional()
});
-// PUT /api/providers/active — set the active provider by id.
+// PUT /api/providers/active — set the active provider by id. Constrain to the
+// same slug shape createProvider assigns (`providerSchema.id`) so a reserved
+// key like `__proto__` can't reach the `data.providers[id]` lookup in
+// setActiveProvider (which walks the prototype chain and would otherwise treat
+// `__proto__` as an existing provider and persist it as active).
export const providerActiveSchema = z.object({
- id: z.string().min(1)
+ id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, 'id must be lowercase alphanumeric with hyphens').max(80)
});
export const runSchema = z.object({
diff --git a/server/lib/aiToolkit/validation.test.js b/server/lib/aiToolkit/validation.test.js
index d2df094adf..108a1daf46 100644
--- a/server/lib/aiToolkit/validation.test.js
+++ b/server/lib/aiToolkit/validation.test.js
@@ -182,12 +182,19 @@ describe('validate', () => {
});
describe('providerActiveSchema — PUT /api/providers/active (#2521)', () => {
- it('requires a non-empty id', () => {
+ it('accepts a slug id and rejects empty/missing/non-string', () => {
expect(validate(providerActiveSchema, { id: 'codex' }).success).toBe(true);
+ expect(validate(providerActiveSchema, { id: 'claude-ollama-1' }).success).toBe(true);
expect(validate(providerActiveSchema, { id: '' }).success).toBe(false);
expect(validate(providerActiveSchema, {}).success).toBe(false);
expect(validate(providerActiveSchema, { id: 5 }).success).toBe(false);
});
+
+ it('rejects reserved prototype keys so setActiveProvider cannot walk the prototype chain', () => {
+ expect(validate(providerActiveSchema, { id: '__proto__' }).success).toBe(false);
+ expect(validate(providerActiveSchema, { id: 'constructor' }).success).toBe(true); // a valid slug, but only matches an OWN provider key
+ expect(validate(providerActiveSchema, { id: 'Codex' }).success).toBe(false); // uppercase disallowed
+ });
});
describe('providerSchema.partial() — PUT /api/providers/:id (#2521)', () => {
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 884d5d8e4b..0a3648bbb7 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -541,3 +541,10 @@ export const activityDigestSettingsSchema = z.object({
runTime: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Expected HH:MM (24h)').optional(),
catchUpDays: z.number().int().min(0).max(30).optional()
}).strict();
+
+// POST /api/brain/{digest,review}/run — manual trigger with optional provider /
+// model overrides (both absent = use configured defaults).
+export const brainDigestRunSchema = z.object({
+ providerOverride: z.string().optional(),
+ modelOverride: z.string().optional()
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 21697cf150..737938ca1d 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -671,12 +671,20 @@ export const portsCheckSchema = z.object({
ports: z.array(z.number().int().min(1).max(65535)).min(1)
});
-// POST /api/ports/allocate — reserve N free ports. `count` is coerced (the UI
-// may send a string) and defaults to 1 when absent, matching the prior
-// `parseInt(count) || 1` behavior — but non-numeric garbage now 400s instead of
-// silently collapsing to 1.
+// POST /api/ports/allocate — reserve N free ports. `count` accepts a number or
+// a numeric string (the UI may send either) and defaults to 1 when absent,
+// matching the prior `parseInt(count) || 1` behavior — but non-numeric garbage
+// now 400s instead of silently collapsing to 1. The preprocess only forwards
+// number|string so `z.coerce` can't quietly turn a boolean (`true → 1`) or an
+// array (`[5] → 5`) into a valid count.
export const portsAllocateSchema = z.object({
- count: z.coerce.number().int().min(1).max(10).default(1)
+ count: z.preprocess(
+ (v) => {
+ if (v === undefined) return 1;
+ return (typeof v === 'number' || typeof v === 'string') ? v : NaN;
+ },
+ z.coerce.number().int().min(1).max(10)
+ )
});
// =============================================================================
@@ -702,17 +710,6 @@ export const databaseExportSchema = z.object({
backend: z.enum(DB_BACKENDS).optional()
});
-// =============================================================================
-// BRAIN DIGEST / REVIEW
-// =============================================================================
-
-// POST /api/brain/{digest,review}/run — manual trigger with optional provider /
-// model overrides.
-export const brainDigestRunSchema = z.object({
- providerOverride: z.string().optional(),
- modelOverride: z.string().optional()
-});
-
/**
* Validate data against a Zod schema, throwing on failure.
* Returns parsed data on success, throws ServerError on failure.
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 201731e2e3..ec8eb37464 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -38,11 +38,13 @@ import {
databaseSwitchSchema,
databaseBackendSchema,
databaseExportSchema,
- brainDigestRunSchema,
} from './validation.js';
import {
telegramForwardTypesSchema,
} from './telegramValidation.js';
+import {
+ brainDigestRunSchema,
+} from './brainValidation.js';
describe('validation.js', () => {
describe('isPaginationRequested', () => {
@@ -1385,10 +1387,14 @@ describe('ad-hoc route schemas (#2521)', () => {
expect(portsAllocateSchema.parse({})).toEqual({ count: 1 });
expect(portsAllocateSchema.parse({ count: '5' })).toEqual({ count: 5 });
});
- it('rejects out-of-range counts and non-numeric garbage', () => {
+ it('rejects out-of-range counts, non-numeric strings, and non-scalar JSON', () => {
expect(portsAllocateSchema.safeParse({ count: 0 }).success).toBe(false);
expect(portsAllocateSchema.safeParse({ count: 11 }).success).toBe(false);
expect(portsAllocateSchema.safeParse({ count: 'abc' }).success).toBe(false);
+ // z.coerce alone would turn these into valid counts (true→1, [5]→5); the
+ // preprocess forwards only number|string so they fail instead.
+ expect(portsAllocateSchema.safeParse({ count: true }).success).toBe(false);
+ expect(portsAllocateSchema.safeParse({ count: [5] }).success).toBe(false);
});
});
diff --git a/server/routes/brainDigest.js b/server/routes/brainDigest.js
index f6bb949865..314bca2d32 100644
--- a/server/routes/brainDigest.js
+++ b/server/routes/brainDigest.js
@@ -7,7 +7,8 @@
import { Router } from 'express';
import * as brainService from '../services/brain.js';
import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest, brainDigestRunSchema } from '../lib/validation.js';
+import { validateRequest } from '../lib/validation.js';
+import { brainDigestRunSchema } from '../lib/brainValidation.js';
const router = Router();
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 0a00556c7c..f24b6aa5b3 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -2,7 +2,7 @@ import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';
import { getAllProviderStatuses, getProviderStatus, markProviderAvailable, getTimeUntilRecovery } from '../services/providerStatus.js';
-import { providerSchema, validate } from '../lib/aiToolkit/validation.js';
+import { providerSchema, providerActiveSchema, validate } from '../lib/aiToolkit/validation.js';
/**
* Sanitize a provider object for client responses.
@@ -53,10 +53,11 @@ export function createPortOSProviderRoutes(aiToolkit) {
// PUT /active must be defined before PUT /:id to avoid the wildcard
// catching "active" as a provider ID (which causes 404 "Provider not found")
router.put('/active', asyncHandler(async (req, res) => {
- const { id } = req.body;
- if (!id) {
- throw new ServerError('Provider ID required', { status: 400 });
+ const validation = validate(providerActiveSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Invalid provider data', { status: 400, code: 'VALIDATION_ERROR', context: { details: validation.errors } });
}
+ const { id } = validation.data;
const provider = await providerService.setActiveProvider(id);
if (!provider) {
throw new ServerError('Provider not found', { status: 404 });