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
refactor([issue-752]): extract appBuilder service from apps.js build route
[._.]/ Adam Eivy12422acccab7
diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 2b0911ffce..ee3c54225e 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -7,6 +7,7 @@ import * as appsService from '../services/apps.js';import { notifyAppsChanged, PORTOS_APP_ID } from '../services/apps.js';import * as pm2Service from '../services/pm2.js';import * as appUpdater from '../services/appUpdater.js';+import * as appBuilder from '../services/appBuilder.js';import * as cos from '../services/cos.js';import { logAction } from '../services/history.js';import { z } from 'zod';@@ -673,100 +674,25 @@ router.post('/:id/build', loadApp, asyncHandler(async (req, res) => {throw new ServerError('App repo path does not exist', { status: 400, code: 'PATH_NOT_FOUND' });}- const buildCommand = app.buildCommand || 'npm run build';- const [cmd, ...args] = buildCommand.split(/\s+/);-- if (!ALLOWED_BUILD_CMDS.has(cmd)) {- throw new ServerError(`Build command '${cmd}' is not allowed. Allowed: ${[...ALLOWED_BUILD_CMDS].join(', ')}`, { status: 400, code: 'INVALID_BUILD_COMMAND' });- }-- if (needsShell(cmd) && args.some(a => SHELL_UNSAFE_RE.test(a))) {- throw new ServerError('Build command args contain shell-unsafe characters', { status: 400, code: 'INVALID_BUILD_COMMAND' });- }-- console.log(`🔨 Building ${app.name}: ${buildCommand}`);-- // Install dependencies before building (root + common subdirs) - skip for non-Node apps- // For self-builds, skip server/ install to avoid triggering PM2 watch restart- const isNodeApp = ['npm', 'npx'].includes(cmd);- const isSelfBuild = app.id === 'portos-default';- const installDirs = isNodeApp ? ['', 'client', ...(isSelfBuild ? [] : ['server']), 'admin'] : [];- for (const sub of installDirs) {- const subDir = sub ? join(app.repoPath, sub) : app.repoPath;- if (await pathExists(join(subDir, 'package.json'))) {- const label = sub || 'root';- console.log(`📦 Installing ${label} dependencies for ${app.name}`);- const installResult = await new Promise((resolve) => {- const child = spawn('npm', ['install'], { cwd: subDir, windowsHide: true, shell: needsShell('npm') });- let stdout = '';- let stderr = '';- let settled = false;- const MAX = 64 * 1024;- const timer = setTimeout(() => {- if (!settled) { settled = true; killProc(child); resolve({ success: false, exitCode: -1, output: `npm install timed out after ${INSTALL_TIMEOUT_MS / 1000}s` }); }- }, INSTALL_TIMEOUT_MS);- child.stdout.on('data', d => { stdout += d; if (stdout.length > MAX) stdout = stdout.slice(-MAX); });- child.stderr.on('data', d => { stderr += d; if (stderr.length > MAX) stderr = stderr.slice(-MAX); });- child.on('close', exitCode => { if (!settled) { settled = true; clearTimeout(timer); resolve({ success: exitCode === 0, exitCode, output: (stderr.trim() || stdout.trim()).slice(-1024) }); } });- child.on('error', err => { if (!settled) { settled = true; clearTimeout(timer); resolve({ success: false, exitCode: -1, output: err.message }); } });- });- if (!installResult.success) {- console.log(`❌ npm install (${label}) exit=${installResult.exitCode}: ${installResult.output.slice(-300)}`);- await logAction('build', app.id, app.name, { buildCommand, step: `npm install (${label})` }, false);- throw new ServerError(`npm install failed (${label}) exit=${installResult.exitCode}: ${installResult.output}`, { status: 500, code: 'INSTALL_FAILED' });- }- }+ const result = await appBuilder.buildApp(app);++ if (result.failure === 'validation') {+ throw new ServerError(result.message, { status: 400, code: result.code });}- const result = await new Promise((resolve) => {- const child = spawn(cmd, args, { cwd: app.repoPath, windowsHide: true, shell: needsShell(cmd) });- let stdout = '';- let stderr = '';- let settled = false;- const MAX = 64 * 1024;- const timer = setTimeout(() => {- if (!settled) {- settled = true;- killProc(child);- const timeoutMsg = `Build timed out after ${BUILD_TIMEOUT_MS / 1000}s`;- const tail = (stderr.trim() || stdout.trim()).slice(-512);- resolve({ success: false, stderr: timeoutMsg, code: -1, output: tail ? `${timeoutMsg} — last output: ${tail}` : timeoutMsg });- }- }, BUILD_TIMEOUT_MS);- child.stdout.on('data', d => {- stdout += d;- if (stdout.length > MAX) stdout = stdout.slice(-MAX);- });- child.stderr.on('data', d => {- stderr += d;- if (stderr.length > MAX) stderr = stderr.slice(-MAX);- });- child.on('close', (code, signal) => {- if (!settled) {- settled = true;- clearTimeout(timer);- const output = (stderr.trim() || stdout.trim()).slice(-1024);- resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim(), code, signal, output });- }- });- child.on('error', err => {- if (!settled) {- settled = true;- clearTimeout(timer);- resolve({ success: false, stderr: err.message, code: -1, signal: null, output: err.message });- }- });- });+ if (result.failure === 'install') {+ await logAction('build', app.id, app.name, { buildCommand: result.buildCommand, step: `npm install (${result.label})` }, false);+ throw new ServerError(`npm install failed (${result.label}) exit=${result.exitCode}: ${result.output}`, { status: 500, code: 'INSTALL_FAILED' });+ }- await logAction('build', app.id, app.name, { buildCommand }, result.success);- console.log(`${result.success ? '✅' : '❌'} Build ${result.success ? 'complete' : 'failed'} for ${app.name}`);+ await logAction('build', app.id, app.name, { buildCommand: result.buildCommand }, result.success);if (!result.success) {const detail = result.signal ? `killed by ${result.signal}` : result.output || `exit code ${result.code}`;throw new ServerError(`Build failed: ${detail}`, { status: 500, code: 'BUILD_FAILED' });}- res.json({ success: true, output: result.stdout });+ res.json({ success: true, output: result.output });}));// GET /api/apps/:id/status - Get PM2 status@@ -804,37 +730,6 @@ router.get('/:id/logs', loadApp, asyncHandler(async (req, res) => {res.json({ processName, lines, logs });}));-// Allowlist of safe build commands-const ALLOWED_BUILD_CMDS = new Set([- 'npm', // Node.js- 'npx', // Node.js- 'xcodebuild', // Xcode- 'swift', // Swift Package Manager- 'make', // Make- 'cargo' // Rust-]);--const IS_WIN32 = process.platform === 'win32';-// npm/npx are .cmd shims on Windows — enable shell only for these so cmd.exe-// can resolve them, without enabling shell metacharacter interpretation for-// native binaries (xcodebuild, swift, make, cargo).-const WIN_CMD_SHIMS = new Set(['npm', 'npx']);-const needsShell = (cmd) => IS_WIN32 && WIN_CMD_SHIMS.has(cmd);-// Actual cmd.exe metacharacters (& | < > ^ % ! and grouping parens).-// Validated only when shell is active (needsShell guard at call site).-const SHELL_UNSAFE_RE = /[&|<>^%!()]/;-// On Windows, SIGTERM kills cmd.exe but orphans its child (npm). Use taskkill-// /T /F to terminate the whole process tree.-const killProc = (child) => {- if (IS_WIN32 && child.pid) {- spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();- } else {- child.kill('SIGTERM');- }-};-const INSTALL_TIMEOUT_MS = 3 * 60 * 1000;-const BUILD_TIMEOUT_MS = 5 * 60 * 1000;-// Allowlist of safe editor commands// Security: Only allow known-safe editor commands to prevent arbitrary code executionconst ALLOWED_EDITORS = new Set([diff --git a/server/services/appBuilder.js b/server/services/appBuilder.jsnew file mode 100644index 0000000000..96f6d5d718--- /dev/null+++ b/server/services/appBuilder.js@@ -0,0 +1,178 @@+import { spawn } from 'child_process';+import { join } from 'path';+import { access } from 'fs/promises';++/** Async equivalent of existsSync — returns true if the path is accessible */+const pathExists = (p) => access(p).then(() => true).catch(() => false);++// Allowlist of safe build commands+export const ALLOWED_BUILD_CMDS = new Set([+ 'npm', // Node.js+ 'npx', // Node.js+ 'xcodebuild', // Xcode+ 'swift', // Swift Package Manager+ 'make', // Make+ 'cargo' // Rust+]);++const IS_WIN32 = process.platform === 'win32';+// npm/npx are .cmd shims on Windows — enable shell only for these so cmd.exe+// can resolve them, without enabling shell metacharacter interpretation for+// native binaries (xcodebuild, swift, make, cargo).+const WIN_CMD_SHIMS = new Set(['npm', 'npx']);+const needsShell = (cmd) => IS_WIN32 && WIN_CMD_SHIMS.has(cmd);+// Actual cmd.exe metacharacters (& | < > ^ % ! and grouping parens).+// Validated only when shell is active (needsShell guard at call site).+const SHELL_UNSAFE_RE = /[&|<>^%!()]/;+// On Windows, SIGTERM kills cmd.exe but orphans its child (npm). Use taskkill+// /T /F to terminate the whole process tree.+const killProc = (child) => {+ if (IS_WIN32 && child.pid) {+ spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();+ } else {+ child.kill('SIGTERM');+ }+};+const INSTALL_TIMEOUT_MS = 3 * 60 * 1000;+const BUILD_TIMEOUT_MS = 5 * 60 * 1000;+const MAX_OUTPUT_BYTES = 64 * 1024;++/**+ * Validate and split a build command.+ * @returns {{ ok: true, cmd, args }} when valid, or+ * {{ ok: false, message, code: 'INVALID_BUILD_COMMAND' }} when not —+ * so the route can map a bad command to HTTP 400 without try/catch.+ */+export function parseBuildCommand(buildCommand) {+ const [cmd, ...args] = (buildCommand || 'npm run build').split(/\s+/);++ if (!ALLOWED_BUILD_CMDS.has(cmd)) {+ return {+ ok: false,+ code: 'INVALID_BUILD_COMMAND',+ message: `Build command '${cmd}' is not allowed. Allowed: ${[...ALLOWED_BUILD_CMDS].join(', ')}`+ };+ }++ if (needsShell(cmd) && args.some(a => SHELL_UNSAFE_RE.test(a))) {+ return { ok: false, code: 'INVALID_BUILD_COMMAND', message: 'Build command args contain shell-unsafe characters' };+ }++ return { ok: true, cmd, args };+}++/**+ * Run `npm install` in a single directory.+ * @returns {Promise<{success, exitCode, output}>} — resolves (never rejects).+ */+function runNpmInstall(subDir) {+ return new Promise((resolve) => {+ const child = spawn('npm', ['install'], { cwd: subDir, windowsHide: true, shell: needsShell('npm') });+ let stdout = '';+ let stderr = '';+ let settled = false;+ const timer = setTimeout(() => {+ if (!settled) { settled = true; killProc(child); resolve({ success: false, exitCode: -1, output: `npm install timed out after ${INSTALL_TIMEOUT_MS / 1000}s` }); }+ }, INSTALL_TIMEOUT_MS);+ child.stdout.on('data', d => { stdout += d; if (stdout.length > MAX_OUTPUT_BYTES) stdout = stdout.slice(-MAX_OUTPUT_BYTES); });+ child.stderr.on('data', d => { stderr += d; if (stderr.length > MAX_OUTPUT_BYTES) stderr = stderr.slice(-MAX_OUTPUT_BYTES); });+ child.on('close', exitCode => { if (!settled) { settled = true; clearTimeout(timer); resolve({ success: exitCode === 0, exitCode, output: (stderr.trim() || stdout.trim()).slice(-1024) }); } });+ child.on('error', err => { if (!settled) { settled = true; clearTimeout(timer); resolve({ success: false, exitCode: -1, output: err.message }); } });+ });+}++/**+ * Run the build command in `repoPath`.+ * @returns {Promise<{success, stdout, stderr, code, signal, output}>} — resolves (never rejects).+ */+function runBuild(cmd, args, repoPath) {+ return new Promise((resolve) => {+ const child = spawn(cmd, args, { cwd: repoPath, windowsHide: true, shell: needsShell(cmd) });+ let stdout = '';+ let stderr = '';+ let settled = false;+ const timer = setTimeout(() => {+ if (!settled) {+ settled = true;+ killProc(child);+ const timeoutMsg = `Build timed out after ${BUILD_TIMEOUT_MS / 1000}s`;+ const tail = (stderr.trim() || stdout.trim()).slice(-512);+ resolve({ success: false, stderr: timeoutMsg, code: -1, output: tail ? `${timeoutMsg} — last output: ${tail}` : timeoutMsg });+ }+ }, BUILD_TIMEOUT_MS);+ child.stdout.on('data', d => {+ stdout += d;+ if (stdout.length > MAX_OUTPUT_BYTES) stdout = stdout.slice(-MAX_OUTPUT_BYTES);+ });+ child.stderr.on('data', d => {+ stderr += d;+ if (stderr.length > MAX_OUTPUT_BYTES) stderr = stderr.slice(-MAX_OUTPUT_BYTES);+ });+ child.on('close', (code, signal) => {+ if (!settled) {+ settled = true;+ clearTimeout(timer);+ const output = (stderr.trim() || stdout.trim()).slice(-1024);+ resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim(), code, signal, output });+ }+ });+ child.on('error', err => {+ if (!settled) {+ settled = true;+ clearTimeout(timer);+ resolve({ success: false, stderr: err.message, code: -1, signal: null, output: err.message });+ }+ });+ });+}++/**+ * Build an app's production UI: install dependencies (root + common subdirs for+ * Node apps) then run the validated build command.+ *+ * Resolves (never rejects) with a structured result the route maps to HTTP:+ * - { success: false, failure: 'validation', code, message } → 400+ * - { success: false, failure: 'install', label, exitCode, output } → 500+ * - { success: false, failure: 'build', code, signal, output } → 500+ * - { success: true, output } (build stdout) → 200+ *+ * @param {object} app - app object (id, name, repoPath, buildCommand?)+ * @returns {Promise<object>} structured build result+ */+export async function buildApp(app) {+ const buildCommand = app.buildCommand || 'npm run build';+ const parsed = parseBuildCommand(app.buildCommand);+ if (!parsed.ok) {+ return { success: false, failure: 'validation', code: parsed.code, message: parsed.message, buildCommand };+ }+ const { cmd, args } = parsed;++ console.log(`🔨 Building ${app.name}: ${buildCommand}`);++ // Install dependencies before building (root + common subdirs) - skip for non-Node apps+ // For self-builds, skip server/ install to avoid triggering PM2 watch restart+ const isNodeApp = ['npm', 'npx'].includes(cmd);+ const isSelfBuild = app.id === 'portos-default';+ const installDirs = isNodeApp ? ['', 'client', ...(isSelfBuild ? [] : ['server']), 'admin'] : [];+ for (const sub of installDirs) {+ const subDir = sub ? join(app.repoPath, sub) : app.repoPath;+ if (await pathExists(join(subDir, 'package.json'))) {+ const label = sub || 'root';+ console.log(`📦 Installing ${label} dependencies for ${app.name}`);+ const installResult = await runNpmInstall(subDir);+ if (!installResult.success) {+ console.log(`❌ npm install (${label}) exit=${installResult.exitCode}: ${installResult.output.slice(-300)}`);+ return { success: false, failure: 'install', label, exitCode: installResult.exitCode, output: installResult.output, buildCommand };+ }+ }+ }++ const result = await runBuild(cmd, args, app.repoPath);+ console.log(`${result.success ? '✅' : '❌'} Build ${result.success ? 'complete' : 'failed'} for ${app.name}`);++ if (!result.success) {+ return { success: false, failure: 'build', code: result.code, signal: result.signal, output: result.output, buildCommand };+ }++ return { success: true, output: result.stdout, buildCommand };+}diff --git a/server/services/appBuilder.test.js b/server/services/appBuilder.test.jsnew file mode 100644index 0000000000..f969af7751--- /dev/null+++ b/server/services/appBuilder.test.js@@ -0,0 +1,33 @@+import { describe, it, expect } from 'vitest';+import { parseBuildCommand, ALLOWED_BUILD_CMDS } from './appBuilder.js';++describe('appBuilder.parseBuildCommand', () => {+ it('defaults to "npm run build" when no command is provided', () => {+ const result = parseBuildCommand(undefined);+ expect(result).toEqual({ ok: true, cmd: 'npm', args: ['run', 'build'] });+ });++ it('accepts an allowlisted command and splits cmd/args', () => {+ const result = parseBuildCommand('npx vite build');+ expect(result).toEqual({ ok: true, cmd: 'npx', args: ['vite', 'build'] });+ });++ it('accepts all allowlisted native build tools', () => {+ for (const cmd of ALLOWED_BUILD_CMDS) {+ expect(parseBuildCommand(`${cmd} build`).ok).toBe(true);+ }+ });++ it('rejects a non-allowlisted command with INVALID_BUILD_COMMAND', () => {+ const result = parseBuildCommand('rm -rf /');+ expect(result.ok).toBe(false);+ expect(result.code).toBe('INVALID_BUILD_COMMAND');+ expect(result.message).toContain("'rm' is not allowed");+ });++ it.skipIf(process.platform !== 'win32')('rejects shell-unsafe args for npm/npx on Windows', () => {+ const result = parseBuildCommand('npm run build&whoami');+ expect(result.ok).toBe(false);+ expect(result.code).toBe('INVALID_BUILD_COMMAND');+ });+});