Skip to content

relay: in-tab worker via Web Worker + snippets use scoped token - #334

Merged
FMXExpress merged 2 commits into
mainfrom
claude/relay-webworker-and-scoped-snippets
Jun 22, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/relay-webworker-and-scoped-snippets

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Two real issues you hit after PR #333:

  1. "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.

  2. 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/chat etc., 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":

Sandboxed iframe (opaque origin) Dedicated Web Worker
IndexedDB ❌ blocked ✓ works
WebGPU storage ❌ blocked ✓ works
SharedArrayBuffer ❌ blocked ✓ works
localStorage ❌ (different origin) ❌ (Worker scope has no window)
Parent DOM access ❌ ❌
Credentialed /v1/* ❌ (different origin) ✓ same origin — but PasClaw uses bearer tokens, not cookies, so no implicit credentials anyway

The worker can call /v1/* only with tokens we explicitly hand it via postMessage, 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'} so await 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

  • setupRelayTab eagerly calls GET /v1/relay/worker-token (gated by main token) and caches _relayScopedToken.
  • relayEffectiveToken returns the scoped token when "show" is on, placeholder otherwise.
  • syncRelayTokenInput renders the scoped token; the field label changed from "Bearer token" to "Relay worker token" with hint text explaining the scoping.
  • Placeholder string <PASCLAW_GATEWAY_TOKEN> → <PASCLAW_RELAY_TOKEN>.
  • Env-vars snippet: export PASCLAW_RELAY_TOKEN=... instead of PASCLAW_GATEWAY_TOKEN=....
  • CLI parity: pasclaw relay now reads PASCLAW_RELAY_TOKEN (preferred) then falls back to PASCLAW_GATEWAY_TOKEN for back-compat.

Test plan

  • make all clean.
  • make test-relay-queue — 23/23 green.
  • Static-grep against served HTML:
    • new Worker(_relayInbWorkerUrl) present ✓
    • no _relayInbIframe / srcdoc references ✓
    • self.addEventListener / self.postMessage in worker script ✓
    • UI hint mentions "Web Worker" ✓
    • placeholder uses <PASCLAW_RELAY_TOKEN> ✓
    • env snippet uses PASCLAW_RELAY_TOKEN (not PASCLAW_GATEWAY_TOKEN) ✓
  • jsdom render at /#relay: zero runtime errors.
  • Rendered env-vars snippet:
    export PASCLAW_GATEWAY_URL=http://...
    export PASCLAW_RELAY_TOKEN=<PASCLAW_RELAY_TOKEN>
    pasclaw relay
    
  • Snippet body contains the operator's main token: false (confirmed — main token never leaks).
  • Server-side: GET /v1/relay/worker-token returns the scoped token (e.g. HENQ-4WW2).
  • Manual: pick a model in Relay tab → click Connect → observe progress bar climb during WebLLM warmup → status flips to "connected -- waiting for jobs" (requires real browser with WebGPU; jsdom doesn't have URL.createObjectURL / Worker natively).

🤖 Generated with Claude Code

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

       + 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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/pkg/gateway/webui.html Outdated
Comment on lines +2737 to +2738
if (!_relayScopedToken && gwToken()) {
await refreshRelayScopedToken();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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
@FMXExpress
FMXExpress merged commit 7d6856d into main Jun 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants