Repository navigation
relay: in-tab worker via Web Worker + snippets use scoped token - #334
Conversation
+ snippets use the scoped token end-to-end Two issues user reported after PR #333 merged: 1. Clicking Connect from the in-tab worker died with "engine init failed: The operation is insecure." That's the fundamental limitation of opaque-origin iframes: sandbox without allow-same-origin gives the iframe an opaque null origin, and opaque origins cannot open IndexedDB. WebLLM caches multi-GB model weights there and refuses to init without it. We were on the wrong side of an inherent browser tradeoff: lose IndexedDB OR lose origin isolation. 2. The relay tab still rendered snippets with the MAIN gateway token. The whole point of the per-process scoped token from the previous commit was to hand external workers a credential that doesn't unlock /v1/chat etc -- but the UI was leaking the main token into every copy-paste block. FIX 1: switch from sandboxed iframe to dedicated Web Worker. - Workers are same-origin, so IndexedDB + WebGPU + SharedArrayBuffer all work. WebLLM can actually start. - Worker scope has no `window` and no `localStorage` -- the isolation property we wanted from the iframe is still here. - No DOM access; communicates only via postMessage. The parent UI hands the worker a token via postMessage at Connect time; that token is the ONLY credential the worker ever sees. - PasClaw uses bearer-token auth (no cookies), so a same-origin fetch from the worker has no implicit credentials. The worker can call /v1/* only with tokens we explicitly pass it, and we only pass the relay-scoped token. Module worker spawned from a Blob: URL with `{type: 'module'}` so `await import('https://esm.run/...')` still works inside; the WebLLM fetch stays gated behind the Connect click. EventSource is exposed in DedicatedWorker scope in every evergreen browser. Hint text in the Relay tab updated: "dedicated Web Worker (no window / localStorage in Worker scope)" instead of the old "opaque-origin sandboxed iframe" copy. FIX 2: snippets render the relay-scoped token, not the main token. - setupRelayTab now eagerly calls GET /v1/relay/worker-token at tab load (gated by main token, so unauth'd gateways return 200 anyway) and caches the result in _relayScopedToken. - relayEffectiveToken returns _relayScopedToken when "show" is on; the placeholder when masked. - syncRelayTokenInput renders the scoped token (or "fetching ..." while the GET is in flight). The input label changed from "Bearer token" to "Relay worker token" with a fresh hint paragraph explaining the scoping. - The placeholder string changed from <PASCLAW_GATEWAY_TOKEN> to <PASCLAW_RELAY_TOKEN> -- when an operator screen-shares the masked snippets, the visible text now names the right env var. - env-vars snippet uses `export PASCLAW_RELAY_TOKEN=...` instead of `PASCLAW_GATEWAY_TOKEN`. Verified rendered output contains no occurrence of the operator's main token. CLI parity: PasClaw.Cmd.Relay now reads PASCLAW_RELAY_TOKEN as the preferred env var (the scoped credential printed at `pasclaw serve` startup), falling back to PASCLAW_GATEWAY_TOKEN for back-compat. Both work; the snippet defaults to the more specific name. Smoke (gateway with main token MAINTOKEN, port 18910): - jsdom render at /#relay: zero runtime errors - server-side GET /v1/relay/worker-token returns HENQ-4WW2 - env-vars snippet body: export PASCLAW_GATEWAY_URL=http://127.0.0.1:18910 export PASCLAW_RELAY_TOKEN=<PASCLAW_RELAY_TOKEN> pasclaw relay - snippet contains "MAINTOKEN": false (main token never leaks) - 23/23 relay queue tests still green Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6e0efead07
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (!_relayScopedToken && gwToken()) { | ||
| await refreshRelayScopedToken(); |
There was a problem hiding this comment.
Refresh the scoped token when connecting
If the gateway restarts while the Relay tab stays open, TGatewayServer.Create regenerates FRelayToken, but this guard skips refreshRelayScopedToken() whenever the cached _relayScopedToken is non-empty. In that common restart/config-change scenario, clicking Connect keeps passing the old relay token to /v1/relay/poll, so the in-browser worker gets 401s until the whole page is reloaded; refresh on Connect or retry after a 401 instead of trusting the non-empty cache.
Useful? React with 👍 / 👎.
Codex P2 review on PR #334. The Connect-time guard if (!_relayScopedToken && gwToken()) await refreshRelayScopedToken(); only re-fetched when the cache was EMPTY. TGatewayServer.Create regenerates FRelayToken on every startup, so if the gateway restarted (or its config reloaded) while the Relay tab stayed open, the stale cached token kept getting handed to the Worker -> the worker 401'd against the fresh server-side token -> the in-browser worker spun forever on the auto-retry loop until the operator reloaded the whole page. Fix: always call refreshRelayScopedToken() on Connect when a main token is set. The fetch is one tiny JSON GET; freshness matters more than the cache hit. Also re-runs syncRelayTokenInput + renderRelaySnippets so the visible token / displayed snippet bodies reflect the just-refreshed value (covers the case where the operator had "show" on with a stale token visible). Live smoke (gateway with main token MAINTOKEN, port 18911): boot #1 token: KYNB-G50W -> /v1/relay/status 200 restart boot #2 token: 76QZ-GGCD -> /v1/relay/status 200 stale KYNB-G50W against fresh #2 -> 401 (the failure mode) fresh 76QZ-GGCD against fresh #2 -> 200 (the fix path) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
Two real issues you hit after PR #333:
"engine init failed: The operation is insecure" — fundamental limitation of opaque-origin sandboxed iframes. Without
allow-same-origin, the iframe gets an opaque null origin → IndexedDB / SharedArrayBuffer are blocked → WebLLM (which caches multi-GB weights in IndexedDB) refuses to initialise. We were on the wrong side of an inherent browser trade-off.UI/snippets still referenced
PASCLAW_GATEWAY_TOKEN— the whole point of the scoped per-process token from PR webui: in-tab WebLLM relay worker w/ lazy esm.run import #333 was for external workers to use a credential that doesn't unlock/v1/chatetc., but the snippets were still rendering with the main gateway token.Fix 1 — switch the isolation primitive: iframe → dedicated Web Worker
Web Workers are the right shape for "isolate untrusted JS that needs storage":
localStoragewindow)/v1/*The worker can call
/v1/*only with tokens we explicitly hand it viapostMessage, and we only hand it the relay-scoped token. Net credential isolation is the same as the iframe approach, but WebLLM actually works — IndexedDB lets it cache model weights, so the second Connect doesn't re-download multi-GB blobs.Module worker spawned from a
Blob:URL with{type: 'module'}soawait import('https://esm.run/...')still works inside; the WebLLM fetch stays gated behind Connect.UI hint updated: "dedicated Web Worker (Worker scope has no
window/localStorage...)" instead of "opaque-origin sandboxed iframe."Fix 2 — snippets and UI render the scoped token, not the main token
setupRelayTabeagerly callsGET /v1/relay/worker-token(gated by main token) and caches_relayScopedToken.relayEffectiveTokenreturns the scoped token when "show" is on, placeholder otherwise.syncRelayTokenInputrenders the scoped token; the field label changed from "Bearer token" to "Relay worker token" with hint text explaining the scoping.<PASCLAW_GATEWAY_TOKEN>→<PASCLAW_RELAY_TOKEN>.export PASCLAW_RELAY_TOKEN=...instead ofPASCLAW_GATEWAY_TOKEN=....pasclaw relaynow readsPASCLAW_RELAY_TOKEN(preferred) then falls back toPASCLAW_GATEWAY_TOKENfor back-compat.Test plan
make allclean.make test-relay-queue— 23/23 green.new Worker(_relayInbWorkerUrl)present ✓_relayInbIframe/srcdocreferences ✓self.addEventListener/self.postMessagein worker script ✓<PASCLAW_RELAY_TOKEN>✓PASCLAW_RELAY_TOKEN(notPASCLAW_GATEWAY_TOKEN) ✓/#relay: zero runtime errors.GET /v1/relay/worker-tokenreturns the scoped token (e.g.HENQ-4WW2).URL.createObjectURL/Workernatively).🤖 Generated with Claude Code
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code