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
feat([issue-1089]): document detect/repo trust model + optional PORTOS_WORKSPACE_ROOTS scoping
Adam Eivy4bd565e3b04a
diff --git a/server/lib/README.md b/server/lib/README.mdindex 4845e6c9d8..39bace10c7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -212,6 +212,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). || `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |+| `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), `isWithinAllowedRoots(realPath)`, and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Used by `routes/commands.js` (always scoped) and `routes/detect.js` (scoped only when configured). || `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |## Test supportdiff --git a/server/lib/index.js b/server/lib/index.jsindex 0f0cc4a9db..d653a98b8c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -179,6 +179,7 @@ export * from './singleFlight.js';export * from './streamBackpressure.js';export * from './sseUtils.js';export * from './uuid.js';+export * from './workspaceRoots.js';export * from './zodCompat.js';// === Test support (consumed by *.test.js files) ===diff --git a/server/lib/workspaceRoots.js b/server/lib/workspaceRoots.jsnew file mode 100644index 0000000000..1a0dc083d6--- /dev/null+++ b/server/lib/workspaceRoots.js@@ -0,0 +1,49 @@+import { realpathSync } from 'fs';+import { resolve, relative, isAbsolute } from 'path';+import { homedir } from 'os';++// Allowed workspace roots shared by routes that accept a caller-supplied+// filesystem path (command execution scoping in `routes/commands.js`, repo+// detection in `routes/detect.js`).+//+// Defaults cover common single-user Tailscale deployments (home + /tmp ++// /Users so multiple macOS accounts' repos work, plus /Volumes for external+// drives and /opt for Linux server layouts). Operators can extend via+// PORTOS_WORKSPACE_ROOTS="/path1:/path2" if their repos live somewhere more+// exotic.+//+// Roots are symlink-resolved (e.g. /tmp -> /private/tmp on macOS) so a path+// the caller passed and we realpath() still matches.+export const DEFAULT_WORKSPACE_ROOTS = [homedir(), '/tmp', '/Users', '/Volumes', '/opt'];++export const EXTRA_WORKSPACE_ROOTS = (process.env.PORTOS_WORKSPACE_ROOTS || '')+ .split(':')+ .map(s => s.trim())+ .filter(Boolean);++// True when the operator has explicitly configured PORTOS_WORKSPACE_ROOTS.+// Routes that are permissive by default (detect) opt into root-restriction+// only when this is set; routes that always scope (command execution) ignore+// it and enforce against ALLOWED_WORKSPACE_ROOTS unconditionally.+export const WORKSPACE_ROOTS_CONFIGURED = EXTRA_WORKSPACE_ROOTS.length > 0;++export const ALLOWED_WORKSPACE_ROOTS = [...DEFAULT_WORKSPACE_ROOTS, ...EXTRA_WORKSPACE_ROOTS]+ .map(r => {+ const abs = resolve(r);+ // Falls back to the resolved path if the root doesn't exist yet — callers+ // providing paths under a non-existent root will fail the existence check.+ try { return realpathSync(abs); } catch { return abs; }+ });++// Separator-safe containment: resolvedPath === root or is a descendant of root.+export function isWithinRoot(resolvedPath, root) {+ if (resolvedPath === root) return true;+ const rel = relative(root, resolvedPath);+ return !!rel && !rel.startsWith('..') && !isAbsolute(rel);+}++// True when a symlink-resolved path sits inside any allowed root. Callers must+// pass an already-realpath()'d path so a symlink can't escape the check.+export function isWithinAllowedRoots(realPath) {+ return ALLOWED_WORKSPACE_ROOTS.some(root => isWithinRoot(realPath, root));+}diff --git a/server/lib/workspaceRoots.test.js b/server/lib/workspaceRoots.test.jsnew file mode 100644index 0000000000..fd078ef359--- /dev/null+++ b/server/lib/workspaceRoots.test.js@@ -0,0 +1,54 @@+import { describe, it, expect } from 'vitest';+import { homedir } from 'os';+import { join } from 'path';+import {+ isWithinRoot,+ isWithinAllowedRoots,+ ALLOWED_WORKSPACE_ROOTS,+ DEFAULT_WORKSPACE_ROOTS,+} from './workspaceRoots.js';++describe('isWithinRoot', () => {+ it('returns true when the path IS the root', () => {+ expect(isWithinRoot('/Users/alice', '/Users/alice')).toBe(true);+ });++ it('returns true for a descendant of the root', () => {+ expect(isWithinRoot('/Users/alice/repo', '/Users/alice')).toBe(true);+ expect(isWithinRoot('/Users/alice/repo/src/index.js', '/Users/alice')).toBe(true);+ });++ it('returns false for a path outside the root', () => {+ expect(isWithinRoot('/etc/passwd', '/Users/alice')).toBe(false);+ expect(isWithinRoot('/Users/bob', '/Users/alice')).toBe(false);+ });++ it('is separator-safe — a sibling that shares a name prefix is NOT contained', () => {+ // /Users/alice-evil starts with "/Users/alice" as a string but is not under it.+ expect(isWithinRoot('/Users/alice-evil/repo', '/Users/alice')).toBe(false);+ });++ it('does not treat a parent as contained', () => {+ expect(isWithinRoot('/Users', '/Users/alice')).toBe(false);+ });+});++describe('isWithinAllowedRoots', () => {+ it('accepts a path under a default root (home dir)', () => {+ expect(isWithinAllowedRoots(join(homedir(), 'projects', 'foo'))).toBe(true);+ });++ it('rejects a path outside every allowed root', () => {+ // /etc is not in DEFAULT_WORKSPACE_ROOTS and (in tests) PORTOS_WORKSPACE_ROOTS is unset.+ expect(isWithinAllowedRoots('/etc/shadow')).toBe(false);+ });+});++describe('ALLOWED_WORKSPACE_ROOTS', () => {+ it('includes every default root', () => {+ // Defaults are symlink-resolved, so compare on length/non-empty rather than+ // exact strings (e.g. /tmp -> /private/tmp on macOS).+ expect(ALLOWED_WORKSPACE_ROOTS.length).toBeGreaterThanOrEqual(DEFAULT_WORKSPACE_ROOTS.length);+ expect(ALLOWED_WORKSPACE_ROOTS.every(r => typeof r === 'string' && r.length > 0)).toBe(true);+ });+});diff --git a/server/routes/commands.js b/server/routes/commands.jsindex b6c6aec08b..e424f3ca0b 100644--- a/server/routes/commands.js+++ b/server/routes/commands.js@@ -1,40 +1,13 @@import { Router } from 'express';import { existsSync, statSync, realpathSync } from 'fs';-import { resolve, relative, isAbsolute } from 'path';-import { homedir } from 'os';+import { resolve } from 'path';import * as commands from '../services/commands.js';import * as pm2Service from '../services/pm2.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';const router = Router();-// Allowed workspace roots. Defaults cover common single-user Tailscale-// deployments (home + /tmp + /Users so multiple macOS accounts' repos work,-// plus /Volumes for external drives and /opt for Linux server layouts).-// Operators can extend via PORTOS_WORKSPACE_ROOTS="/path1:/path2" if their-// repos live somewhere more exotic.-// Resolve symlinks so e.g. /tmp -> /private/tmp on macOS still matches after-// we realpath() the caller's workspacePath.-const DEFAULT_WORKSPACE_ROOTS = [homedir(), '/tmp', '/Users', '/Volumes', '/opt'];-const EXTRA_WORKSPACE_ROOTS = (process.env.PORTOS_WORKSPACE_ROOTS || '')- .split(':')- .map(s => s.trim())- .filter(Boolean);-const ALLOWED_WORKSPACE_ROOTS = [...DEFAULT_WORKSPACE_ROOTS, ...EXTRA_WORKSPACE_ROOTS]- .map(r => {- const abs = resolve(r);- // Falls back to the resolved path if the root doesn't exist yet — callers- // providing paths under a non-existent root will fail the existence check.- try { return realpathSync(abs); } catch { return abs; }- });--// Separator-safe containment: resolvedPath === root or is a descendant of root.-function isWithinRoot(resolvedPath, root) {- if (resolvedPath === root) return true;- const rel = relative(root, resolvedPath);- return !!rel && !rel.startsWith('..') && !isAbsolute(rel);-}-// POST /api/commands/execute - Execute a commandrouter.post('/execute', asyncHandler(async (req, res) => {const { command, workspacePath } = req.body;@@ -67,8 +40,7 @@ router.post('/execute', asyncHandler(async (req, res) => {if (err instanceof ServerError) throw err;throw new ServerError('workspacePath is not accessible', { status: 400, code: 'INVALID_PATH' });}- const isAllowed = ALLOWED_WORKSPACE_ROOTS.some(root => isWithinRoot(realPath, root));- if (!isAllowed) {+ if (!isWithinAllowedRoots(realPath)) {throw new ServerError('workspacePath is outside allowed directories', { status: 400, code: 'INVALID_PATH' });}}diff --git a/server/routes/detect.js b/server/routes/detect.jsindex 3de2d13678..7921f1b63a 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -1,18 +1,35 @@import { Router } from 'express';-import { existsSync } from 'fs';+import { existsSync, realpathSync } from 'fs';import { readFile, stat } from 'fs/promises';-import { join } from 'path';+import { join, resolve } from 'path';import { exec } from 'child_process';import { promisify } from 'util';import { execPm2 } from '../services/pm2.js';import { detectAppWithAi } from '../services/aiDetect.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { isWithinAllowedRoots, WORKSPACE_ROOTS_CONFIGURED } from '../lib/workspaceRoots.js';const execAsync = promisify(exec);const router = Router();// POST /api/detect/repo - Validate repo path and detect project type+//+// TRUST MODEL: This endpoint accepts an arbitrary, caller-supplied filesystem+// path and reads a small set of well-known project files under it (package.json+// scripts + name, project.yml, vite.config, and PORT/VITE_PORT lines from .env),+// returning their values verbatim. This is INTENTIONAL: PortOS is a single-user+// app on a private Tailscale network (see CLAUDE.md "Security Model"), where the+// sole operator legitimately points the "import a repo" flow at any directory on+// their own machine — there is no second user to read data from, so no path+// confinement is required for safety.+//+// Operators who still want to confine detection to specific directories can set+// PORTOS_WORKSPACE_ROOTS="/path1:/path2" (the same allow-list `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 configured roots returns valid:false+// rather than reading its files. When it is unset (the default), detection is+// unrestricted, matching the pre-existing behavior.router.post('/repo', asyncHandler(async (req, res) => {const { path } = req.body;@@ -37,6 +54,18 @@ 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.+ if (WORKSPACE_ROOTS_CONFIGURED) {+ const realPath = realpathSync(resolve(path));+ if (!isWithinAllowedRoots(realPath)) {+ return res.json({+ valid: false,+ error: 'Path is outside the configured workspace roots (PORTOS_WORKSPACE_ROOTS)'+ });+ }+ }+// Detect project typeconst result = {valid: true,