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: validate standardization apply requests (#4921)

Adam Eivyb2605035184c
diff --git a/server/lib/validation.js b/server/lib/validation.js
index c96b686f74..9293de11f4 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -310,6 +310,46 @@ export const referenceRepoUpdateSchema = z.object({
// either — all ref CRUD goes through /api/apps/:appId/reference-repos.
export const appUpdateSchema = partialWithoutDefaults(appSchema);
+const standardizePlanFileSchema = z.string().trim().min(1).max(500)
+ .refine((file) => {
+ const segments = file.split(/[/\\]/);
+ return !file.startsWith('/')
+ && !file.startsWith('\\')
+ && !/^[A-Za-z]:/.test(file)
+ && !segments.includes('..');
+ }, { message: 'file must be a repo-relative path without parent traversal' });
+
+const standardizePlanProcessSchema = z.object({
+ name: z.string().trim().min(1).max(120)
+}).passthrough();
+
+const standardizePlanStrayPortSchema = z.object({
+ file: standardizePlanFileSchema,
+ variable: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(120),
+ value: z.number().int().min(1).max(65535),
+ line: z.number().int().positive(),
+ action: z.enum(['remove', 'keep'])
+}).passthrough();
+
+export const standardizePlanSchema = z.object({
+ currentState: z.object({
+ hasGit: z.boolean()
+ }).passthrough(),
+ proposedChanges: z.object({
+ createEcosystem: z.boolean(),
+ ecosystemContent: z.string().min(1).max(1_000_000),
+ processes: z.array(standardizePlanProcessSchema).max(100),
+ strayPorts: z.array(standardizePlanStrayPortSchema).max(500)
+ }).passthrough()
+}).passthrough();
+
+export const standardizeApplySchema = z.object({
+ repoPath: z.string().trim().min(1).max(4096).optional(),
+ appId: z.string().trim().min(1).max(200).optional(),
+ plan: standardizePlanSchema,
+ overwriteEcosystem: z.boolean().optional().default(false)
+});
+
// Game studio (#3177): managed-app binding, reusable asset bindings, bundle
// compile, and user-triggered AI feedback.
const gameNameSchema = z.string().trim().min(1).max(120);
diff --git a/server/routes/standardize.js b/server/routes/standardize.js
index 30c45acc30..e6416f1e80 100644
--- a/server/routes/standardize.js
+++ b/server/routes/standardize.js
@@ -1,5 +1,9 @@
import { Router } from 'express';
+import { realpath } from 'fs/promises';
+import { resolve } from 'path';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { standardizeApplySchema, validateRequest } from '../lib/validation.js';
+import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaceRoots.js';
import * as pm2Standardizer from '../services/pm2Standardizer.js';
import * as appsService from '../services/apps.js';
@@ -20,9 +24,11 @@ const router = Router();
* rewriting a different directory would make the gate decorative: a permitted
* Node `appId` alongside some other repo's path would carry a Python or Docker
* project straight past the refusal. No caller sends both (the client wrappers
- * in `apiSystem.js` send one or the other), so this only closes the hole.
+ * in `apiSystem.js` send one or the other), so this only closes the hole. Every
+ * selected target is still canonicalized and confined to the workspace roots.
*/
async function resolveStandardizeTarget({ repoPath, appId }) {
+ let target;
if (appId) {
const app = await appsService.getAppById(appId);
if (!app) {
@@ -32,12 +38,32 @@ async function resolveStandardizeTarget({ repoPath, appId }) {
if (refusal) {
throw new ServerError(refusal, { status: 400, code: 'NOT_STANDARDIZABLE' });
}
- return app.repoPath;
+ target = app.repoPath;
+ } else if (repoPath) {
+ target = repoPath;
+ } else {
+ throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });
}
- if (repoPath) return repoPath;
+ if (typeof target !== 'string' || !target.trim()) {
+ throw new ServerError('Standardization target is invalid', { status: 400, code: 'INVALID_PATH' });
+ }
- throw new ServerError('Either repoPath or appId is required', { status: 400, code: 'MISSING_PATH' });
+ // Resolve symlinks before checking containment so a path that appears to sit
+ // below an allowed root cannot redirect the standardizer's writes elsewhere.
+ const realTarget = await realpath(resolve(target)).catch(() => null);
+ if (!realTarget) {
+ throw new ServerError('Standardization target is not accessible', { status: 400, code: 'INVALID_PATH' });
+ }
+ if (!isWithinAllowedRoots(realTarget)) {
+ console.error(`❌ ${outsideAllowedRootsMessage(realTarget, { field: 'standardization target' })}`);
+ throw new ServerError('Standardization target is outside allowed directories', {
+ status: 403,
+ code: 'FORBIDDEN'
+ });
+ }
+
+ return realTarget;
}
// POST /api/standardize/analyze - Analyze app and generate standardization plan
@@ -61,18 +87,19 @@ router.post('/analyze', asyncHandler(async (req, res) => {
// POST /api/standardize/apply - Apply standardization changes
router.post('/apply', asyncHandler(async (req, res) => {
- const { repoPath, appId, plan, overwriteEcosystem = false } = req.body;
+ const { repoPath, appId } = req.body;
const path = await resolveStandardizeTarget({ repoPath, appId });
-
- if (!plan) {
- throw new ServerError('Standardization plan is required', { status: 400, code: 'MISSING_PLAN' });
- }
+ const { plan, overwriteEcosystem } = validateRequest(standardizeApplySchema, req.body);
console.log(`🔧 Applying PM2 standardization to: ${path}`);
const result = await pm2Standardizer.applyStandardization(path, plan, { overwriteEcosystem });
+ if (!result.success) {
+ throw new ServerError(result.error || 'Standardization failed', { status: 400, code: 'APPLY_FAILED' });
+ }
+
if (result.backupBranch) {
console.log(`📦 Backup branch created: ${result.backupBranch}`);
}
diff --git a/server/routes/standardize.test.js b/server/routes/standardize.test.js
index eefdcf7d67..00b49db08c 100644
--- a/server/routes/standardize.test.js
+++ b/server/routes/standardize.test.js
@@ -2,13 +2,23 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, realpath: vi.fn(async (path) => path) };
+});
+
+vi.mock('../lib/workspaceRoots.js', () => ({
+ isWithinAllowedRoots: vi.fn(() => true),
+ outsideAllowedRootsMessage: vi.fn(() => 'standardization target is outside allowed directories')
+}));
+
// Standardizing REWRITES the target repo (writes ecosystem.config.cjs, comments
// ports out of .env/vite config), so these tests assert the precondition gate
// runs before any of that — and that a refused request does zero work.
vi.mock('../services/pm2Standardizer.js', () => ({
standardizeRefusalFor: vi.fn(() => null),
analyzeApp: vi.fn().mockResolvedValue({ success: true, proposedChanges: { processes: [{ name: 'p' }] } }),
- applyStandardization: vi.fn().mockResolvedValue({ filesModified: [], backupBranch: null }),
+ applyStandardization: vi.fn().mockResolvedValue({ success: true, filesModified: [], backupBranch: null }),
createGitBackup: vi.fn().mockResolvedValue({ success: true, branch: 'backup-1' })
}));
@@ -20,7 +30,8 @@ vi.mock('../services/apps.js', () => ({
import standardizeRoutes from './standardize.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { standardizeRefusalFor, analyzeApp, applyStandardization, createGitBackup } from '../services/pm2Standardizer.js';
-import { getAppById } from '../services/apps.js';
+import { getAppById, updateApp } from '../services/apps.js';
+import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';
function makeApp() {
const app = express();
@@ -37,10 +48,22 @@ function expectNoStandardizerWork() {
expect(createGitBackup).not.toHaveBeenCalled();
}
+const validPlan = () => ({
+ currentState: { hasGit: true },
+ proposedChanges: {
+ createEcosystem: true,
+ ecosystemContent: 'module.exports = { apps: [] };',
+ processes: [{ name: 'example-api' }],
+ strayPorts: [{ file: '.env', variable: 'PORT', value: 3000, line: 1, action: 'remove' }]
+ }
+});
+
describe('standardize routes — target resolution and the refusal gate', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(standardizeRefusalFor).mockReturnValue(null);
+ vi.mocked(isWithinAllowedRoots).mockReturnValue(true);
+ vi.mocked(applyStandardization).mockResolvedValue({ success: true, filesModified: [], backupBranch: null });
});
it('resolves an allowed app to its repoPath and proceeds', async () => {
@@ -100,7 +123,7 @@ describe('standardize routes — target resolution and the refusal gate', () =>
expectNoStandardizerWork();
});
- it('takes a bare repoPath at face value — there is no app record to type-check', async () => {
+ it('resolves a bare repoPath without an app record to type-check', async () => {
const res = await request(makeApp()).post('/api/standardize/backup').send({ repoPath: '/srv/loose-repo' });
expect(res.status).toBe(200);
@@ -109,6 +132,66 @@ describe('standardize routes — target resolution and the refusal gate', () =>
expect(createGitBackup).toHaveBeenCalledWith('/srv/loose-repo');
});
+ it('validates and applies a standardization plan successfully', async () => {
+ vi.mocked(getAppById).mockResolvedValue({ id: 'app-1', type: 'vite+express', repoPath: '/srv/example-app' });
+
+ const plan = validPlan();
+ const res = await request(makeApp())
+ .post('/api/standardize/apply')
+ .send({ appId: 'app-1', plan });
+
+ expect(res.status).toBe(200);
+ expect(applyStandardization).toHaveBeenCalledWith('/srv/example-app', plan, { overwriteEcosystem: false });
+ expect(updateApp).toHaveBeenCalledWith('app-1', { pm2ProcessNames: ['example-api'] });
+ });
+
+ it('returns the standard error envelope when apply reports failure', async () => {
+ vi.mocked(applyStandardization).mockResolvedValue({
+ success: false,
+ error: 'Working tree has uncommitted changes',
+ filesModified: [],
+ errors: ['Working tree has uncommitted changes']
+ });
+
+ const res = await request(makeApp())
+ .post('/api/standardize/apply')
+ .send({ repoPath: '/srv/example-app', plan: validPlan() });
+
+ expect(res.status).toBe(400);
+ expect(res.body).toEqual(expect.objectContaining({
+ error: 'Working tree has uncommitted changes',
+ code: 'APPLY_FAILED',
+ timestamp: expect.any(Number)
+ }));
+ expect(res.body.success).toBeUndefined();
+ expect(updateApp).not.toHaveBeenCalled();
+ });
+
+ it('rejects a hostile plan that traverses outside the target repo', async () => {
+ const plan = validPlan();
+ plan.proposedChanges.strayPorts[0].file = '../../outside.env';
+
+ const res = await request(makeApp())
+ .post('/api/standardize/apply')
+ .send({ repoPath: '/srv/example-app', plan });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(applyStandardization).not.toHaveBeenCalled();
+ });
+
+ it('rejects a target outside the allowed workspace roots before applying', async () => {
+ vi.mocked(isWithinAllowedRoots).mockReturnValue(false);
+
+ const res = await request(makeApp())
+ .post('/api/standardize/apply')
+ .send({ repoPath: '/private/example-app', plan: validPlan() });
+
+ expect(res.status).toBe(403);
+ expect(res.body.code).toBe('FORBIDDEN');
+ expect(applyStandardization).not.toHaveBeenCalled();
+ });
+
it('400s when neither repoPath nor appId is supplied', async () => {
const res = await request(makeApp()).post('/api/standardize/analyze').send({});