# Fenced policy sandbox in the page: opaque-origin iframe + per-run Worker, wired like the WebRTC ingress (rev 2, plan only) Status: proposed, waiting for owner approval. No code is written until it is approved. Rev 2 (2026-10-30, owner, atirc seq 836): follow the established wasm pattern of the WebRTC ingress (an API value declared in socialweb and only instantiated by the wasm build, a contract interface with a native and a `js && wasm` implementation, a page half reached through one `__socialweb` bridge, state in resource status) instead of rev 1's ad-hoc `__kcpSandbox*` globals. The fence mechanism (opaque iframe + per-run Worker) is unchanged. Also records the owner's stable-rkey preference for the bundled tangled-vouch action. ## Context The owner chose option C of plan 0036 (section 2): evaluate socialweb policy (e.g. `requester-tangled-vouch`) inside the page's kcp.wasm instead of in Go-only checks. Today every policy verdict in the page would be Deny, because the page's runner says it is not fenced. References: socialweb at `origin/main` 90d0435e (`~/src/kcp/socialweb-computer-kcp`, read only); this repo at `kcp-wasm-memory-storage-1`. ### What "Fenced" means in socialweb - Interface `internal/contract/sandbox/sandbox.go:8-38`: `Program{Source, Dir, Timeout, Net, Env}` -> `Result{ExitCode, TimedOut, Stdout, Stderr}`; `Runner{Run, Available, Fenced, Kind}`. `Fenced()` is a self-declared bool. No test anywhere asserts fencing (no `_test.go` under `internal/sandbox` or `internal/policyengine/workflow`; nothing greps for `Fenced` in tests). - Linux runner `internal/sandbox/deno/deno.go`: `Fenced()` is always true (:42). It runs `deno run --quiet --no-prompt --no-config`, then `--allow-net` if `Net`, else `--deny-net --no-remote --no-lock` (:59-64), `--allow-read/--allow-write=` only if `Dir` (:65-67), `--deny-run --deny-ffi --ext ts -` (:68), the program on stdin, a closed environment when `Env` is set (:74-76), a timeout via `context.WithTimeout` (default 2 min, :18-20, :53-58) and stdout/stderr capped at 64 KiB each (:22, :77-80). No memory cap (V8 default heap). - What the policy engine asks for: every `${{ }}` expression and every `uses:` action is one `Run` with `Net: true`, no `Dir`, `Env` = `NO_COLOR`, `DENO_NO_UPDATE_CHECK` + step env (`internal/policyengine/workflow/expression.go:285-314`, `action.go:101-129`; `CONTRIBUTING.md:1116-1127`). So for policy code the Linux fence is: **no filesystem, no ambient env, no subprocess, no FFI, killed at the deadline, output capped; network allowed** (and since `--no-remote` is only added without net, remote `import()` is allowed too). - The gate: `expression.go:289` refuses a runner with `Fenced() == false`; `Engine.Ready()` (`internal/policyengine/controller/engine.go:164-166`) needs `Available() && Fenced()`; `manager.go:113-131` turns that into the PolicyEngine `Ready` condition (when false the message is hard-coded "the embedded or system deno runtime is unavailable", :125-130); the run controller (`internal/controllers/policyworkflowrun/controller.go:159-173`) only runs on a ready engine. A refused expression falls back to the pure-Go property-path resolver (`expression.go:108-121`), an action step fails, the verdict is Deny (`CONTRIBUTING.md:1121-1127`). - Inputs Go -> sandbox: the program text only. Expressions are a generated script with the contexts inlined as JSON literals (`github`, `steps`, `inputs`, `env`, `secrets`, `vars`, `needs`, `matrix`; `expression.go:136-205`); the answer is `console.log` on stdout. An action is `actionShim` + the bundled `dist/index.js` + footer (`action.go:116-120, 209-309`): the shim inlines the step env, the policy cache (`GITHUB_CACHE`) and the event, overrides `Deno.env`, `Deno.writeTextFile(Sync)`/`readTextFile(Sync)` for the virtual `GITHUB_*` files, routes `console.*` to stderr, turns `Deno.exit` into a throw, and prints one `__PE_RESULT__{code, vfs}` line on stdout that Go parses (`action.go:131-200`: outputs, env, cache updates). - Host APIs the bundled action uses (`tangy/policy-requester-tangled-vouch/dist/index.js`, 300 KB): `Deno.env.get`, `Deno.exit`, `Deno.readTextFileSync`, `Deno.writeTextFile(Sync)` (all through the shim), `Deno.stdout/stderr.writeSync` and `Deno.inspect` (shim), top-level `await`, and `fetch` (5 sites: did:web, plc.directory, `/.well-known/atproto-did`, `com.atproto.repo.getRecord` :9438-9448, `listRecords` :9451-9470). The trust lookups read `cache["trust/"]` first (`operatorOf.json`, `vouchedBy.json`, :9827-9840), which Go seeds from `trust.BuildSnapshotFor` only when the run reconciler has a `Host` (`internal/policyengine/controller/run.go:277-288`); without it the action fetches itself. - Who writes the code: the bundled actions are ours (`executor.BundledActions`, `engine.go:509`); workflow text can come from a `PolicyWorkflow` record (`RecordRef`), and its `${{ }}` expressions are arbitrary JS. On the page (requester only) that is the requester's own chosen workflow; counterparty records arrive as data (JSON literals). ### The page today - `socialweb-wasm/internal/socialweb/orchestrator.go:315-326`: engine factory with `Sandbox: worker.New()`, `DisableActions: true`, then only `policyenginectl.Register`. No `policyworkflow`/`policyworkflowrun` controllers and no trust `Host` are registered (compare socialweb `internal/controllers/policy/register.go:67-93`), so even a fenced runner would never see a `PolicyWorkflowRun`. - socialweb `internal/sandbox/worker/worker.go`: a module Worker from a same-origin `blob:` URL (:77-83), program run with `new Function` (:51), `console.*` captured, timeout 2 min (:111-119). `Fenced()` false (:27-29) is correct: that Worker has the page's origin, so it can open the page's IndexedDB (OAuth sessions and DPoP keys, kcp state), Cache Storage and OPFS, join the page's `BroadcastChannel`s, `fetch` same-origin URLs as the page (dev server `/debug/*`), `import()`/`importScripts` anything, and spawn Workers. It also has no `Deno` global, so the action shim (`Deno.exit.bind`, `Deno.writeTextFile.bind`) would throw at line 1 anyway. - No CSP, COOP or COEP on either host: `scripts/kubectl_wasm_web.ts` sets none, the Caddy site from `scripts/deploy.sh:100-110` sets only `Cache-Control` and the metadata `Content-Type`. ### The established wasm pattern: the WebRTC ingress How the requester's WebRTC ingress (commit 4585d48e6 "webrtc ingress", plan 0034 for the guest side) is built, layer by layer: | Layer | WebRTC ingress | Where | | --- | --- | --- | | API value declared in socialweb, instantiated only by the wasm build | `IngressConfig{Provider: "webrtc", WebRTC: &IngressWebRTCConfig{STUNURLs, SessionTTLSeconds, MaxSessions}}` | socialweb `api/v1alpha1/types_application.go:216-236`; the page sets it in `createRoot` (`orchestrator.go:528-532`) and keeps it on restore (`:544-546`) | | Schema | generated from socialweb, never hand-written: no wasm-only kinds exist | `socialweb-wasm/manifests/README.md:1-6` ("Do not edit by hand"), `marketrequester-apiresourceschema.yaml` (synced in 4585d48e6) | | Contract interface + injection seam | `tunnel.Service{Offer, Accept, Close}`, `tunnel.ServiceOptions`; requester `Deps.OpenIngress` | socialweb `internal/contract/tunnel/tunnel.go:42-56`, `internal/services/requester/service.go:35, :153-170` | | Native implementation | pion, build-tag split for js | socialweb `internal/ingress/webrtc/webrtc.go`, `settings_js.go` / `settings_other.go` | | wasm implementation | `browserwebrtc.NewService` (`//go:build js && wasm`) and a stub that errors (`//go:build !js \|\| !wasm`) | `socialweb-wasm/internal/browserwebrtc/service.go:1, :79-123`, `service_other.go:1-23`; injected at `socialweb-wasm/internal/socialweb/requester_runner.go:59-60` | | Page half | ES module imported by the kcp worker and published as one bridge object; Go refuses to start without it and installs its callbacks once | `scripts/browser/kcp_worker.js:159-164` -> `scripts/browser/webrtc_ingress.js`; `service.go:83-86` (`__socialwebWebRTC`), `:131-137` (`__socialwebWebRTC{Open,Data,Close,State}`) | | State to the page | through resources, not globals: ContractEvents (guest `signalWebRTC`) reconciled by the contractevent controller registered in wasm, pushed to the page by the status feed | `orchestrator.go:335-344`; `socialweb-wasm/internal/statusfeed/feed.go:122-170, :238`; `kcp_worker.js:173-181` (`__kcpState`); page side `scripts/browser/webrtc_guest.js:296-320` | Related: `socialweb-wasm/internal/browserinfra/{exposure,vaulthost}` substitute controllers for existing kinds and write the same status shape as the real controllers (`browserinfra/exposure/README.md` "Exact status written"; registered at `orchestrator.go:208, :233`). `contrib/wasm/apis/fetch` (`fetch.kcp.io` Fetch CRD) is the older kcp-only demo and not part of the socialweb pattern. Consequence for this plan: no new `PolicySandbox` kind (it would be the only hand-written schema in `socialweb-wasm/manifests`). The sandbox becomes a provider value on the existing `PolicyEngine` kind, declared in socialweb like `IngressConfig.Provider`, with the probe result on `PolicyEngine.status.conditions`. ## Options | | Page-origin authority | Kill / timeout | Memory cap | iOS Safari | Size / boot | Same results as Deno | | --- | --- | --- | --- | --- | --- | --- | | (a) `sandbox="allow-scripts"` srcdoc iframe (opaque origin) + per-run module Worker it creates | none: opaque origin has its own (or no) storage, no page DOM, no page channels; fetch carries `Origin: null`, no credentials | `worker.terminate()` from the iframe; iframe removal as backstop | none (as Linux) | sandbox attribute and module Workers are supported; **Worker from `blob:null/...` inside an opaque iframe must be proven on the iPhone** (step 0) | 0 new bytes; ~1 thread + JSC VM per run | same JS, native engine; only the `Deno` shim differs | | (b) Worker from blob/data URL under a CSP | blob: same origin, CSP does not restrict IndexedDB/OPFS; data: gives an opaque origin but Worker support and CSP inheritance vary by engine | `terminate()` | none | data: Workers in WebKit uncertain | 0 | same | | (c) QuickJS-ng (or Boa) compiled to wasm, in a Worker | none by construction: only the host functions we expose | interrupt handler + `terminate()` | yes (`JS_SetMemoryLimit`) | works anywhere wasm works | ~1 MB wasm + polyfills (`URL`, `TextEncoder`, `AbortController`, `setTimeout`, `fetch`, `Deno.*`); interpreter speed | different engine: 300 KB bundles with modern syntax/regex/Intl may diverge | | (d) ShadowRealm | not a security boundary (same agent, same thread) | none: a loop blocks the caller | none | not shipped (flag only) | 0 | n/a | Not considered further: a cross-origin iframe on a second host (`sandbox.`) gives the same isolation as (a) but needs another deploy; JS-level "delete `indexedDB`/`fetch`" hardening in a same-origin Worker is bypassable (`import()` cannot be deleted) and is not a fence. ## Design (recommended: option (a), wired like the WebRTC ingress) The browser enforces the fence (origin isolation), as deno enforces it with permission flags, and the program runs on the same kind of JS engine with nothing new to download. Option (c) stays the fallback if step 0 fails on the iPhone. ### 0. Feasibility probe on the iPhone (before any other code) One `phone.sh` snippet, run on the iPhone and in headless Chrome: create the srcdoc iframe of section 4, have it build a module Worker from a `blob:` URL (then a `data:` URL), post back `self.origin`, `typeof Deno`, whether top-level `await` works, and the facts of section 5. Go/no-go for (a); if blob and data Workers both fail in Safari, stop and write the (c) plan. ### 1. API (socialweb; request linux-kcp) Mirror `IngressConfig` on `PolicyEngineSpec` (`api/policy/v1alpha1/types_policyengine.go:22-32`): ```go Sandbox *PolicySandboxConfig `json:"sandbox,omitempty"` type PolicySandboxConfig struct { Provider string `json:"provider,omitempty" apigen:"enum=deno|browser"` // empty = deno Browser *PolicyBrowserSandboxConfig `json:"browser,omitempty"` } type PolicyBrowserSandboxConfig struct { TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty" apigen:"default=120,minimum=1"` } ``` Status needs no new field: `PolicyEngineStatus.Conditions` (`:72-80`) gets a `Fenced` condition type. Then `make sync-socialweb-manifests` here (`policyengine-apiresourceschema.yaml`). ### 2. Contract (socialweb; request linux-kcp) - `internal/contract/sandbox`: an optional interface next to `Runner` (`sandbox.go:30-38`), type-asserted, so the deno runner and every caller stay unchanged: ```go type Fence struct { Fenced bool; Reason, Message string } type Prober interface { Probe(ctx context.Context) (Fence, error) } ``` - `internal/policyengine/controller`: `Config` (`engine.go:39-51`) gains `OpenSandbox func(ctx context.Context, spec *policyv1alpha1.PolicySandboxConfig) (sandbox.Runner, error)`, the counterpart of requester `Deps.OpenIngress`; the default factory uses it when set, else `Config.Sandbox`. A `browser` provider with no `OpenSandbox` fails the factory, which `manager.go:82-91` already reports as `Ready=False, reason CreateFailed` (a native host never pretends to run the browser sandbox). - `manager.go` `reconcileState` (:111-131): if the runner is a `Prober`, call it when the engine is created and write `Fenced` (`True`/`False`, reason `ProbePassed`/`ProbeFailed`/`NotProbed`, message = the compact fact list); when not ready, use that reason instead of the hard-coded deno message (:125-130). `Engine.Ready()` stays `Available() && Fenced()`. - `internal/controllers/policy.Options` (`register.go:25-41`) passes `OpenSandbox` through. ### 3. wasm implementation: `socialweb-wasm/internal/browsersandbox/` (new) Same shape as `browserwebrtc`: - `runner.go` (`//go:build js && wasm`): `New(cfg)` returns an error when the page has no `__socialwebSandbox` bridge object with `run`/`kill`/`probe` functions (as `service.go:83-86`). It implements `sandbox.Runner` and `sandbox.Prober`: `Kind() = "browser"`, `Available()` = bridge present, `Fenced()` = last `Probe` passed; `Probe` calls `__socialwebSandbox.probe()` and caches the `Fence`. - `Run`: refuses `Dir != ""` and `Net == false` with an error (the page only runs policy programs; the bidder compute kind is not served by the page and must not get a weaker fence than it asked for). Marshals `{id, source, env, timeoutMs}`, awaits the Promise from a goroutine (pattern `cmd/kcp-wasm/refresher_js.go:33-60`; never from a `js.FuncOf` callback, socialweb `CONTRIBUTING.md:1080-1084`), returns `TimedOut` on its own timer or `ctx.Done()` and calls `kill(id)`. Output capped at 64 KiB per stream (`deno.go:22`). One run at a time (`chan struct{}` of 1) to bound iOS memory: an evaluation is about a dozen `Run`s (one per `${{ }}` plus the action), sequential anyway. - `runner_other.go` (`//go:build !js || !wasm`): `New` returns an error (as `service_other.go`), so native tests in `socialweb-wasm` build. ### 4. Page half: `scripts/browser/policy_sandbox.js` (new), `kcp_worker.js`, `app.js` - `startFrame()` (main thread, `app.js`): appends one hidden `