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: confine POST /api/detect/ai to PORTOS_WORKSPACE_ROOTS (#5650)

Adam Eivy13cd393c8737
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 7601121cd2..f01a6f5f2e 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -7175,7 +7175,7 @@
"sources": [
{
"source": "server/routes/detect.js",
- "line": 239
+ "line": 263
}
]
},
@@ -7186,7 +7186,7 @@
"sources": [
{
"source": "server/routes/detect.js",
- "line": 215
+ "line": 235
}
]
},
@@ -7197,7 +7197,7 @@
"sources": [
{
"source": "server/routes/detect.js",
- "line": 171
+ "line": 191
}
]
},
@@ -7208,7 +7208,7 @@
"sources": [
{
"source": "server/routes/detect.js",
- "line": 33
+ "line": 70
}
]
},
@@ -18590,7 +18590,7 @@
},
{
"source": "server/routes/providers.js",
- "line": 767
+ "line": 776
}
]
},
@@ -18643,6 +18643,10 @@
{
"source": "server/lib/aiToolkit/routes/providers.js",
"line": 110
+ },
+ {
+ "source": "server/routes/providers.js",
+ "line": 765
}
]
},
@@ -19908,7 +19912,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 154
+ "line": 159
}
]
},
@@ -19919,7 +19923,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 218
+ "line": 223
}
]
},
@@ -19930,7 +19934,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 490
+ "line": 498
}
]
},
@@ -19941,7 +19945,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 231
+ "line": 236
}
]
},
@@ -19952,7 +19956,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 476
+ "line": 484
}
]
},
@@ -19963,7 +19967,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 278
+ "line": 283
}
]
},
@@ -19974,7 +19978,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 485
+ "line": 493
}
]
},
@@ -19985,7 +19989,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 455
+ "line": 463
}
]
},
@@ -19996,7 +20000,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 468
+ "line": 476
}
]
},
@@ -20007,7 +20011,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 336
+ "line": 344
}
]
},
@@ -20018,7 +20022,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 463
+ "line": 471
}
]
},
@@ -20029,7 +20033,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 286
+ "line": 291
}
]
},
@@ -20040,7 +20044,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 306
+ "line": 314
}
]
},
@@ -20051,7 +20055,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 322
+ "line": 330
}
]
},
@@ -20062,7 +20066,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 329
+ "line": 337
}
]
},
@@ -20073,7 +20077,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 314
+ "line": 322
}
]
},
@@ -20084,7 +20088,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 365
+ "line": 373
}
]
},
@@ -20095,7 +20099,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 358
+ "line": 366
}
]
},
@@ -20106,7 +20110,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 372
+ "line": 380
}
]
},
@@ -20117,7 +20121,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 381
+ "line": 389
}
]
},
@@ -20128,7 +20132,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 344
+ "line": 352
}
]
},
@@ -20139,7 +20143,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 414
+ "line": 422
}
]
},
@@ -20150,7 +20154,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 399
+ "line": 407
}
]
},
@@ -20161,7 +20165,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 423
+ "line": 431
}
]
},
@@ -20172,7 +20176,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 440
+ "line": 448
}
]
},
@@ -20183,7 +20187,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 407
+ "line": 415
}
]
},
@@ -20194,7 +20198,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 447
+ "line": 455
}
]
},
@@ -20205,7 +20209,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 390
+ "line": 398
}
]
},
@@ -20216,7 +20220,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 212
+ "line": 217
}
]
},
@@ -20227,7 +20231,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 183
+ "line": 188
}
]
},
@@ -20238,7 +20242,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 187
+ "line": 192
}
]
},
@@ -20249,7 +20253,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 198
+ "line": 203
}
]
},
@@ -20260,7 +20264,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 192
+ "line": 197
}
]
},
@@ -20271,7 +20275,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 226
+ "line": 231
}
]
},
@@ -20282,7 +20286,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 165
+ "line": 170
}
]
},
@@ -20293,7 +20297,7 @@
"sources": [
{
"source": "server/routes/sprites.js",
- "line": 171
+ "line": 176
}
]
},
@@ -23865,7 +23869,7 @@
"stats": {
"mounts": 147,
"operations": 2153,
- "declarations": 2156,
+ "declarations": 2157,
"sourceFiles": 229
}
}
diff --git a/server/lib/workspaceRoots.js b/server/lib/workspaceRoots.js
index 10ac8cb503..6867663c44 100644
--- a/server/lib/workspaceRoots.js
+++ b/server/lib/workspaceRoots.js
@@ -3,9 +3,15 @@ import { resolve, relative, isAbsolute, delimiter, basename } from 'path';
import { homedir, tmpdir } from 'os';
// Allowed workspace roots shared by routes that accept a caller-supplied
-// filesystem path: command execution (`routes/commands.js`), repo detection
-// (`routes/detect.js`), scaffolding (`routes/scaffold.js`), submodule reads
-// (`routes/git.js`).
+// filesystem path: command execution (`routes/commands.js`), scaffolding
+// (`routes/scaffold.js`), submodule reads (`routes/git.js`), and detection
+// (`routes/detect.js`).
+//
+// Coverage is per-HANDLER, not per-file — a route module listed here does not
+// imply every handler in it is scoped. In `routes/detect.js` the two handlers
+// that take a path (`POST /repo`, `POST /ai`) both go through one shared
+// `checkWorkspacePathAllowed` helper; its other handlers (`POST /port`,
+// `POST /pm2`) take no path at all.
//
// Repos legitimately live on secondary volumes, so the defaults cover home plus
// the places each platform mounts them: /Volumes (macOS), /mnt + /media (Linux),
diff --git a/server/routes/detect.js b/server/routes/detect.js
index 3922e57b56..9f130cc95d 100644
--- a/server/routes/detect.js
+++ b/server/routes/detect.js
@@ -13,6 +13,42 @@ import { isWithinAllowedRoots, outsideAllowedRootsMessage, WORKSPACE_ROOTS_CONFI
const execAsync = promisify(exec);
const router = Router();
+// Optional confinement, shared by every handler here that takes a caller-supplied
+// path (POST /repo and POST /ai): enforced only when the operator has configured
+// PORTOS_WORKSPACE_ROOTS. realpath() first so a symlink can't smuggle a path past
+// the containment check. realpathSync can throw on a permission/TOCTOU edge (the
+// path deleted between an earlier stat and here) — reported as a refusal rather
+// than leaking a 500. This is the sanctioned fs-edge-case exception to the
+// no-try/catch rule (see commands.js).
+//
+// Returns { ok: true } or { ok: false, error, code } so each caller shapes the
+// refusal its own way: /repo answers with its valid:false verdict (deciding
+// "is this a usable repo?" is that route's whole product), while /ai — which has
+// no such field, and where {success:false} could not be told apart from
+// "provider unavailable" — throws a 400. The resolved path stays out of both,
+// appearing only in the redacted server-side diagnostic.
+const checkWorkspacePathAllowed = (path) => {
+ if (!WORKSPACE_ROOTS_CONFIGURED) return { ok: true };
+
+ let realPath;
+ try {
+ realPath = realpathSync(resolve(path));
+ } catch {
+ return { ok: false, error: 'Path is not accessible', code: 'PATH_NOT_ACCESSIBLE' };
+ }
+
+ if (!isWithinAllowedRoots(realPath)) {
+ console.error(`❌ ${outsideAllowedRootsMessage(realPath)}`);
+ return {
+ ok: false,
+ error: 'Path is outside the configured workspace roots (PORTOS_WORKSPACE_ROOTS)',
+ code: 'PATH_OUTSIDE_WORKSPACE_ROOTS'
+ };
+ }
+
+ return { ok: true };
+};
+
// POST /api/detect/repo - Validate repo path and detect project type
//
// TRUST MODEL: This endpoint accepts an arbitrary, caller-supplied filesystem
@@ -29,7 +65,8 @@ const router = Router();
// `routes/commands.js` uses to scope command execution). When that env var is set,
// this route enforces the allow-list too — a path outside the roots returns valid:false
// rather than reading its files. When it is unset (the default), detection is
-// unrestricted, matching the pre-existing behavior.
+// unrestricted, matching the pre-existing behavior. POST /ai enforces the same
+// allow-list via the shared `checkWorkspacePathAllowed` helper above.
router.post('/repo', asyncHandler(async (req, res) => {
const { path } = req.body;
@@ -54,26 +91,9 @@ router.post('/repo', asyncHandler(async (req, res) => {
});
}
- // Optional confinement: only when the operator has configured workspace roots.
- // realpath() first so a symlink can't smuggle a path past the containment check.
- // realpathSync can throw on a permission/TOCTOU edge (path deleted between the
- // stat above and here) — convert that to the same valid:false shape the rest of
- // this route returns for unusable paths, rather than leaking a 500. This is the
- // sanctioned fs-edge-case exception to the no-try/catch rule (see commands.js).
- if (WORKSPACE_ROOTS_CONFIGURED) {
- let realPath;
- try {
- realPath = realpathSync(resolve(path));
- } catch {
- return res.json({ valid: false, error: 'Path is not accessible' });
- }
- if (!isWithinAllowedRoots(realPath)) {
- console.error(`❌ ${outsideAllowedRootsMessage(realPath)}`);
- return res.json({
- valid: false,
- error: 'Path is outside the configured workspace roots (PORTOS_WORKSPACE_ROOTS)'
- });
- }
+ const confinement = checkWorkspacePathAllowed(path);
+ if (!confinement.ok) {
+ return res.json({ valid: false, error: confinement.error });
}
// Detect project type
@@ -236,6 +256,10 @@ router.post('/pm2', asyncHandler(async (req, res) => {
}));
// POST /api/detect/ai - AI-powered app detection
+// Unlike /repo this reads package.json, config files, .env port lines and the
+// README, then ships them to a configured AI provider (possibly a hosted API) and
+// runs that provider's CLI with cwd set here — so the confinement check must run
+// BEFORE detectAppWithAi, or a refused path has already left the machine.
router.post('/ai', asyncHandler(async (req, res) => {
const { path, providerId } = req.body;
@@ -243,6 +267,11 @@ router.post('/ai', asyncHandler(async (req, res) => {
throw new ServerError('Path is required', { status: 400, code: 'MISSING_PATH' });
}
+ const confinement = checkWorkspacePathAllowed(path);
+ if (!confinement.ok) {
+ throw new ServerError(confinement.error, { status: 400, code: confinement.code });
+ }
+
const result = await detectAppWithAi(path, providerId);
res.json(result);
diff --git a/server/routes/detect.test.js b/server/routes/detect.test.js
index 3570005acc..db3b007ea5 100644
--- a/server/routes/detect.test.js
+++ b/server/routes/detect.test.js
@@ -1,5 +1,8 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
+import { mkdtempSync, realpathSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
import { errorMiddleware } from '../lib/errorHandler.js';
import { request } from '../lib/testHelper.js';
import detectRoutes from './detect.js';
@@ -44,3 +47,82 @@ describe('Detect Routes', () => {
expect(response.body).not.toHaveProperty('success');
});
});
+
+// PORTOS_WORKSPACE_ROOTS is read once at module load, so these stub the env and
+// re-import a fresh copy of the route graph. The module-registry reset drops the
+// hoisted vi.mock above with it, so the AI service is re-mocked per load via
+// vi.doMock (which applies to subsequent dynamic imports).
+describe('POST /api/detect/ai workspace-root confinement', () => {
+ let roots;
+ let outside;
+
+ const loadApp = async (workspaceRoots) => {
+ vi.resetModules();
+ vi.stubEnv('PORTOS_WORKSPACE_ROOTS', workspaceRoots);
+ const detect = vi.fn();
+ vi.doMock('../services/aiDetect.js', () => ({ detectAppWithAi: detect }));
+ const routes = await import('./detect.js');
+ const errors = await import('../lib/errorHandler.js');
+ const scoped = express();
+ scoped.use(express.json());
+ scoped.use('/api/detect', routes.default);
+ scoped.use(errors.errorMiddleware);
+ return { app: scoped, detect };
+ };
+
+ beforeEach(() => {
+ // realpathSync so macOS's /var -> /private/var symlink doesn't make the
+ // configured root and the resolved request path disagree.
+ roots = realpathSync(mkdtempSync(join(tmpdir(), 'portos-roots-')));
+ outside = realpathSync(mkdtempSync(join(tmpdir(), 'portos-outside-')));
+ });
+
+ afterEach(() => {
+ vi.doUnmock('../services/aiDetect.js');
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ rmSync(roots, { recursive: true, force: true });
+ rmSync(outside, { recursive: true, force: true });
+ });
+
+ it('refuses a path outside the configured roots without invoking the provider', async () => {
+ const { app: scoped, detect } = await loadApp(roots);
+
+ const response = await request(scoped)
+ .post('/api/detect/ai')
+ .send({ path: outside });
+
+ expect(response.status).toBe(400);
+ expect(response.body).toMatchObject({ code: 'PATH_OUTSIDE_WORKSPACE_ROOTS' });
+ // The refusal must not echo the rejected filesystem path back to the caller.
+ expect(JSON.stringify(response.body)).not.toContain(outside);
+ // The regression this uniquely catches: no file was read and nothing was
+ // shipped to a (possibly hosted) AI provider.
+ expect(detect).not.toHaveBeenCalled();
+ });
+
+ it('allows a path inside the configured roots', async () => {
+ const { app: scoped, detect } = await loadApp(roots);
+ detect.mockResolvedValue({ success: true, app: { name: 'example' } });
+
+ const response = await request(scoped)
+ .post('/api/detect/ai')
+ .send({ path: roots });
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ success: true, app: { name: 'example' } });
+ expect(detect).toHaveBeenCalledWith(roots, undefined);
+ });
+
+ it('stays unrestricted when PORTOS_WORKSPACE_ROOTS is unset', async () => {
+ const { app: scoped, detect } = await loadApp('');
+ detect.mockResolvedValue({ success: true, app: { name: 'example' } });
+
+ const response = await request(scoped)
+ .post('/api/detect/ai')
+ .send({ path: outside });
+
+ expect(response.status).toBe(200);
+ expect(detect).toHaveBeenCalledWith(outside, undefined);
+ });
+});