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
fix: validate scaffold request schema before any filesystem mutation (#2390)
Adam Eivy529ee8de538f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c3b02f3f44..19fded5a36 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,8 @@- **[issue-2391] The Character Sheet name is now editable by keyboard and screen reader.** Editing the hero's name used to hang off a non-semantic `<h2 onClick>` — invisible to the keyboard (not focusable, Enter/Space did nothing) and unlabelled for assistive tech. The name is now a real labelled `<button>` (`aria-label="Edit character name (currently …)"`, `type="button"` so it can't submit any wrapping form) that reveals an `aria-label`ed text input; the input commits on **Enter**, cancels and restores the original name on **Escape** (both `preventDefault`ed to avoid accidental form behavior), and still saves on blur — resolved exactly once via a re-entrancy guard so the Enter/Escape-then-blur pair can't double-save. The 2xl-bold hover-accent visual treatment is unchanged, and new accessibility-focused component tests cover the labelled control plus the Enter/Escape flows.+- **[issue-2390] The app scaffolder now validates the complete request before it touches the filesystem.** `POST /api/scaffold` previously ran only a partial `name/template/parentDir` presence check, then allocated ports and created the target directory before it could reject a malformed template, out-of-range port, or garbage name — an unknown template even left an empty half-scaffolded directory behind. The route now validates and normalizes the full request against a Zod `scaffoldSchema` (`server/lib/validation.js`): the template must be one of the six known templates, `uiPort`/`apiPort` must be valid TCP ports, and the name must yield a usable directory slug — all enforced up front, so an invalid request is rejected deterministically with zero filesystem writes or subprocess spawns. New route-level tests prove each invalid class (unknown template, bad port, malformed name, missing fields) performs no mutations.+- **Modals and drawers now trap and restore keyboard focus, and toasts are announced to screen readers.** Opening any shared `Modal` or `Drawer` (which back the great majority of the app's dialogs, config drawers, and lightboxes) now moves focus into the dialog, keeps Tab/Shift+Tab cycling inside it instead of leaking to the page behind, and returns focus to the control that opened it on close (WCAG 2.4.3 / 2.1.2) — implemented once in a reusable `useFocusTrap` hook. The toast stack is now a labelled ARIA notification region: default toasts announce politely (`role="status"`) and error toasts assertively (`role="alert"`), with the decorative status glyphs hidden from assistive tech, so screen-reader users hear notifications (including error toasts) as they arrive.## AI Providersdiff --git a/server/lib/validation.js b/server/lib/validation.jsindex 6ba28ee614..df3d209ea2 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1,6 +1,6 @@import { z } from 'zod';import { ServerError } from './errorHandler.js';-import { partialWithoutDefaults, emptyToUndefined } from './zodCompat.js';+import { partialWithoutDefaults, emptyToUndefined, emptyToNull } from './zodCompat.js';import { WORK_TRACKERS } from './workTracker.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total@@ -498,6 +498,50 @@ export function validate(schema, data) {};}+// =============================================================================+// SCAFFOLD (app generator)+// =============================================================================++// Known scaffold templates — the single source of truth for the enum the+// scaffold route accepts. An unknown template MUST be rejected before any+// filesystem write or subprocess spawn (issue #2390), so the route can no+// longer create a target directory for a template it can't actually build.+export const SCAFFOLD_TEMPLATES = [+ 'portos-stack',+ 'vite-express',+ 'vite-react',+ 'express-api',+ 'ios-native',+ 'xcode-multiplatform'+];++// Ports may arrive absent (auto-allocated by the route) or as an explicit+// number. Tolerate the UI '' sentinel as "not provided"; anything else must be+// a valid TCP port so an out-of-range value is rejected deterministically.+const scaffoldPortSchema = z.preprocess(+ emptyToUndefined,+ z.number().int().min(1).max(65535).nullable().optional()+);++// Full request schema for POST /api/scaffold. Validated before the route+// touches the filesystem — template enum, port range, and a name that yields a+// usable directory slug are all enforced up front.+export const scaffoldSchema = z.object({+ name: z.string().trim().min(1).max(100)+ // The route sanitizes name → [a-z0-9-]; a name with no alphanumerics+ // slugifies to an all-dash/empty dirName. Reject it here rather than+ // creating a garbage directory.+ .refine(v => /[a-z0-9]/i.test(v), {+ message: 'name must contain at least one letter or number'+ }),+ template: z.enum(SCAFFOLD_TEMPLATES),+ parentDir: z.string().trim().min(1),+ uiPort: scaffoldPortSchema,+ apiPort: scaffoldPortSchema,+ createGitHubRepo: z.boolean().optional().default(false),+ githubOrg: z.preprocess(emptyToNull, z.string().min(1).nullable().optional())+});+/*** Validate data against a Zod schema, throwing on failure.* Returns parsed data on success, throws ServerError on failure.diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex 951aa9dfc1..1ce85b50d2 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -8,6 +8,7 @@ import { promisify } from 'util';import { platform } from 'os';import { createApp, getReservedPorts } from '../services/apps.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest, scaffoldSchema } from '../lib/validation.js';import { ensureDir, expandHome } from '../lib/fileUtils.js';import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';import { scaffoldVite } from './scaffoldVite.js';@@ -210,23 +211,15 @@ async function findNextAvailablePorts(needsApi, needsUi) {// Shared scaffold logicasync function scaffoldApp(req, res) {- let {- name,- template,- parentDir,- uiPort,- apiPort,- createGitHubRepo = false,- githubOrg = null- } = req.body;-- // Validation- if (!name || !template || !parentDir) {- throw new ServerError('name, template, and parentDir are required', {- status: 400,- code: 'VALIDATION_ERROR'- });- }+ // Validate + normalize the COMPLETE request before ANY filesystem write or+ // subprocess spawn: unknown templates and out-of-range ports are rejected+ // deterministically here, so no target directory or resource is allocated+ // for a request the route can't fulfill (issue #2390).+ const parsed = validateRequest(scaffoldSchema, req.body);+ const { name, template, parentDir, createGitHubRepo, githubOrg } = parsed;+ // uiPort/apiPort are reassigned by the auto-allocator below, so they need+ // their own mutable bindings.+ let { uiPort, apiPort } = parsed;// Auto-allocate ports if not providedconst templateNeedsPorts = {diff --git a/server/routes/scaffold.test.js b/server/routes/scaffold.test.jsnew file mode 100644index 0000000000..89fbd8bfe9--- /dev/null+++ b/server/routes/scaffold.test.js@@ -0,0 +1,150 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { EventEmitter } from 'events';+import { request } from '../lib/testHelper.js';++// --- Mock the filesystem + subprocess boundary so we can assert ZERO+// mutations happen when a request fails validation (issue #2390). ---+vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn().mockResolvedValue(undefined),+ expandHome: (p) => p+}));++vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue(undefined),+ readdir: vi.fn().mockResolvedValue([]),+ stat: vi.fn().mockResolvedValue({ isDirectory: () => true })+}));++// Parent dir exists; target dir does not (so a valid request proceeds).+vi.mock('fs', () => ({+ existsSync: vi.fn((p) => p === '/tmp/workspace'),+ realpathSync: vi.fn((p) => p)+}));++vi.mock('child_process', () => ({+ exec: vi.fn((cmd, opts, cb) => cb(null, { stdout: '', stderr: '' })),+ spawn: vi.fn(() => {+ const proc = new EventEmitter();+ proc.stderr = new EventEmitter();+ // Resolve the spawn promise on the next tick with a success exit code.+ setImmediate(() => proc.emit('close', 0));+ return proc;+ })+}));++vi.mock('../services/apps.js', () => ({+ createApp: vi.fn().mockResolvedValue({ id: 'app-001', name: 'Test' }),+ getReservedPorts: vi.fn().mockResolvedValue([])+}));++vi.mock('../lib/workspaceRoots.js', () => ({+ isWithinAllowedRoots: vi.fn(() => true)+}));++vi.mock('./scaffoldVite.js', () => ({ scaffoldVite: vi.fn().mockResolvedValue(undefined) }));+vi.mock('./scaffoldExpress.js', () => ({ scaffoldExpress: vi.fn().mockResolvedValue(undefined) }));+vi.mock('./scaffoldIOS.js', () => ({ scaffoldIOS: vi.fn().mockResolvedValue(undefined) }));+vi.mock('./scaffoldXcode.js', () => ({ scaffoldXcode: vi.fn().mockResolvedValue(undefined) }));+vi.mock('./scaffoldPortOS.js', () => ({ scaffoldPortOS: vi.fn().mockResolvedValue(undefined) }));+vi.mock('../services/xcodeScripts.js', () => ({ toTargetName: vi.fn(() => 'TestApp') }));++import scaffoldRoutes from './scaffold.js';+import { ensureDir } from '../lib/fileUtils.js';+import { writeFile } from 'fs/promises';+import { spawn, exec } from 'child_process';+import { createApp } from '../services/apps.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/scaffold', scaffoldRoutes);+ return app;+}++/** Assert that NO filesystem write or subprocess spawn happened. */+function expectZeroMutations() {+ expect(ensureDir).not.toHaveBeenCalled();+ expect(writeFile).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(exec).not.toHaveBeenCalled();+ expect(createApp).not.toHaveBeenCalled();+}++describe('POST /api/scaffold — request validation before filesystem mutation (#2390)', () => {+ let app;++ beforeEach(() => {+ vi.clearAllMocks();+ app = makeApp();+ });++ const validBody = {+ name: 'My App',+ template: 'ios-native',+ parentDir: '/tmp/workspace'+ };++ it('rejects an unknown template with a validation error and zero mutations', async () => {+ const res = await request(app)+ .post('/api/scaffold')+ .send({ ...validBody, template: 'malware-kit' });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expectZeroMutations();+ });++ it('rejects an out-of-range uiPort with a validation error and zero mutations', async () => {+ const res = await request(app)+ .post('/api/scaffold')+ .send({ ...validBody, template: 'vite-react', uiPort: 70000 });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expectZeroMutations();+ });++ it('rejects a non-integer apiPort with a validation error and zero mutations', async () => {+ const res = await request(app)+ .post('/api/scaffold')+ .send({ ...validBody, template: 'express-api', apiPort: 'not-a-port' });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expectZeroMutations();+ });++ it('rejects a malformed name (no alphanumerics) with a validation error and zero mutations', async () => {+ const res = await request(app)+ .post('/api/scaffold')+ .send({ ...validBody, name: '!!!___' });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expectZeroMutations();+ });++ it('rejects missing required fields with a validation error and zero mutations', async () => {+ const res = await request(app)+ .post('/api/scaffold')+ .send({ name: 'My App' }); // no template, no parentDir++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expectZeroMutations();+ });++ it('accepts a valid request and only then performs filesystem mutations', async () => {+ const res = await request(app)+ .post('/api/scaffold')+ .send(validBody);++ expect(res.status).toBe(200);+ expect(res.body.success).toBe(true);+ // Validation passed → the route reached the first filesystem mutation+ // (directory creation) and registered the app.+ expect(ensureDir).toHaveBeenCalledWith('/tmp/workspace/my-app');+ expect(createApp).toHaveBeenCalledTimes(1);+ });+});