Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: contain Code Animation production workers in an enforced sandbox (#9388)

[._.]/ Adam Eivy6a3aa339014d
diff --git a/client/src/components/codeAnimation/ProductionContainment.jsx b/client/src/components/codeAnimation/ProductionContainment.jsx
new file mode 100644
index 0000000000..e84c9fdb9f
--- /dev/null
+++ b/client/src/components/codeAnimation/ProductionContainment.jsx
@@ -0,0 +1,55 @@
+import { useEffect, useState } from 'react';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { getCodeAnimationExecution, probeCodeAnimationExecution, updateCodeAnimationExecutionTools } from '../../services/apiCodeAnimation';
+import { formatCount } from '../../utils/formatters';
+
+const buttonClass = 'rounded border border-port-border px-3 py-2 text-sm hover:border-port-accent disabled:opacity-50';
+
+/** Machine-level contained-execution status: fail-closed readiness, operator tool path, on-demand check. */
+export default function ProductionContainment() {
+ const [execution, setExecution] = useState(null);
+ const [blenderPath, setBlenderPath] = useState('');
+ const [savedPath, setSavedPath] = useState('');
+ const apply = (next) => {
+ if (!next) return;
+ setExecution(next);
+ const path = next.tools.blender.executable || '';
+ setSavedPath(path);
+ setBlenderPath(path);
+ };
+ useEffect(() => {
+ let active = true;
+ getCodeAnimationExecution({ silent: true }).then(next => { if (active) apply(next); }, () => {});
+ return () => { active = false; };
+ }, []);
+ const [save, saving] = useAsyncAction(async () => apply(await updateCodeAnimationExecutionTools({ blender: { executable: blenderPath.trim() || null } }, { silent: true })));
+ const [probe, probing] = useAsyncAction(async () => apply(await probeCodeAnimationExecution({ silent: true })));
+ if (!execution) return null;
+ const { mechanism, lanes, probe: result } = execution;
+ const dirty = blenderPath.trim() !== savedPath;
+ return <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4">
+ <h2 className="text-base font-semibold">Contained execution</h2>
+ <p className="text-sm text-gray-400">Production code runs only inside an enforced sandbox with no network, credentials, host APIs or access outside its workspace. Without one, execution is refused.</p>
+ <div className="grid grid-cols-1 gap-2 text-sm md:grid-cols-3">
+ <p>Sandbox: {mechanism.supported ? mechanism.id : <span className="text-port-warning">{mechanism.reason}</span>}</p>
+ <p>Browser lane: {lanes.browser.mechanism}</p>
+ <p>Blender lane: {lanes.blender.ready ? 'Ready' : <span className="text-port-warning">{lanes.blender.reason}</span>}</p>
+ </div>
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="min-w-0 flex-1 basis-72">
+ <label htmlFor="cap-blender-path" className="mb-1 block text-sm">Blender executable (operator-owned)</label>
+ <input id="cap-blender-path" value={blenderPath} onChange={event => setBlenderPath(event.target.value)} placeholder="/Applications/Blender.app/Contents/MacOS/Blender" className="w-full min-w-0 rounded border border-port-border bg-port-bg px-3 py-2 text-sm" />
+ </div>
+ <button type="button" className={buttonClass} disabled={!dirty || saving || probing} onClick={save}>{saving ? 'Saving…' : 'Save tool'}</button>
+ <button type="button" className={buttonClass} disabled={dirty || saving || probing || !mechanism.supported} onClick={probe}>{probing ? 'Checking containment…' : 'Run containment check'}</button>
+ </div>
+ {execution.tools.blender.problem && savedPath && <p className="text-sm text-port-warning">{execution.tools.blender.problem}</p>}
+ {result && <div role="status" className="space-y-1 text-sm">
+ <p>{result.refused || `${result.passed ? 'Containment proven' : 'Containment check failed'}: ${formatCount(result.checks.filter(check => check.passed).length)} of ${formatCount(result.checks.length)} checks`}</p>
+ <ul className="space-y-1">
+ {result.checks.map(check => <li key={check.id} className={check.passed ? 'text-gray-400' : 'text-port-error'}>{check.passed ? 'Pass' : 'Fail'} · {check.detail}</li>)}
+ {result.tools?.blender && <li className={result.tools.blender.passed ? 'text-gray-400' : 'text-port-warning'}>{result.tools.blender.detail}</li>}
+ </ul>
+ </div>}
+ </section>;
+}
diff --git a/client/src/components/codeAnimation/ProductionProjects.jsx b/client/src/components/codeAnimation/ProductionProjects.jsx
index fd8e675a9f..7ed026c705 100644
--- a/client/src/components/codeAnimation/ProductionProjects.jsx
+++ b/client/src/components/codeAnimation/ProductionProjects.jsx
@@ -15,6 +15,7 @@ import { formatCount, formatBytes, timeAgo } from '../../utils/formatters';
import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';
import ProductionProjectForm from './ProductionProjectForm';
import ProductionPreflight from './ProductionPreflight';
+import ProductionContainment from './ProductionContainment';
const EVENTS = ['code-animation:changed'];
const buttonClass = 'rounded border border-port-border px-3 py-2 text-sm hover:border-port-accent disabled:opacity-50';
@@ -94,6 +95,7 @@ export default function ProductionProjects() {
</div>
<InfiniteScrollFooter hasMore={projects.hasMore} loading={projects.loading} error={projects.error} onLoadMore={projects.loadMore} autoLoad={false} label="Load older projects" />
</section>
+ <ProductionContainment />
{projectId && resource.loading && <p>Loading production project…</p>}
{resource.error && <div role="alert" className="rounded border border-port-error p-3">
diff --git a/client/src/components/codeAnimation/ProductionProjects.test.jsx b/client/src/components/codeAnimation/ProductionProjects.test.jsx
index cc8e9c6e58..04ae3aa7d5 100644
--- a/client/src/components/codeAnimation/ProductionProjects.test.jsx
+++ b/client/src/components/codeAnimation/ProductionProjects.test.jsx
@@ -7,6 +7,7 @@ vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [
vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));
vi.mock('../../services/apiCodeAnimation', () => ({
preflightCodeAnimationProject: vi.fn(),
+ getCodeAnimationExecution: vi.fn(), updateCodeAnimationExecutionTools: vi.fn(), probeCodeAnimationExecution: vi.fn(),
listCodeAnimationProjects: vi.fn(), createCodeAnimationProject: vi.fn(), getCodeAnimationProject: vi.fn(),
updateCodeAnimationProject: vi.fn(), importCodeAnimationPackage: vi.fn(), acceptCodeAnimationSource: vi.fn(),
getCodeAnimationProjectBrief: vi.fn(), getCodeAnimationRevisionPackage: vi.fn(), listCodeAnimationProjectHistory: vi.fn(),
@@ -28,6 +29,12 @@ const project = {
acceptedRevisionId: null, candidateRevisionId: '00000000-0000-4000-8000-000000000002',
};
const page = (items = []) => ({ items, nextCursor: null });
+const execution = (overrides = {}) => ({
+ platform: 'darwin', mechanism: { id: 'macos-seatbelt', supported: true, reason: null }, probe: null,
+ tools: { blender: { executable: null, problem: 'Not configured.' } },
+ lanes: { browser: { mechanism: 'chromium-cdp-sandbox' }, blender: { ready: false, reason: 'Blender: Not configured.' } },
+ ...overrides,
+});
const renderPage = (entry = '/code-animation/production/' + project.id) => render(
<MemoryRouter initialEntries={[entry]}><Routes>
<Route path="/code-animation/production" element={<ProductionProjects />} />
@@ -39,6 +46,7 @@ beforeEach(() => {
api.listCodeAnimationProjects.mockResolvedValue(page([project]));
api.getCodeAnimationProject.mockResolvedValue(project);
api.listCodeAnimationProjectHistory.mockResolvedValue(page());
+ api.getCodeAnimationExecution.mockResolvedValue(execution());
});
describe('Production project rendered interactions', () => {
@@ -105,4 +113,25 @@ describe('Production project rendered interactions', () => {
expect(await screen.findByRole('button', { name: 'Save project settings' })).toBeInTheDocument();
expect(api.getCodeAnimationProject).toHaveBeenCalledWith(project.id, expect.objectContaining({ silent: true }));
});
+
+ it('reports refused containment and checks only a saved operator tool path', async () => {
+ const user = userEvent.setup();
+ renderPage('/code-animation/production');
+ expect(await screen.findByText('Blender: Not configured.')).toBeInTheDocument();
+ const path = '/Applications/Example.app/Contents/MacOS/Blender';
+ await user.type(screen.getByLabelText('Blender executable (operator-owned)'), path);
+ expect(screen.getByRole('button', { name: 'Run containment check' })).toBeDisabled();
+ const saved = execution({ tools: { blender: { executable: path, problem: null } }, lanes: { browser: { mechanism: 'chromium-cdp-sandbox' }, blender: { ready: false, reason: 'Run the containment check.' } } });
+ api.updateCodeAnimationExecutionTools.mockResolvedValue(saved);
+ await user.click(screen.getByRole('button', { name: 'Save tool' }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Run containment check' })).toBeEnabled());
+ expect(api.updateCodeAnimationExecutionTools).toHaveBeenCalledWith({ blender: { executable: path } }, { silent: true });
+ api.probeCodeAnimationExecution.mockResolvedValue({ ...saved,
+ probe: { passed: true, refused: null, checks: [{ id: 'network', passed: true, detail: 'Outbound network was refused by the sandbox.' }],
+ tools: { blender: { passed: false, detail: 'Blender did not start under containment (failed: exit).' } } },
+ lanes: { ...saved.lanes, blender: { ready: false, reason: 'Blender did not start under containment.' } } });
+ await user.click(screen.getByRole('button', { name: 'Run containment check' }));
+ expect(await screen.findByText(/Containment proven: 1 of 1 checks/)).toBeInTheDocument();
+ expect(screen.getByText('Blender did not start under containment.')).toBeInTheDocument();
+ });
});
diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.js
index 537b2c5908..8b821c3cdf 100644
--- a/client/src/services/apiCodeAnimation.js
+++ b/client/src/services/apiCodeAnimation.js
@@ -62,3 +62,9 @@ export const cancelCodeAnimationExport = (exportJobId, options) => request(`/htm
});
export const preflightCodeAnimationProject = (id, options) => request(`/code-animation/projects/${encodeURIComponent(id)}/preflight`, options);
+
+// Contained production execution (#9388): capability report, operator tool
+// paths, and the on-demand adversarial containment check.
+export const getCodeAnimationExecution = (options) => request('/code-animation/execution', options);
+export const updateCodeAnimationExecutionTools = (tools, options) => request('/code-animation/execution/tools', { method: 'PUT', body: JSON.stringify(tools), ...options });
+export const probeCodeAnimationExecution = (options) => request('/code-animation/execution/probe', { method: 'POST', ...options });
diff --git a/docs/API.md b/docs/API.md
index 33745cae0b..e9ea2072fd 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -769,6 +769,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/sprites` | Sprite catalog / export |
| `/api/threejs-models` | Procedural Three.js models |
| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building, persistent jobs gallery, generated HTML retrieval, frame-exact MP4 export (`POST /:id/export` → HTML-composition media job), portable source download (`GET /:id/package`), and data-only package validation (`POST /packages/validate`; [contract](CODE_ANIMATION_PACKAGES.md)) |
+| `/api/code-animation/execution` | Code Animation contained production execution: platform sandbox and lane readiness (`GET /`), operator-owned tool paths (`PUT /tools`, host control) and the on-demand adversarial containment check (`POST /probe`, host control) ([contract](CODE_ANIMATION_PACKAGES.md#contained-production-execution)) |
| `/api/image-to-3d` | Image-to-3D conversion |
| `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models |
| `/api/privacy` | PII vault / trusted-org / broker opt-out |
diff --git a/docs/CODE_ANIMATION_PACKAGES.md b/docs/CODE_ANIMATION_PACKAGES.md
index 9f1bc6e4f3..437428dc86 100644
--- a/docs/CODE_ANIMATION_PACKAGES.md
+++ b/docs/CODE_ANIMATION_PACKAGES.md
@@ -92,3 +92,91 @@ model access at the vendor, or render readiness. Production authoring dispatch,
render/inspection/research adapters, fallback decisions and actual-run provenance
remain pending under #9387 and the execution slices of #9383. Package export and
import remain available for external authoring.
+
+## Contained production execution
+
+A job directory is not a boundary. Production package code (a Blender scene
+script, a generated renderer) runs only through the contained worker in
+`server/services/codeAnimation/containedWorker.js`, under an enforced OS
+mechanism. Where no mechanism is available the worker refuses with 503
+`CODE_ANIMATION_CONTAINMENT_UNAVAILABLE`; there is no uncontained fallback.
+Authoring stays outside the worker: provider transport, credentials and any
+research access belong to the authoring route, never to execution.
+
+| Platform | Mechanism | Status |
+|---|---|---|
+| macOS | Seatbelt kernel sandbox (`/usr/bin/sandbox-exec`, deny-by-default profile) | Supported; proven on demand by the containment check |
+| Linux | None implemented (bubblewrap/user namespaces are the candidate) | Refused |
+| Windows | None implemented | Refused |
+
+Each run gets a fresh UUID workspace under `data/code-animation-workspaces/`
+(excluded from backups, removed when the run ends, swept on the next run after
+a crash) with `input/` (staged files, read-only), `output/`, `tmp/` and a
+private `home/`. The Seatbelt profile allows:
+
+- exec of exactly the operator-configured executable; **fork is denied**, so a
+ worker is one process and cannot start a shell, package manager or helper;
+- reads of system libraries, Homebrew package code (`Cellar/`, `opt/`, not
+ `var/` or `etc/`), the tool's install roots and the staged input;
+- writes to `output/`, `tmp/` and `home/` only;
+- metadata (not listing or content) of those roots' ancestor directories.
+
+Everything else is denied, including all network (loopback and Unix sockets
+too, so PortOS's API and local services are unreachable), Mach/XPC services
+(keychain, pasteboard, launchd) and IPC. The environment is built from scratch
+(paths only), so no `PORTOS_API_TOKEN`, provider key, cloud credential or proxy
+setting is inherited. The process runs in its own process group: cancellation
+and every limit `SIGKILL` the group, and the result reports whether the group
+was verified empty. Limits: wall time, total bytes and file count of the
+writable directories (watchdog), single-file size (`RLIMIT_FSIZE`), resident
+memory (watchdog), open descriptors, no core dumps. Output that is not a
+regular, singly-linked file (a symlink or hard link the worker made) fails the
+run and is never handed to the caller.
+
+Installed tools are operator-owned machine-local settings
+(`codeAnimationExecution` in `data/settings.json`). Packages cannot name an
+executable, install command or mount. A tool must be an existing absolute
+executable outside PortOS data; workers can read its app bundle (macOS
+`.app`), its prefix's `bin/`, `lib/`, `libexec/`, `share/` and `Frameworks/`
+when it lives in a `bin/` directory, or otherwise its own directory — and none
+of those may contain PortOS data or the home directory.
+
+- `GET /api/code-animation/execution` reports the platform mechanism, the
+ configured tools, the last containment check and each lane's readiness.
+ Readiness fails closed: the Blender lane is ready only after a containment
+ check has passed in this server process with the currently configured
+ executable.
+- `PUT /api/code-animation/execution/tools` sets `{ blender: { executable } }`
+ (`null` clears it). Host control: it chooses what a worker runs.
+- `POST /api/code-animation/execution/probe` runs the containment check on
+ demand (host control; never at boot; no provider call). PortOS's own Node
+ interpreter runs synthetic hostile scripts through the same staging, profile,
+ environment and limits, and each check must observe the sandbox refusing:
+ reading a file outside the workspace, listing PortOS data or the home
+ directory, writing outside the workspace or into staged input, starting a
+ process, writing a file over the size limit, inheriting environment
+ variables, connecting to a loopback listener (which must see no connection)
+ or to the network. Positive control: the worker must still write its report.
+ Separate runs must be terminated by the wall-time, disk, memory and
+ cancellation limits with an empty process group. A configured Blender is then
+ started contained with `--background --factory-startup --version`.
+
+Known limits: Blender is granted CPU rendering only — no GPU/Metal device or
+window-server access — and has not been verified under this profile on a
+machine with Blender installed; a Blender that cannot start contained keeps its
+lane refused. Seatbelt (`sandbox-exec`) is deprecated by Apple but remains the
+mechanism Chromium and the private security assessment harness use. A host
+that already runs PortOS inside another sandbox may be unable to apply a nested
+profile; the check then fails and execution stays refused. Memory and total
+disk are watchdog-enforced (1 s interval in production), so a worker can
+briefly exceed them before it is killed.
+
+The browser lane does not use this worker. It reuses the HTML-composition
+renderer sandbox (`server/services/htmlComposition/browser.js`): an in-memory
+asset snapshot (symlinks refused), every request intercepted with only the
+snapshot origin fulfilled, network/WebSocket/WebRTC/workers/frames refused, and
+a disposable credential-free browser context closed on cancel or failure. Its
+limits: it runs inside the shared managed Chromium (Chromium's renderer sandbox
+contains page code, not a PortOS-owned process group), with per-command
+timeouts and render cancellation but no per-render memory cap. Its boundary
+tests are `server/services/htmlComposition/index.test.js`.
diff --git a/docs/README.md b/docs/README.md
index 7504abeb1d..c106bf7d46 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -10,7 +10,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
|-----|--------|
| [HTML_COMPOSITIONS.md](./HTML_COMPOSITIONS.md) | Seekable HTML scenes rendered offline to MP4 through hidden managed-browser targets |
| [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 and non-executing validation |
+| [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 |
| [features/catalog-ingest.md](./features/catalog-ingest.md) | Catalog extraction graph, context budgets, coverage, and review draft contract |
| [API.md](./API.md) | REST endpoints, complete route-domain index, Socket.IO events |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index bccc8d41e9..7c3c76f8fc 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -56,7 +56,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).
- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.
- `code_animation_jobs` — Code Animation generation history (`db-primary` record with a managed HTML output asset): job status/title and the generation brief/provider details are stored in PostgreSQL so the gallery can list and reopen jobs after navigation or restart. The generated HTML is kept as a managed file at `data/code-animations/<id>.html`; PostgreSQL stores only its job record, not the output bytes. Jobs are machine-local and never federated. The database dump covers records and the normal filesystem backup includes the HTML assets.
-- `code_animation_projects`, `code_animation_project_revisions`, `code_animation_project_runs` — opt-in Code Animation Production settings, accepted/candidate source pointers, immutable source/package hashes, portable manifest metadata and bounded import history. PostgreSQL owns metadata; source/asset bytes are write-once files under `data/code-animations/projects/<project-id>/revisions/<revision-id>/`. Settings, reference IDs, execution snapshots, managed paths and run IDs are machine-local and never federate. Budgets independently record iterations, elapsed time, tokens, render time and total retained disk bytes; imports consume disk only and never execute or install dependencies. Every attempted import has its own UUID-owned destination; failed/interrupted staging stays attributable to its run and never replaces accepted source. Boot DDL and migration 420 install empty tables without a seed. The PostgreSQL dump covers all three tables, and normal filesystem backup includes the entire project directory (no new excludes). Brief handoff omits local settings/IDs/paths; revision packages export only the validated portable contract. Source acceptance is explicit and does not assert visual, motion, sound or render evidence.
+- `code_animation_projects`, `code_animation_project_revisions`, `code_animation_project_runs` — opt-in Code Animation Production settings, accepted/candidate source pointers, immutable source/package hashes, portable manifest metadata and bounded import history. PostgreSQL owns metadata; source/asset bytes are write-once files under `data/code-animations/projects/<project-id>/revisions/<revision-id>/`. Settings, reference IDs, execution snapshots, managed paths and run IDs are machine-local and never federate. Budgets independently record iterations, elapsed time, tokens, render time and total retained disk bytes; imports consume disk only and never execute or install dependencies. Every attempted import has its own UUID-owned destination; failed/interrupted staging stays attributable to its run and never replaces accepted source. Boot DDL and migration 420 install empty tables without a seed. The PostgreSQL dump covers all three tables, and normal filesystem backup includes the entire project directory (no new excludes). Brief handoff omits local settings/IDs/paths; revision packages export only the validated portable contract. Source acceptance is explicit and does not assert visual, motion, sound or render evidence. Contained production workers stage each run in its own `data/code-animation-workspaces/<uuid>/` (excluded from backups, removed when the run ends); their operator-chosen tool paths are the machine-local `codeAnimationExecution` slice of `data/settings.json`.
- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — AI **services** (instances a harness is pointed at) and the graph the **presets** derived from them are projected through (#6367 → #7561; user guide [AI_PROVIDERS.md](./AI_PROVIDERS.md), design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.
- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). Broker-case `evidence` follows the same rule (#8333): the matched name/location and the identity-bearing search/listing URLs a scan records are sealed under `evidence.sealed_identity` with the same key, erased on `confirmed_removed`, on the per-case erase action, and when the source `legal_name`/`address` vault record is deleted. **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.
diff --git a/server/index.js b/server/index.js
index 6ec2d2b214..822fb139a1 100644
--- a/server/index.js
+++ b/server/index.js
@@ -148,6 +148,7 @@ import moodBoardRoutes from './routes/moodBoard.js';
import deckRoutes from './routes/decks.js';
import threejsModelsRoutes from './routes/threejsModels.js';
import codeAnimationRoutes from './routes/codeAnimation.js';
+import codeAnimationExecutionRoutes from './routes/codeAnimationExecution.js';
import imageTo3dRoutes from './routes/imageTo3d.js';
import riggingRoutes from './routes/rigging.js';
import privacyRoutes from './routes/privacy.js';
@@ -437,6 +438,7 @@ app.use('/api/sprites', spriteRoutes);
app.use('/api/mood-boards', moodBoardRoutes);
app.use('/api/decks', deckRoutes);
app.use('/api/threejs-models', threejsModelsRoutes);
+app.use('/api/code-animation/execution', codeAnimationExecutionRoutes);
app.use('/api/code-animation', codeAnimationRoutes);
app.use('/api/image-to-3d', imageTo3dRoutes);
app.use('/api/rigging', riggingRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 07dbfcdf50..7adb056319 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,6 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. |
| `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema` (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects. |
+| `codeAnimationContainment.js` | Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt, otherwise refusal), deny-by-default Seatbelt profile, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is `services/codeAnimation/containedWorker.js`. |
| `codeAnimationPackage.js` | Versioned data-only Code Animation package schema, byte/path/reference integrity limits, SHA-256 revision binding, `createCodeAnimationPackage` and `summarizeCodeAnimationPackage`; validation never executes or stages code. |
| `socketEventContracts.js` | Payload contracts for modeled Socket.IO events, reusing live Zod validation for inbound events and documenting public outbound snapshots. |
| `socketEventInventory.js` | Cached source-derived Socket.IO event inventory: event names and directions only, with no checked-in manifest or positional source metadata. |
diff --git a/server/lib/codeAnimationContainment.js b/server/lib/codeAnimationContainment.js
new file mode 100644
index 0000000000..2a99255a58
--- /dev/null
+++ b/server/lib/codeAnimationContainment.js
@@ -0,0 +1,140 @@
+/**
+ * Containment contract for Code Animation production workers (#9388).
+ *
+ * A job directory is not a boundary. Generated or imported package code runs
+ * only under an enforced OS mechanism; when none is available execution is
+ * refused, never downgraded to an uncontained spawn. The supported mechanism
+ * on this release is the macOS Seatbelt kernel sandbox (`sandbox-exec`), the
+ * same one the private security assessment harness uses. Linux and Windows
+ * report no mechanism and refuse.
+ *
+ * Pure: no filesystem, process or settings access.
+ */
+import { basename, dirname, isAbsolute, join, normalize, parse } from 'node:path';
+import { z } from 'zod';
+
+export const CODE_ANIMATION_SEATBELT = '/usr/bin/sandbox-exec';
+
+/** Upper bounds a caller may request; defaults suit one preview render. */
+export const codeAnimationWorkerLimitsSchema = z.object({
+ wallSeconds: z.number().int().min(1).max(86400).default(300),
+ // Every byte the worker can write: output, scratch and its private home.
+ diskBytes: z.number().int().min(1024).max(1_000_000_000_000).default(512 * 1024 * 1024),
+ maxFiles: z.number().int().min(1).max(200_000).default(20_000),
+ memoryBytes: z.number().int().min(16 * 1024 * 1024).max(1024 * 1024 * 1024 * 1024).default(8 * 1024 * 1024 * 1024),
+ openFiles: z.number().int().min(64).max(65536).default(1024),
+}).strict();
+
+/**
+ * Operator-owned installed tools, kept in the machine-local settings slice
+ * `codeAnimationExecution`. Packages never name an executable, install
+ * command or mount; only this operator-gated configuration does.
+ */
+export const codeAnimationExecutionToolsSchema = z.object({
+ blender: z.object({
+ executable: z.string().trim().max(4096).nullable(),
+ }).strict(),
+}).strict();
+
+/**
+ * The enforced mechanism for `platform`, or a refusal reason. `seatbeltAvailable`
+ * is whether `/usr/bin/sandbox-exec` is executable on this host.
+ */
+export function codeAnimationContainmentMechanism(platform, seatbeltAvailable) {
+ if (platform === 'darwin') {
+ return seatbeltAvailable
+ ? { id: 'macos-seatbelt', supported: true, reason: null }
+ : { id: null, supported: false, reason: 'macOS Seatbelt (/usr/bin/sandbox-exec) is unavailable on this host.' };
+ }
+ return {
+ id: null, supported: false,
+ reason: `No enforced worker containment is implemented for ${platform}. Production code execution is refused; package import/export and the browser preview sandbox remain available.`,
+ };
+}
+
+// SBPL string literals: refuse anything that could close the literal or the form.
+const sbplPath = (path) => {
+ if (typeof path !== 'string' || !isAbsolute(path) || normalize(path) !== path || /["\\()\0\r\n]/.test(path)) {
+ throw new Error('Containment paths must be normalized absolute paths without quote, backslash or parenthesis characters');
+ }
+ return JSON.stringify(path);
+};
+
+const ancestors = (path) => {
+ const out = [];
+ for (let current = dirname(path); current !== parse(current).root; current = dirname(current)) out.push(current);
+ return out;
+};
+
+/**
+ * The installed tool's read-only roots. A macOS app bundle is read as a whole
+ * (frameworks, Python and data files live inside it). A binary in a prefix's
+ * `bin/` reads that prefix's code directories, never the whole prefix (where
+ * `var/` or `etc/` may hold other programs' data); any other binary reads
+ * only its own directory.
+ */
+export function codeAnimationToolRoots(executable) {
+ const marker = executable.lastIndexOf('.app/Contents/MacOS/');
+ if (marker > 0) return [executable.slice(0, marker + 4)];
+ const dir = dirname(executable);
+ if (basename(dir) !== 'bin' || dirname(dir) === parse(dir).root) return [dir];
+ return ['bin', 'lib', 'libexec', 'share', 'Frameworks'].map((name) => join(dirname(dir), name));
+}
+
+// System libraries plus Homebrew's installed-package code (a Homebrew binary
+// links its sibling formulae through opt/). Homebrew's var/ and etc/, which
+// hold other programs' data, are not included.
+const SYSTEM_READ_ROOTS = [
+ '/System', '/usr/lib', '/usr/share', '/private/var/db/dyld', '/private/var/db/timezone',
+ '/opt/homebrew/Cellar', '/opt/homebrew/opt', '/opt/homebrew/lib', '/usr/local/Cellar', '/usr/local/opt',
+];
+
+/**
+ * Deny-by-default Seatbelt profile for one worker. All paths must already be
+ * realpaths. Grants:
+ * - exec of exactly the operator-configured executable; fork is denied, so
+ * the worker is one process that cannot start a shell, installer or helper;
+ * - read of system and Homebrew package libraries, the tool's install roots
+ * and the staged input;
+ * - read/write of the workspace's output, scratch and private home only;
+ * - metadata (stat, not listing or content) of the ancestors of those roots,
+ * which path resolution needs.
+ * Everything else is denied: network (including loopback and Unix sockets, so
+ * PortOS's own API is unreachable), Mach/XPC services (keychain, pasteboard,
+ * launchd), IPC, other files, device files beyond the null/random devices.
+ */
+export function codeAnimationSeatbeltProfile({ executable, toolRoots, workspace }) {
+ const staged = join(workspace, 'input');
+ const writable = ['output', 'tmp', 'home'].map((name) => join(workspace, name));
+ const readRoots = [...SYSTEM_READ_ROOTS, ...toolRoots, staged, ...writable];
+ const metadata = [...new Set([...readRoots, executable].flatMap(ancestors))];
+ return `(version 1)
+(deny default)
+(allow process-exec (literal ${sbplPath(executable)}))
+(allow sysctl-read)
+(allow file-read-metadata (literal "/") ${metadata.map((path) => `(literal ${sbplPath(path)})`).join(' ')})
+(allow file-read* (literal "/") (literal "/dev/null") (literal "/dev/zero") (literal "/dev/random") (literal "/dev/urandom")
+ ${readRoots.map((path) => `(subpath ${sbplPath(path)})`).join(' ')})
+(allow file-write* (literal "/dev/null") ${writable.map((path) => `(subpath ${sbplPath(path)})`).join(' ')})`;
+}
+
+/**
+ * The worker's complete environment. Built from nothing — never a copy of the
+ * server's — so no PortOS token, provider key, cloud credential or proxy
+ * setting can be inherited.
+ */
+export function codeAnimationWorkerEnv(workspace) {
+ const home = join(workspace, 'home');
+ const tmp = join(workspace, 'tmp');
+ return {
+ PATH: '/usr/bin:/bin', HOME: home, TMPDIR: tmp, TMP: tmp, TEMP: tmp,
+ LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8',
+ XDG_CONFIG_HOME: join(home, 'config'), XDG_CACHE_HOME: join(home, 'cache'), XDG_DATA_HOME: join(home, 'data'),
+ // Blender reads user add-ons/startup files from here; keep them private and empty.
+ BLENDER_USER_RESOURCES: join(home, 'blender'),
+ // Workers have no network; an OpenSSL build's config outside the sandbox is not needed.
+ OPENSSL_CONF: '/dev/null',
+ PORTOS_WORKER_INPUT: join(workspace, 'input'),
+ PORTOS_WORKER_OUTPUT: join(workspace, 'output'),
+ };
+}
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 233757e4f7..e1c4bed041 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -277,6 +277,11 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// Runs the configured local or provider reviewer on a caller-supplied diff.
'POST /api/code-review/local',
+ // Code Animation contained execution (#9388): choosing the installed tool a
+ // worker runs, and the containment check that spawns sandboxed processes.
+ 'PUT /api/code-animation/execution/tools',
+ 'POST /api/code-animation/execution/probe',
+
// Providers: which binary runs, with which args, against which endpoint and
// credentials; installing or launching runtimes; signing a CLI in or out.
// `PUT /api/providers/:id` also matches `/active` and `/bootstraps`.
@@ -389,12 +394,13 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
/**
* `PUT /api/settings` slices that set what runs or the guardrails around it:
- * harness enablement and wrapper CLIs, the code-review chain, the untrusted
- * content screen in front of agent work, scheduled self-update, and scheduled
- * series autopilots. The store is polymorphic, so its other slices stay open.
+ * 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, and scheduled series autopilots. The store is polymorphic, so its other slices stay open.
*/
export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze([
'autoUpdate',
+ 'codeAnimationExecution',
'codeReview',
'credentialBootstraps',
'harnesses',
diff --git a/server/lib/index.js b/server/lib/index.js
index 940b775f8e..fdbc5b8841 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -20,6 +20,7 @@ export * from './appPromptPlaceholders.js';
export * from './appDeployFlags.js';
export * from './apiContractSchemas.js';
export * from './codeAnimationPackage.js';
+export * from './codeAnimationContainment.js';
export * from './autonomousJobTask.js';
export * from './asyncApiSpec.js';
export * from './avatarVariants.js';
diff --git a/server/routes/codeAnimationExecution.js b/server/routes/codeAnimationExecution.js
new file mode 100644
index 0000000000..b285b5329f
--- /dev/null
+++ b/server/routes/codeAnimationExecution.js
@@ -0,0 +1,33 @@
+/**
+ * Code Animation production execution capability (#9388).
+ *
+ * GET /api/code-animation/execution platform mechanism, tools, lane readiness, last check
+ * PUT /api/code-animation/execution/tools operator-owned installed-tool paths (host control)
+ * POST /api/code-animation/execution/probe run the adversarial containment check (host control)
+ *
+ * Packages never reach these routes' choices: they cannot name an executable,
+ * install command or mount. Nothing here calls a provider.
+ */
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { codeAnimationExecutionToolsSchema } from '../lib/codeAnimationContainment.js';
+import {
+ getCodeAnimationExecution, probeCodeAnimationExecution, setCodeAnimationExecutionTools,
+} from '../services/codeAnimation/execution.js';
+
+const router = Router();
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await getCodeAnimationExecution());
+}));
+
+router.put('/tools', asyncHandler(async (req, res) => {
+ res.json(await setCodeAnimationExecutionTools(validateRequest(codeAnimationExecutionToolsSchema, req.body ?? {})));
+}));
+
+router.post('/probe', asyncHandler(async (_req, res) => {
+ res.json(await probeCodeAnimationExecution());
+}));
+
+export default router;
diff --git a/server/routes/codeAnimationExecution.test.js b/server/routes/codeAnimationExecution.test.js
new file mode 100644
index 0000000000..c38504e636
--- /dev/null
+++ b/server/routes/codeAnimationExecution.test.js
@@ -0,0 +1,106 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { existsSync } from 'node:fs';
+import { chmod, mkdir, mkdtemp, readdir, realpath, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { CODE_ANIMATION_SEATBELT } from '../lib/codeAnimationContainment.js';
+
+const { settings } = vi.hoisted(() => ({ settings: { current: {} } }));
+vi.mock('../lib/paths.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-code-animation-execution-') }));
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(async () => settings.current),
+ updateSettings: vi.fn(async (patch) => { settings.current = { ...settings.current, ...patch }; return settings.current; }),
+}));
+// The browser lane's availability is reported, not exercised, by the probe.
+vi.mock('../services/browserService.js', () => ({ cdpRequest: vi.fn(async () => { throw new Error('offline'); }) }));
+
+import { PATHS } from '../lib/paths.js';
+import router from './codeAnimationExecution.js';
+
+const app = express();
+app.use(express.json());
+app.use('/api/code-animation/execution', router);
+app.use(errorMiddleware);
+const seatbelt = process.platform === 'darwin' && existsSync(CODE_ANIMATION_SEATBELT);
+const scratch = [];
+afterAll(async () => {
+ cleanupTempDataRoots();
+ await Promise.all(scratch.map((dir) => rm(dir, { recursive: true, force: true })));
+});
+beforeEach(() => { settings.current = {}; });
+
+const executableAt = async (dir, name = 'blender') => {
+ await mkdir(dir, { recursive: true });
+ const path = join(dir, name);
+ await writeFile(path, '#!/bin/sh\necho "Blender 4.2.0"\n');
+ await chmod(path, 0o755);
+ return path;
+};
+
+describe('Code Animation execution capability', () => {
+ it('stays fail-closed before a containment check has passed on this server process', async () => {
+ const { status, body } = await request(app).get('/api/code-animation/execution');
+ expect(status).toBe(200);
+ expect(body.probe).toBeNull();
+ expect(body.lanes.blender.ready).toBe(false);
+ expect(body.lanes.browser.mechanism).toBe('chromium-cdp-sandbox');
+ expect(body.mechanism.supported).toBe(seatbelt);
+ if (!seatbelt) expect(body.mechanism.reason).toMatch(/refused|unavailable/);
+ });
+
+ it('accepts only an operator tool that cannot expose PortOS data, and stores its realpath', async () => {
+ const put = (executable) => request(app).put('/api/code-animation/execution/tools').send({ blender: { executable } });
+ expect((await put('blender')).status).toBe(400);
+ expect((await put(join(tmpdir(), 'portos-no-such-blender'))).body.code).toBe('CODE_ANIMATION_TOOL_INVALID');
+ const planted = await executableAt(join(PATHS.data, 'code-animations', 'projects', 'evil'));
+ expect((await put(planted)).body.code).toBe('CODE_ANIMATION_TOOL_INVALID');
+ expect(settings.current.codeAnimationExecution).toBeUndefined();
+
+ const dir = await mkdtemp(join(tmpdir(), 'portos-tool-'));
+ scratch.push(dir);
+ const tool = await executableAt(join(dir, 'Blender.app', 'Contents', 'MacOS'));
+ const { status, body } = await put(tool);
+ expect(status).toBe(200);
+ expect(settings.current.codeAnimationExecution).toEqual({ blender: { executable: await realpath(tool) } });
+ expect(body.tools.blender).toMatchObject({ executable: await realpath(tool), problem: null });
+ expect(body.lanes.blender.ready).toBe(false);
+
+ await put(null);
+ expect(settings.current.codeAnimationExecution).toEqual({ blender: { executable: null } });
+ });
+
+ it.skipIf(seatbelt)('refuses the containment check where no enforced mechanism exists', async () => {
+ const { body } = await request(app).post('/api/code-animation/execution/probe');
+ expect(body.probe).toMatchObject({ passed: false, mechanism: null, checks: [] });
+ expect(body.probe.refused).toMatch(/refused|unavailable/);
+ expect(body.lanes.blender.ready).toBe(false);
+ });
+
+ // Actual mechanism evidence: synthetic hostile packages run through the real
+ // Seatbelt worker, and each boundary/limit is observed failing for them.
+ it.skipIf(!seatbelt)('proves the macOS Seatbelt boundary and limits, and keeps a tool that cannot start contained refused', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'portos-tool-'));
+ scratch.push(dir);
+ // A script tool needs /bin/sh, which the worker profile does not grant.
+ settings.current = { codeAnimationExecution: { blender: { executable: await executableAt(join(dir, 'Blender.app', 'Contents', 'MacOS')) } } };
+
+ const { status, body } = await request(app).post('/api/code-animation/execution/probe');
+ expect(status).toBe(200);
+ expect(body.probe.mechanism).toBe('macos-seatbelt');
+ expect(Object.fromEntries(body.probe.checks.map((check) => [check.id, check.passed]))).toEqual({
+ 'worker-runs': true, 'read-outside': true, 'list-data': true, 'list-home': true, 'write-outside': true,
+ 'write-input': true, 'spawn-process': true, 'file-size': true, credentials: true, 'host-api': true, network: true,
+ 'limit-time': true, 'limit-disk': true, 'limit-memory': true, 'limit-cancel': true,
+ });
+ expect(body.probe.passed).toBe(true);
+ expect(body.probe.tools.blender).toMatchObject({ passed: false, version: null });
+ expect(body.lanes.blender).toEqual({ ready: false, reason: 'Blender did not start under containment.' });
+ // Every owned workspace was removed, including the terminated ones.
+ expect(await readdir(join(PATHS.data, 'code-animation-workspaces'))).toEqual([]);
+ }, 60_000);
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index e009b308b3..df4eb71ca1 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -171,6 +171,7 @@ export const DEFAULT_EXCLUDES = [
{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },
{ path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true },
{ path: '/composition-proofs/', reason: 'HTML-composition contact-sheet proofs — review stills, re-rendered from the composition source', overridable: true },
+ { path: '/code-animation-workspaces/', reason: 'In-flight sandboxed Code Animation worker workspaces — removed when each run ends', overridable: false },
{ path: '/code-animation-exports/', reason: 'Code Animation frame-exact export staging — the stored HTML plus render shim, staged once per export', overridable: true },
{ path: '/music-video-compositions/', reason: 'In-flight music-video typography overlay scratch — removed when its render ends and swept at boot', overridable: false },
{ path: '/music-video-song-renders/', reason: 'In-flight music-video composition renders (a staged copy of the document plus scene media) — removed when the render ends and swept at boot', overridable: false },
diff --git a/server/services/codeAnimation/containedWorker.js b/server/services/codeAnimation/containedWorker.js
new file mode 100644
index 0000000000..feafec8489
--- /dev/null
+++ b/server/services/codeAnimation/containedWorker.js
@@ -0,0 +1,211 @@
+/**
+ * Contained Code Animation worker (#9388): stage files into a fresh, owned
+ * workspace, run one operator-configured executable under the enforced OS
+ * sandbox with a from-scratch environment, enforce wall-time / disk / file /
+ * memory limits, own the process group through cancellation, and validate
+ * what the worker left behind. No uncontained fallback exists.
+ */
+import { constants } from 'node:fs';
+import { access, lstat, mkdir, open, readdir, realpath, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { promisify } from 'node:util';
+import { ServerError } from '../../lib/errorHandler.js';
+import { execFile, spawn } from '../../lib/childProcess.js';
+import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
+import {
+ CODE_ANIMATION_SEATBELT, codeAnimationContainmentMechanism, codeAnimationSeatbeltProfile,
+ codeAnimationToolRoots, codeAnimationWorkerEnv, codeAnimationWorkerLimitsSchema,
+} from '../../lib/codeAnimationContainment.js';
+
+const execFileAsync = promisify(execFile);
+const WORKSPACE_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const SEGMENT = /^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/i;
+const TAIL_BYTES = 8192;
+const active = new Set();
+const swept = new Set();
+
+const canExecute = (path) => access(path, constants.X_OK).then(() => true, () => false);
+
+/** The enforced mechanism for this host, probing only that the sandbox binary is executable. */
+export async function currentContainmentMechanism(seatbeltPath = CODE_ANIMATION_SEATBELT) {
+ return codeAnimationContainmentMechanism(process.platform, process.platform === 'darwin' && await canExecute(seatbeltPath));
+}
+
+// A crash leaves its workspace behind; nothing else may own a UUID entry here.
+async function sweepOnce(root) {
+ if (swept.has(root)) return;
+ swept.add(root);
+ for (const name of await readdir(root).catch(() => [])) {
+ if (WORKSPACE_NAME.test(name) && !active.has(join(root, name))) await rm(join(root, name), { recursive: true, force: true });
+ }
+}
+
+async function stage(input, files) {
+ for (const file of files) {
+ const parts = String(file.path).split('/');
+ if (!parts.every((part) => SEGMENT.test(part))) throw new ServerError('Staged worker paths must be portable relative paths', { status: 400, code: 'CODE_ANIMATION_STAGE_PATH' });
+ let parent = input;
+ for (const part of parts.slice(0, -1)) {
+ parent = join(parent, part);
+ await mkdir(parent, { mode: 0o700 }).catch((error) => { if (error.code !== 'EEXIST') throw error; });
+ const info = await lstat(parent);
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new ServerError('Staged worker paths collide', { status: 400, code: 'CODE_ANIMATION_STAGE_PATH' });
+ }
+ const handle = await open(join(input, file.path), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0), 0o444);
+ try {
+ await handle.writeFile(Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content, file.encoding === 'base64' ? 'base64' : 'utf8'));
+ } finally { await handle.close(); }
+ }
+}
+
+// lstat walk: never follows a link the worker made. Non-regular entries and
+// multiply-linked files are reported, not read.
+async function measure(dirs, { maxFiles }) {
+ let bytes = 0;
+ let files = 0;
+ const outputs = [];
+ const invalid = [];
+ async function walk(path, prefix, collect) {
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
+ const full = join(path, entry.name);
+ const rel = `${prefix}${entry.name}`;
+ const info = await lstat(full).catch(() => null);
+ if (!info) continue;
+ files += 1;
+ if (files > maxFiles) return;
+ if (info.isDirectory()) await walk(full, `${rel}/`, collect);
+ else {
+ bytes += info.size;
+ if (!collect) continue;
+ if (!info.isFile() || info.nlink !== 1) invalid.push(rel);
+ else outputs.push({ path: rel, bytes: info.size });
+ }
+ }
+ }
+ for (const [index, dir] of dirs.entries()) await walk(dir, '', index === 0);
+ return { bytes, files, outputs, invalid };
+}
+
+async function residentBytes(pid) {
+ const { stdout } = await execFileAsync('/bin/ps', ['-o', 'rss=', '-p', String(pid)]).catch(() => ({ stdout: '' }));
+ const kib = Number.parseInt(stdout.trim(), 10);
+ return Number.isFinite(kib) ? kib * 1024 : 0;
+}
+
+function groupAlive(pgid) {
+ try { process.kill(-pgid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
+}
+
+const tail = () => {
+ let text = '';
+ return { push: (chunk) => { text = (text + chunk.toString('utf8')).slice(-TAIL_BYTES); }, get: () => text };
+};
+
+/**
+ * Run `tool` (`{ executable, argv(entryPath, workspace) }`, chosen by server
+ * code from operator configuration, never by a package) over `files` in a new
+ * workspace under `workspaceRoot`. `onOutput(outputDir, outputs)` runs only for a
+ * completed, valid result, before the workspace is removed. Resolves with the
+ * run's evidence; refuses (503) when no enforced mechanism is available.
+ */
+export async function runContainedWorker({
+ tool, files = [], entrypoint = null, limits: requested = {}, signal, workspaceRoot,
+ onOutput, tickMs = 1000, seatbeltPath = CODE_ANIMATION_SEATBELT,
+}) {
+ const mechanism = await currentContainmentMechanism(seatbeltPath);
+ if (!mechanism.supported) {
+ throw new ServerError(`Contained execution refused: ${mechanism.reason}`, { status: 503, code: 'CODE_ANIMATION_CONTAINMENT_UNAVAILABLE' });
+ }
+ const limits = codeAnimationWorkerLimitsSchema.parse(requested);
+ if (entrypoint !== null && !files.some((file) => file.path === entrypoint)) {
+ throw new ServerError('The worker entrypoint is not a staged file', { status: 400, code: 'CODE_ANIMATION_STAGE_PATH' });
+ }
+ signal?.throwIfAborted();
+ const executable = await realpath(tool.executable);
+ await mkdir(workspaceRoot, { recursive: true, mode: 0o700 });
+ const root = await realpath(workspaceRoot);
+ await sweepOnce(root);
+ const workspace = join(root, randomUUID());
+ // Exclusive: an existing destination is never reused or followed.
+ await mkdir(workspace, { mode: 0o700 });
+ active.add(workspace);
+ const started = Date.now();
+ try {
+ for (const name of ['input', 'output', 'tmp', 'home']) await mkdir(join(workspace, name), { mode: 0o700 });
+ await stage(join(workspace, 'input'), files);
+ const writable = ['output', 'tmp', 'home'].map((name) => join(workspace, name));
+ const profile = codeAnimationSeatbeltProfile({ executable, toolRoots: codeAnimationToolRoots(executable), workspace });
+ const argv = tool.argv(entrypoint === null ? null : join(workspace, 'input', entrypoint), workspace);
+ // RLIMIT_FSIZE caps any single file (macOS sh counts 1 KiB blocks), no core
+ // dumps, bounded descriptors. `exec` keeps one pid: sh → sandbox-exec → tool.
+ const child = spawn('/bin/sh', ['-c', 'ulimit -c 0 && ulimit -n "$1" && ulimit -f "$2" && shift 2 && exec "$@"',
+ 'portos-contained-worker', String(limits.openFiles), String(Math.max(1, Math.floor(limits.diskBytes / 1024))),
+ seatbeltPath, '-p', profile, executable, ...argv], {
+ cwd: join(workspace, 'tmp'), env: withSpawnCwdEnv(codeAnimationWorkerEnv(workspace), join(workspace, 'tmp')), detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const stdout = tail();
+ const stderr = tail();
+ child.stdout.on('data', stdout.push);
+ child.stderr.on('data', stderr.push);
+ let terminated = null;
+ const kill = (reason) => {
+ terminated ??= reason;
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { /* already gone */ }
+ };
+ const onAbort = () => kill('canceled');
+ signal?.addEventListener('abort', onAbort, { once: true });
+ if (signal?.aborted) onAbort();
+ const timer = setTimeout(() => kill('time'), limits.wallSeconds * 1000);
+ let checking = false;
+ const watchdog = setInterval(async () => {
+ if (checking || terminated) return;
+ checking = true;
+ try {
+ const usage = await measure(writable, limits);
+ if (usage.bytes > limits.diskBytes) kill('disk');
+ else if (usage.files > limits.maxFiles) kill('files');
+ else if (await residentBytes(child.pid) > limits.memoryBytes) kill('memory');
+ } catch (error) {
+ console.error(`❌ Code Animation worker watchdog failed: ${error.message}`);
+ kill('watchdog');
+ } finally { checking = false; }
+ }, tickMs);
+ const exit = await new Promise((resolve) => {
+ child.once('error', (error) => resolve({ code: null, signal: null, error }));
+ child.once('close', (code, sig) => resolve({ code, signal: sig, error: null }));
+ });
+ clearTimeout(timer);
+ clearInterval(watchdog);
+ signal?.removeEventListener('abort', onAbort);
+ // The worker cannot fork, but the group is still verified empty, and any
+ // straggler is killed before the run is reported.
+ let processGroupClear = !groupAlive(child.pid);
+ for (let attempt = 0; !processGroupClear && attempt < 20; attempt += 1) {
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ processGroupClear = !groupAlive(child.pid);
+ }
+ if (exit.signal === 'SIGXFSZ') terminated ??= 'file-size';
+ const usage = await measure(writable, limits);
+ if (!terminated && usage.bytes > limits.diskBytes) terminated = 'disk';
+ if (!terminated && usage.files > limits.maxFiles) terminated = 'files';
+ let status = 'completed';
+ let reason = null;
+ if (terminated) { status = 'terminated'; reason = terminated; }
+ else if (exit.error || exit.code !== 0) { status = 'failed'; reason = exit.error ? 'spawn' : 'exit'; }
+ else if (usage.invalid.length) { status = 'failed'; reason = 'output-invalid'; }
+ const result = {
+ status, reason, mechanism: mechanism.id, exitCode: exit.code, signal: exit.signal,
+ processGroupClear, durationMs: Date.now() - started, limits,
+ usage: { bytes: usage.bytes, files: usage.files },
+ outputs: status === 'completed' ? usage.outputs : [], invalidOutputs: usage.invalid,
+ stdout: stdout.get(), stderr: stderr.get(),
+ };
+ if (status === 'completed' && onOutput) await onOutput(join(workspace, 'output'), result.outputs);
+ return result;
+ } finally {
+ await rm(workspace, { recursive: true, force: true });
+ active.delete(workspace);
+ }
+}
diff --git a/server/services/codeAnimation/containedWorker.test.js b/server/services/codeAnimation/containedWorker.test.js
new file mode 100644
index 0000000000..cbd08ce9e3
--- /dev/null
+++ b/server/services/codeAnimation/containedWorker.test.js
@@ -0,0 +1,81 @@
+import { afterAll, describe, expect, it } from 'vitest';
+import { existsSync } from 'node:fs';
+import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { CODE_ANIMATION_SEATBELT } from '../../lib/codeAnimationContainment.js';
+import { runContainedWorker } from './containedWorker.js';
+
+// Real-mechanism suite: these run only where the enforced sandbox exists. The
+// adversarial boundary and limit checks run end to end through the probe route
+// (routes/codeAnimationExecution.test.js); this file pins the worker lifecycle.
+const seatbelt = process.platform === 'darwin' && existsSync(CODE_ANIMATION_SEATBELT);
+const roots = [];
+const workspaceRoot = async () => {
+ const root = await mkdtemp(join(tmpdir(), 'portos-contained-worker-'));
+ roots.push(root);
+ return root;
+};
+const node = (extra = []) => ({ executable: process.execPath, argv: (entry) => [entry, ...extra] });
+afterAll(async () => { await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); });
+
+describe('contained worker refusal', () => {
+ it('refuses with no enforced mechanism and creates no workspace', async () => {
+ const root = await workspaceRoot();
+ await expect(runContainedWorker({
+ tool: node(), workspaceRoot: root, entrypoint: 'main.cjs',
+ files: [{ path: 'main.cjs', content: 'require("fs").writeFileSync("/tmp/never", "x")' }],
+ seatbeltPath: join(root, 'missing-sandbox-exec'),
+ })).rejects.toMatchObject({ status: 503, code: 'CODE_ANIMATION_CONTAINMENT_UNAVAILABLE' });
+ expect(await readdir(root)).toEqual([]);
+ });
+});
+
+describe.skipIf(!seatbelt)('contained worker lifecycle under macOS Seatbelt', () => {
+ it('stages input read-only, collects regular output files, then removes the workspace', async () => {
+ const root = await workspaceRoot();
+ let collected = null;
+ const result = await runContainedWorker({
+ tool: node(), workspaceRoot: root, entrypoint: 'src/main.cjs',
+ files: [
+ { path: 'src/main.cjs', content: 'const fs = require("fs"); const out = process.env.PORTOS_WORKER_OUTPUT; fs.mkdirSync(out + "/frames"); fs.writeFileSync(out + "/frames/0001.txt", fs.readFileSync(__dirname + "/../assets/cue.txt")); console.log("rendered");' },
+ { path: 'assets/cue.txt', content: Buffer.from('frame').toString('base64'), encoding: 'base64' },
+ ],
+ onOutput: async (dir, outputs) => { collected = { outputs, body: await readFile(join(dir, 'frames/0001.txt'), 'utf8') }; },
+ });
+ expect(result).toMatchObject({ status: 'completed', mechanism: 'macos-seatbelt', exitCode: 0, processGroupClear: true });
+ expect(result.stdout).toContain('rendered');
+ expect(collected).toEqual({ outputs: [{ path: 'frames/0001.txt', bytes: 5 }], body: 'frame' });
+ expect(await readdir(root)).toEqual([]);
+ });
+
+ it('refuses output a worker linked rather than wrote, without handing it to the caller', async () => {
+ const root = await workspaceRoot();
+ let handed = false;
+ const result = await runContainedWorker({
+ tool: node(), workspaceRoot: root, entrypoint: 'main.cjs',
+ files: [{ path: 'main.cjs', content: 'require("fs").symlinkSync("/etc/hosts", process.env.PORTOS_WORKER_OUTPUT + "/hosts")' }],
+ onOutput: async () => { handed = true; },
+ });
+ expect(result).toMatchObject({ status: 'failed', reason: 'output-invalid', invalidOutputs: ['hosts'], outputs: [] });
+ expect(handed).toBe(false);
+ });
+
+ it('reports a failing worker with its diagnostics and an empty process group', async () => {
+ const root = await workspaceRoot();
+ const result = await runContainedWorker({
+ tool: node(), workspaceRoot: root, entrypoint: 'main.cjs',
+ files: [{ path: 'main.cjs', content: 'console.error("scene failed: missing camera"); process.exit(3)' }],
+ });
+ expect(result).toMatchObject({ status: 'failed', reason: 'exit', exitCode: 3, processGroupClear: true });
+ expect(result.stderr).toContain('scene failed: missing camera');
+ });
+
+ it('refuses an entrypoint that is not a staged file before spawning', async () => {
+ const root = await workspaceRoot();
+ await expect(runContainedWorker({
+ tool: node(), workspaceRoot: root, entrypoint: '../escape.cjs', files: [{ path: 'main.cjs', content: '' }],
+ })).rejects.toMatchObject({ status: 400, code: 'CODE_ANIMATION_STAGE_PATH' });
+ expect(await readdir(root)).toEqual([]);
+ });
+});
diff --git a/server/services/codeAnimation/execution.js b/server/services/codeAnimation/execution.js
new file mode 100644
index 0000000000..fcb233aa5b
--- /dev/null
+++ b/server/services/codeAnimation/execution.js
@@ -0,0 +1,255 @@
+/**
+ * Code Animation production execution capability (#9388): operator-owned tool
+ * configuration, an on-demand adversarial containment probe, and the
+ * fail-closed readiness report later render stages gate on. Nothing here runs
+ * at boot or calls a provider.
+ */
+import { createServer } from 'node:net';
+import { constants } from 'node:fs';
+import { access, lstat, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
+import { homedir, tmpdir } from 'node:os';
+import { isAbsolute, join, relative, sep } from 'node:path';
+import { PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { validateRequest } from '../../lib/validation.js';
+import {
+ codeAnimationExecutionToolsSchema, codeAnimationToolRoots, codeAnimationWorkerEnv, codeAnimationWorkerLimitsSchema,
+} from '../../lib/codeAnimationContainment.js';
+import { getSettings, updateSettings } from '../settings.js';
+import { cdpRequest } from '../browserService.js';
+import { currentContainmentMechanism, runContainedWorker } from './containedWorker.js';
+
+const SETTINGS_KEY = 'codeAnimationExecution';
+const WORKSPACE_DIR = 'code-animation-workspaces';
+const UNSAFE_PATH = /["\\()\0\r\n]/;
+
+// The browser lane reuses the HTML-composition renderer sandbox unchanged.
+const BROWSER_LANE = {
+ mechanism: 'chromium-cdp-sandbox',
+ boundary: [
+ 'Assets are an in-memory snapshot of the staged directory; symlinks and paths outside it are refused.',
+ 'Every request is intercepted: only the snapshot origin is fulfilled; network, WebSocket, WebRTC, workers, frames and popups are refused.',
+ 'Each render uses a disposable browser context with no cookies or credentials, closed on cancel or failure.',
+ ],
+ limits: [
+ 'Runs inside the shared managed Chromium; its renderer sandbox, not a PortOS-owned process group, contains page code.',
+ 'Bounded by per-command timeouts and render cancellation; no per-render memory cap.',
+ 'Page code can write nothing to disk.',
+ ],
+};
+
+let lastProbe = null;
+let probing = null;
+
+const inside = (root, path) => {
+ const rel = relative(root, path);
+ return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel));
+};
+
+/**
+ * Validate an operator-supplied executable: `{ executable: realpath, fingerprint, problem: null }`
+ * or a problem. The fingerprint ties containment evidence to these exact bytes on disk.
+ */
+async function inspectExecutable(path) {
+ if (!path) return { executable: null, problem: 'Not configured.' };
+ if (!isAbsolute(path) || UNSAFE_PATH.test(path)) return { executable: null, problem: 'Enter an absolute path without quote, backslash or parenthesis characters.' };
+ const executable = await realpath(path).catch(() => null);
+ if (!executable || UNSAFE_PATH.test(executable)) return { executable: null, problem: 'The executable was not found.' };
+ const info = await lstat(executable).catch(() => null);
+ if (!info?.isFile() || !(await access(executable, constants.X_OK).then(() => true, () => false))) {
+ return { executable: null, problem: 'The path is not an executable file.' };
+ }
+ const data = await realpath(PATHS.data).catch(() => PATHS.data);
+ const home = await realpath(homedir()).catch(() => homedir());
+ // Workers may read the tool's roots; they must never expose PortOS data or the home directory.
+ if (inside(data, executable) || codeAnimationToolRoots(executable).some((root) => inside(root, data) || inside(root, home))) {
+ return { executable: null, problem: 'Install the tool in its own application bundle or directory, outside PortOS data and not directly in the home directory.' };
+ }
+ return { executable, fingerprint: `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}`, problem: null };
+}
+
+async function configuredTools() {
+ const parsed = codeAnimationExecutionToolsSchema.safeParse((await getSettings())?.[SETTINGS_KEY]);
+ return parsed.success ? parsed.data : { blender: { executable: null } };
+}
+
+function blenderLane(mechanism, blender) {
+ if (!mechanism.supported) return { ready: false, reason: mechanism.reason };
+ if (!blender.executable) return { ready: false, reason: `Blender: ${blender.problem}` };
+ const evidence = lastProbe?.tools?.blender;
+ if (!lastProbe?.passed) return { ready: false, reason: 'Run the containment check; execution stays refused until it passes on this server process.' };
+ if (!evidence || evidence.executable !== blender.executable || evidence.fingerprint !== blender.fingerprint) {
+ return { ready: false, reason: 'The configured Blender changed since the last containment check.' };
+ }
+ if (!evidence.passed) return { ready: false, reason: 'Blender did not start under containment.' };
+ return { ready: true, reason: null };
+}
+
+export async function getCodeAnimationExecution() {
+ const mechanism = await currentContainmentMechanism();
+ const blender = await inspectExecutable((await configuredTools()).blender.executable);
+ return {
+ platform: process.platform, mechanism, probe: lastProbe,
+ tools: { blender },
+ lanes: { browser: BROWSER_LANE, blender: blenderLane(mechanism, blender) },
+ defaultLimits: codeAnimationWorkerLimitsSchema.parse({}),
+ };
+}
+
+export async function setCodeAnimationExecutionTools(input) {
+ const tools = validateRequest(codeAnimationExecutionToolsSchema, input);
+ let executable = null;
+ if (tools.blender.executable) {
+ const inspected = await inspectExecutable(tools.blender.executable);
+ if (inspected.problem) throw new ServerError(inspected.problem, { status: 400, code: 'CODE_ANIMATION_TOOL_INVALID' });
+ executable = inspected.executable;
+ }
+ await updateSettings({ [SETTINGS_KEY]: { blender: { executable } } });
+ return getCodeAnimationExecution();
+}
+
+// Synthetic adversarial package. It reports only allowed/denied codes, never
+// any content it managed to read.
+const BOUNDARY_SCRIPT = String.raw`
+const fs = require('fs'); const net = require('net'); const cp = require('child_process');
+const [canary, dataDir, homeDir, port] = process.argv.slice(2);
+const attempt = (fn) => { try { fn(); return { allowed: true }; } catch (e) { return { allowed: false, code: e.code || 'ERROR' }; } };
+const connect = (options) => new Promise((resolve) => {
+ const socket = net.connect(options);
+ const timer = setTimeout(() => { socket.destroy(); resolve({ allowed: false, code: 'TIMEOUT' }); }, 3000);
+ socket.once('connect', () => { clearTimeout(timer); socket.destroy(); resolve({ allowed: true }); });
+ socket.once('error', (e) => { clearTimeout(timer); resolve({ allowed: false, code: e.code || 'ERROR' }); });
+});
+(async () => {
+ const report = {
+ readOutside: attempt(() => fs.readFileSync(canary)),
+ listData: attempt(() => fs.readdirSync(dataDir)),
+ listHome: attempt(() => fs.readdirSync(homeDir)),
+ writeOutside: attempt(() => fs.writeFileSync(canary + '.written', 'x')),
+ writeInput: attempt(() => fs.writeFileSync(__dirname + '/written.txt', 'x')),
+ spawnProcess: attempt(() => { const r = cp.spawnSync('/bin/sh', ['-c', 'exit 0']); if (r.error) throw r.error; }),
+ oversizedFile: attempt(() => fs.writeFileSync(process.env.PORTOS_WORKER_OUTPUT + '/big.bin', Buffer.alloc(2 * 1024 * 1024))),
+ envKeys: Object.keys(process.env).sort(),
+ loopback: await connect({ host: '127.0.0.1', port: Number(port) }),
+ remote: await connect({ host: '192.0.2.10', port: 443 }),
+ };
+ fs.rmSync(process.env.PORTOS_WORKER_OUTPUT + '/big.bin', { force: true });
+ fs.writeFileSync(process.env.PORTOS_WORKER_OUTPUT + '/report.json', JSON.stringify(report));
+})();
+`;
+
+const LIMIT_SCRIPTS = {
+ time: 'for (;;) {}',
+ disk: `let n = 0; setInterval(() => require('fs').writeFileSync(process.env.PORTOS_WORKER_OUTPUT + '/f' + (n++), Buffer.alloc(64 * 1024, 1)), 5);`,
+ memory: 'const held = Buffer.alloc(512 * 1024 * 1024, 1); for (;;) { held[0] += 1; }',
+ cancel: 'for (;;) {}',
+};
+
+// PortOS's own interpreter stands in for a configured tool: the same staging,
+// sandbox, environment and limits, running synthetic hostile scripts.
+const probeTool = (extra = []) => ({ executable: process.execPath, argv: (entry) => [entry, ...extra] });
+
+const denied = (result, code = 'EPERM') => result && result.allowed === false && result.code === code;
+
+async function probeBoundary(workspaceRoot) {
+ const scratch = await mkdtemp(join(tmpdir(), 'portos-containment-canary-'));
+ const canary = join(scratch, 'canary.txt');
+ await writeFile(canary, 'containment canary\n');
+ let connections = 0;
+ const listener = createServer((socket) => { connections += 1; socket.destroy(); });
+ await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve));
+ try {
+ let report = null;
+ const run = await runContainedWorker({
+ tool: probeTool([canary, await realpath(PATHS.data).catch(() => PATHS.data), homedir(), String(listener.address().port)]),
+ workspaceRoot, entrypoint: 'probe.cjs', tickMs: 200,
+ files: [{ path: 'probe.cjs', content: BOUNDARY_SCRIPT }],
+ limits: { wallSeconds: 30, diskBytes: 1024 * 1024, maxFiles: 64, memoryBytes: 1024 * 1024 * 1024, openFiles: 256 },
+ onOutput: async (dir) => { report = JSON.parse(await readFile(join(dir, 'report.json'), 'utf8')); },
+ });
+ if (!report) return [{ id: 'worker-runs', passed: false, detail: `The contained worker did not complete (${run.status}${run.reason ? `: ${run.reason}` : ''}).` }];
+ // /bin/sh (which applies the rlimits before exec) adds its own bookkeeping.
+ const allowedEnv = new Set([...Object.keys(codeAnimationWorkerEnv('/')), 'PWD', 'OLDPWD', 'SHLVL', '_']);
+ const inherited = (report.envKeys || []).filter((key) => !allowedEnv.has(key));
+ return [
+ { id: 'worker-runs', passed: true, detail: 'Positive control: the worker ran and wrote its report to the output directory.' },
+ { id: 'read-outside', passed: denied(report.readOutside), detail: 'A file outside the workspace could not be read.' },
+ { id: 'list-data', passed: denied(report.listData), detail: 'The PortOS data directory could not be listed.' },
+ { id: 'list-home', passed: denied(report.listHome), detail: 'The home directory could not be listed.' },
+ { id: 'write-outside', passed: denied(report.writeOutside), detail: 'Nothing could be written outside the workspace.' },
+ { id: 'write-input', passed: denied(report.writeInput), detail: 'Staged input is read-only.' },
+ { id: 'spawn-process', passed: denied(report.spawnProcess), detail: 'No shell, installer or other process could be started.' },
+ { id: 'file-size', passed: report.oversizedFile?.allowed === false, detail: 'A single file larger than the disk limit could not be written.' },
+ { id: 'credentials', passed: Array.isArray(report.envKeys) && inherited.length === 0, detail: inherited.length ? `Unexpected inherited variables: ${inherited.length}.` : 'The environment contained only the worker’s own paths; no PortOS token or credential was inherited.' },
+ { id: 'host-api', passed: denied(report.loopback) && connections === 0, detail: 'Loopback (where PortOS and local services listen) was unreachable.' },
+ { id: 'network', passed: denied(report.remote), detail: 'Outbound network was refused by the sandbox.' },
+ ];
+ } finally {
+ listener.close();
+ await rm(scratch, { recursive: true, force: true });
+ }
+}
+
+async function probeLimit(workspaceRoot, kind, limits, expected) {
+ const controller = new AbortController();
+ const timer = kind === 'cancel' ? setTimeout(() => controller.abort(), 300) : null;
+ try {
+ const run = await runContainedWorker({
+ tool: probeTool(), workspaceRoot, entrypoint: 'limit.cjs', tickMs: 100, signal: controller.signal,
+ files: [{ path: 'limit.cjs', content: LIMIT_SCRIPTS[kind] }],
+ limits: { wallSeconds: 20, diskBytes: 1024 * 1024, maxFiles: 10_000, memoryBytes: 1024 * 1024 * 1024, openFiles: 256, ...limits },
+ }).catch((error) => ({ status: 'failed', reason: error.message, processGroupClear: false }));
+ return {
+ id: `limit-${kind}`, passed: run.status === 'terminated' && run.reason === expected && run.processGroupClear,
+ detail: `Terminated by ${run.reason ?? run.status}; process group ${run.processGroupClear ? 'empty' : 'NOT empty'} afterwards.`,
+ };
+ } finally { clearTimeout(timer); }
+}
+
+async function probeBlender({ executable, fingerprint }, workspaceRoot) {
+ if (!executable) return null;
+ const run = await runContainedWorker({
+ tool: { executable, argv: () => ['--background', '--factory-startup', '--version'] }, workspaceRoot,
+ limits: { wallSeconds: 60, diskBytes: 64 * 1024 * 1024, maxFiles: 1000 },
+ }).catch((error) => ({ status: 'failed', reason: error.message, stdout: '' }));
+ const version = /^Blender \d+\.\d+(?:\.\d+)?/m.exec(run.stdout || '')?.[0] ?? null;
+ return {
+ executable, fingerprint, passed: run.status === 'completed' && Boolean(version), version,
+ detail: version ? `${version} started under containment (CPU only; no GPU device access is granted).` : `Blender did not start under containment (${run.status}${run.reason ? `: ${run.reason}` : ''}).`,
+ };
+}
+
+async function runProbe() {
+ const started = Date.now();
+ // Fail closed while checking, and if the check itself errors.
+ lastProbe = null;
+ const mechanism = await currentContainmentMechanism();
+ if (!mechanism.supported) {
+ lastProbe = { probedAt: new Date().toISOString(), mechanism: null, passed: false, refused: mechanism.reason, checks: [], tools: {}, browser: null, durationMs: 0 };
+ return lastProbe;
+ }
+ const workspaceRoot = join(PATHS.data, WORKSPACE_DIR);
+ const checks = [
+ ...await probeBoundary(workspaceRoot),
+ await probeLimit(workspaceRoot, 'time', { wallSeconds: 1 }, 'time'),
+ await probeLimit(workspaceRoot, 'disk', {}, 'disk'),
+ await probeLimit(workspaceRoot, 'memory', { memoryBytes: 128 * 1024 * 1024 }, 'memory'),
+ await probeLimit(workspaceRoot, 'cancel', {}, 'canceled'),
+ ];
+ const blender = await probeBlender(await inspectExecutable((await configuredTools()).blender.executable), workspaceRoot);
+ const browser = await cdpRequest('/json/version', { timeout: 2000 }).then((response) => response.ok, () => false);
+ lastProbe = {
+ probedAt: new Date().toISOString(), mechanism: mechanism.id, passed: checks.every((check) => check.passed),
+ refused: null, checks, tools: blender ? { blender } : {}, browser: { available: browser }, durationMs: Date.now() - started,
+ };
+ const log = lastProbe.passed ? console.log : console.error;
+ log(`${lastProbe.passed ? '🛡️' : '❌'} Code Animation containment check ${lastProbe.passed ? 'passed' : 'FAILED'} (${checks.filter((check) => check.passed).length}/${checks.length})`);
+ return lastProbe;
+}
+
+/** Run the adversarial self-test on demand; concurrent requests share one run. */
+export async function probeCodeAnimationExecution() {
+ probing ??= runProbe().finally(() => { probing = null; });
+ await probing;
+ return getCodeAnimationExecution();
+}
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 0a6bad5f30..abbff08d99 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -86,6 +86,7 @@ export const CATEGORIES = {
'music-video': { label: 'Music Video Development Files', description: 'Versioned development artifacts (check-in sheets, animatics, treatments) and composition documents referenced by Music Video projects', archivable: true, deletable: false },
'music-video-compositions': { label: 'Music Video Overlay Scratch', description: 'Typography overlay frames for an in-flight composed music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },
'music-video-song-renders': { label: 'Music Video Composition Render Scratch', description: 'A staged copy of a composition document plus its scene media for an in-flight music-video render — removed when the render ends and swept at boot', archivable: false, deletable: false },
+ 'code-animation-workspaces': { label: 'Code Animation Contained Workers', description: 'Per-run staged input, output and scratch for a sandboxed Code Animation worker — removed when the run ends and swept on the next run', archivable: false, deletable: false },
'code-animations': { label: 'Code Animations', description: 'Generated animation HTML retained with its job history — the only copy of provider-generated work', archivable: true, deletable: false },
'code-animation-exports': { label: 'Code Animation Export Staging', description: 'Animation HTML plus the frame-exact render shim, staged once per MP4 export — safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
'commission-feedback': { label: 'Commission Feedback', description: 'Reactions on creative commissions (file mirror of the Postgres store)', archivable: true, deletable: false },