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 prompt stage names and variable keys, 404 unknown stage PUT, 409 duplicates (#9152)
Adam Eivy65c585733f02
diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 45be27f627..c8f0f28c47 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2583,3 +2583,8 @@ export const htmlCompositionContractSchema = htmlCompositionContractSchemaFor(12// Jira issue key (ABC-123) or numeric id — the value is interpolated into upstream REST paths.export const jiraTicketKeySchema = z.string().max(64).regex(/^([A-Za-z][A-Za-z0-9_]*-\d+|\d+)$/, 'Invalid Jira ticket id');++// Prompt stage names and variable keys become `stages/<name>.md` / a+// variables.json key, so they must be a single safe path segment (#9152).+export const promptStageNameSchema = z.string().regex(/^[a-z0-9][a-z0-9_-]*$/, 'invalid stage name').max(80);+export const promptVariableKeySchema = z.string().regex(/^[A-Za-z0-9_-]+$/, 'invalid variable key').max(80);diff --git a/server/routes/prompts.js b/server/routes/prompts.jsindex 89304699dc..76912c6ad4 100644--- a/server/routes/prompts.js+++ b/server/routes/prompts.js@@ -1,6 +1,6 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { stageConfigUpdateSchema, validateRequest } from '../lib/validation.js';+import { promptStageNameSchema, promptVariableKeySchema, stageConfigUpdateSchema, validateRequest } from '../lib/validation.js';import {SYSTEM_STAGE_KEYS,isProtectedStage,@@ -25,6 +25,17 @@ export function createPortOSPromptsRoutes(aiToolkit) {const router = Router();const promptsService = aiToolkit.services.prompts;+ // Stage names and variable keys are joined into file paths by the toolkit;+ // Express decodes %2F in params, so reject anything but a single safe segment.+ router.param('stage', (req, res, next, value) => {+ validateRequest(promptStageNameSchema, value);+ next();+ });+ router.param('key', (req, res, next, value) => {+ validateRequest(promptVariableKeySchema, value);+ next();+ });+// GET /api/prompts - List all stages (wrapped in {stages: ...}) plus the// system-stage key list, so the Prompt Manager badges/filters them off the// server's own table instead of a client-side mirror that can drift (#3314).@@ -54,6 +65,10 @@ export function createPortOSPromptsRoutes(aiToolkit) {if (!key || !content) {throw new ServerError('key and content are required', { status: 400, code: 'VALIDATION_ERROR' });}+ validateRequest(promptVariableKeySchema, key);+ if (promptsService.getVariable(key)) {+ throw new ServerError(`Variable ${key} already exists`, { status: 409, code: 'CONFLICT' });+ }await promptsService.createVariable(key, { name, category, content });res.json({ success: true, key });}));@@ -142,6 +157,10 @@ export function createPortOSPromptsRoutes(aiToolkit) {if (!stageName || !name) {throw new ServerError('stageName and name are required', { status: 400, code: 'VALIDATION_ERROR' });}+ validateRequest(promptStageNameSchema, stageName);+ if (promptsService.getStage(stageName)) {+ throw new ServerError(`Stage ${stageName} already exists`, { status: 409, code: 'CONFLICT' });+ }const config = { name, description, model, returnsJson, variables };await promptsService.createStage(stageName, config, template);res.json({ success: true, stageName });@@ -154,6 +173,9 @@ export function createPortOSPromptsRoutes(aiToolkit) {// to `{}` — skip the disk write in that case to avoid an atomicWrite// churn on stage-config.json (the toolkit rewrites the entire file).router.put('/:stage', asyncHandler(async (req, res) => {+ if (!promptsService.getStage(req.params.stage)) {+ throw new ServerError('Stage not found', { status: 404, code: 'NOT_FOUND' });+ }const { template, ...rawConfig } = req.body;if (Object.keys(rawConfig).length > 0) {diff --git a/server/routes/prompts.test.js b/server/routes/prompts.test.jsindex 9cc30abe31..e5684f69d3 100644--- a/server/routes/prompts.test.js+++ b/server/routes/prompts.test.js@@ -151,3 +151,68 @@ describe('prompts routes — system stages', () => {expect(PROTECTED_STAGE_KEYS.length).toBeGreaterThan(SYSTEM_STAGE_KEYS.length * 5);});});++describe('prompts routes — name validation (#9152)', () => {+ const writers = () => ({+ updateStageTemplate: vi.fn(async () => {}),+ updateStageConfig: vi.fn(async () => {}),+ createStage: vi.fn(async () => {}),+ createVariable: vi.fn(async () => {}),+ getVariable: (k) => (k === 'known' ? { content: 'x' } : null),+ previewPrompt: vi.fn(async () => 'p'),+ });++ it.each(['..%2Fx', 'a%2Fb', 'Upper', 'has%20space'])('rejects stage param %s with 400 and touches nothing', async (bad) => {+ const svc = writers();+ const { app } = makeApp(svc);+ for (const r of [+ await request(app).put(`/api/prompts/${bad}`).send({ template: 'x' }),+ await request(app).get(`/api/prompts/${bad}`),+ await request(app).post(`/api/prompts/${bad}/preview`).send({}),+ await request(app).get(`/api/prompts/${bad}/usage`),+ ]) {+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('VALIDATION_ERROR');+ }+ expect(svc.updateStageTemplate).not.toHaveBeenCalled();+ expect(svc.previewPrompt).not.toHaveBeenCalled();+ });++ it('rejects an invalid stageName / variable key on create without writing', async () => {+ const svc = writers();+ const { app } = makeApp(svc);+ const a = await request(app).post('/api/prompts').send({ stageName: '../evil', name: 'n' });+ const b = await request(app).post('/api/prompts/variables').send({ key: 'a/b', content: 'c' });+ const c = await request(app).put('/api/prompts/variables/..%2Fx').send({ content: 'c' });+ expect([a.status, b.status, c.status]).toEqual([400, 400, 400]);+ expect(svc.createStage).not.toHaveBeenCalled();+ expect(svc.createVariable).not.toHaveBeenCalled();+ });++ it('PUT on an unknown stage is 404 and writes nothing', async () => {+ const svc = writers();+ const { app } = makeApp(svc);+ const r = await request(app).put('/api/prompts/no-such-stage').send({ template: 'x' });+ expect(r.status).toBe(404);+ expect(svc.updateStageTemplate).not.toHaveBeenCalled();+ });++ it('creating an existing stage or variable is 409', async () => {+ const svc = writers();+ const { app } = makeApp(svc);+ const a = await request(app).post('/api/prompts').send({ stageName: 'my-own-stage', name: 'n' });+ const b = await request(app).post('/api/prompts/variables').send({ key: 'known', content: 'c' });+ expect([a.status, b.status]).toEqual([409, 409]);+ expect(svc.createStage).not.toHaveBeenCalled();+ });++ it('every shipped stage name and variable key passes the schemas', async () => {+ const { readFileSync } = await import('fs');+ const { promptStageNameSchema, promptVariableKeySchema } = await import('../lib/validation.js');+ const dir = new URL('../../data.reference/prompts/', import.meta.url);+ const stages = Object.keys(JSON.parse(readFileSync(new URL('stage-config.json', dir), 'utf-8')).stages);+ const vars = Object.keys(JSON.parse(readFileSync(new URL('variables.json', dir), 'utf-8')).variables);+ expect(stages.filter((k) => !promptStageNameSchema.safeParse(k).success)).toEqual([]);+ expect(vars.filter((k) => !promptVariableKeySchema.safeParse(k).success)).toEqual([]);+ });+});