# in-browser LLM router without exposing API keys to every page

> How a site can isolate user API keys to LLMs via a dedicated browser origin behind CSP-locked Dedicated Workers and MessagePorts to run LLM based Chat and the Pi coding agent in the browser without exposing API keys to arbitrary websites

_By Paul Kinlan — 3 December 2026_


A forewarning, this is a really long post, but I think you will like it.

I have a very soft spot for the [`MessageChannel`](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel) API. I think it's magical, and I've been building a side-passion project [port-authority.dev](https://port-authority.dev) that aims to showcase some of the patterns for inter-site or inter-frame communication that is enabled by the entangled `Port` API. It enables some experiences that I think most web developers don't know, including features like delegated discovery and subsequent communication between two apps that don't know about each other. During the development of this project it enabled me to answer a problem that I found in "[calling apis from the browser shouldn't mean exposing keys](/dangerous/)" which highlighted the problem for anyone building a client-side web app that calls a language model, you have to either:

1. Run a backend proxy just to hide a provider API key, which means paying for every visitor's inference calls, operating a server, and securing a new proxy surface.

Or

2. Ask visitors to paste their own API key directly into your page (relying on escape hatches like `anthropic-dangerous-direct-browser-access` or `dangerouslyAllowBrowser`), at which point every script running on your origin can read the raw key string and exfiltrate it anywhere.

I don't think either solution is acceptable.

Since then, providers have shipped ways to connect a consumer subscription to external software: [OpenAI's partner app program](https://help.openai.com/en/articles/20001542-using-your-chatgpt-plan-in-other-apps-and-sites), [Anthropic's third-party app accounts](https://support.claude.com/en/articles/18467148-use-your-claude-platform-account-in-a-third-party-app). Those either require the vendor to approve participating partner apps or move the third-party interface inside the vendor's assistant UI. What I wanted to show is that there is another path which I highlighted in my post and is closer to [Web Cryptography](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)'s opaque [`CryptoKey`](https://w3c.github.io/webcrypto/#cryptokey-interface) handles in [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API): a browser-held `Subscription` or `Session` that any open website can invoke against my chosen model without reading the key and without a developer-run proxy.

To test how far _existing_ web primitives can be pushed today, I built the [Port Authority AI Router](https://port-authority.dev/ai-router/) ([source on GitHub](https://github.com/PaulKinlan/port-authority), live router origin at [llmchannel.dev](https://llmchannel.dev/)). You save your provider API keys once on `llmchannel.dev` and on that site only (trust me...). Now, when any other website calls into the router, you see that site's browser-verified origin in a popup, pick an account and model, and set a request count and day limit. The site receives a [`MessagePort`](https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports) that streams completions back to your host without ever touching the API key. There is no backend API server and no server-side grant database; the Cloudflare Worker serving the router delivers static HTML and JavaScript only. The fun thing is that using this router, I also built a [Pi agent harness](https://port-authority.dev/pi/), running a tool-calling coding agent loop, workspace tools, and a JavaScript sandbox in the browser with zero API keys anywhere in the page.

It's seriously pretty cool.

You can try both demos below using your own key saved on [llmchannel.dev](https://llmchannel.dev/) (or Chrome's built-in [`LanguageModel`](https://developer.chrome.com/docs/ai/prompt-api) if available). This page connects to `llmchannel.dev` once under `aifoc.us`, then lends a bounded `MessagePort` into each embedded frame below so neither frame can access your saved conversations or local files.

There's a lot of mechanics happening that I will explain later, but I really want to get the demo to you (note: due to Safari's lack of support for CSP on workers, it's barely tested there.)

Try the live demos on their own origins (no API keys stored on either app):

- [Port Authority Chat](https://port-authority.dev/chat/) — client-side chat client backed by your router on [llmchannel.dev](https://llmchannel.dev/).
- [Port Authority Pi Agent Harness](https://port-authority.dev/pi/) — browser coding agent with file tools and zero-network JavaScript execution over a `MessagePort`.


The diagram below shows how the host page, hidden router iframe, popup window, workers, and model provider fit together. Press **Step through it** (or click any numbered marker) to trace the 13 hops from initial page load through encrypted key handover and a streamed prompt.

[Embedded page](/port-authority-flow.html)

The short version: the key is plaintext in JavaScript in only two places, the input field on `llmchannel.dev/#add` when you first save an account and the call worker while a request is in flight. Every other context holds either ciphertext with a non-extractable `CryptoKey`, or a `MessagePort`.
To see what a host site holds instead of an API key, start with the single [ES module import](https://github.com/PaulKinlan/port-authority/blob/main/sites/router/router.js) from the router origin. Most browser AI code already expects the [OpenAI Chat Completions](https://platform.openai.com/docs/api-reference/chat) shape rather than a bespoke protocol, so the router exposes `ai.chat.completions.create()` directly over the grant:

```js
import { connect } from "https://llmchannel.dev/router.js";

const ai = await connect();              // embeds hidden frame.html, transfers a MessagePort

button.onclick = async () => {
  if (!ai.ready) await ai.choose();      // opens pick.html popup; requires a user gesture
  if (!ai.ready) return;                 // user cancelled

  const stream = await ai.chat.completions.create(
    {
      messages: [
        { role: "system", content: "You write short cards." },
        { role: "user", content: "A card for Ada, who passed her exam." },
      ],
      stream: true,
    },
    { signal: controller.signal },
  );

  for await (const chunk of stream) {
    output.textContent += chunk.choices[0]?.delta?.content ?? "";
  }
};
```

When `connect()` runs, it appends a hidden `<iframe>` pointing at `https://llmchannel.dev/frame.html` with `allow="language-model"` (letting the frame invoke Chrome's on-device Prompt API if present) and `referrerPolicy="no-referrer"` (keeping the host URL out of `Referer` headers). It creates a `MessageChannel`, transfers `port2` into the iframe with `targetOrigin` pinned to `https://llmchannel.dev`, and keeps `port1` for prompts (there is also a simpler `ai.prompt()` helper for one-liners).

The broader principle here is that one origin can project a familiar, stateful API surface directly into an embedding host over a `MessagePort`, without handing over credentials or inventing a bespoke `postMessage` protocol for every app. Rather than building another ad-hoc RPC layer, `router.js` dynamically loads [Hawser](https://port-authority.dev/comlink/), a [single-file `MessagePort` RPC library](https://github.com/PaulKinlan/port-authority/blob/main/sites/shared/hawser.js) inspired by Comlink that batches chained calls in one microtask, forwards [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)s, cleans up async iterators via [`Symbol.dispose`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/dispose) and [`FinalizationRegistry`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry), blocks prototype-chain walks (`__proto__`, `constructor`, `prototype`), and raises `LinkClosedError` when the other context goes away. On the first `create()` call, `router.js` asks `frame-worker.js` for a sub-port where Hawser exposes `chatApi()` behind an explicit path allowlist:

```js
expose(
  chatApi((request, signal) => answer(request, budget, signal), () => (grant ? grant.model : null)),
  line.port1,
  { only: ["chat.completions.create"] },
);
```

> Because access lives in a <code>MessagePort</code> rather than a bearer string, a host page can also call <code>ai.lend({ requests: 3 })</code> to hand a narrower sub-port to a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Worker</a> or an embedded iframe (which cannot re-lend or wipe the host grant). That is how <code>aifoc.us</code> powers the embedded Chat and Pi frames above.


Existing client code calls `ai.chat.completions.create()` with streaming, cancellation, images, or tool definitions just as it would against a standard SDK client, while authority stays on the router's side of the port. Because `expose()` restricts the proxy to `chat.completions.create` and blocks prototype walks, the host cannot widen the surface or inspect worker state. Because the user picked the model in `pick.html`, `chat.js` ignores whatever `model` field the host passes and stamps the real model onto the response, enforces hard request and token limits inside `frame-worker.js`, rejects unsupported options explicitly instead of dropping them silently, and never executes tools itself (returning `tool_calls` to the host and counting each round-trip against the grant).

## Can the MessagePort be forged or MITM'd?

The first objection any web dev should raise is: the untrusted host page embeds `frame.html`, creates the initial `MessageChannel`, and calls [`window.open()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) for `pick.html`. It sits right in the middle of the setup, and it controls its own JavaScript realm before `router.js` ever loads. What stops a hostile site from monkey-patching `MessageChannel`, relaying the handshake, planting decoy iframes, forging grants or ports, spoofing another site's origin, or wiping its request counter? I have spent a lot of time thinking through this threat model, and the checks below are what the router currently relies on. Before anything like this should be trusted in production, it needs independent security review and cross-browser validation beyond my own test suite.

> You can share storage, but I decided to skip <a href="https://privacycg.github.io/storage-access/">document.requestStorageAccess()</a> because a hidden iframe cannot get a user gesture for its permission prompt - I am paranoid about spoofing, and unpartitioned storage would expose every saved account to every embedded copy instead of isolating one scoped grant per host partition.


First, why do the popup and hidden iframe have to talk across that boundary at all? Under [Client-Side Storage Partitioning](https://privacycg.github.io/storage-partitioning/) (which shipped in Chrome 115+, Firefox, and Safari), embedding `https://llmchannel.dev/frame.html` inside another site (such as `aifoc.us`) keys [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), `IndexedDB`, the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage), [`SharedWorker`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker), [`BroadcastChannel`](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel), and [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) by both the top-level site and the embedded origin. Top-level `pick.html` can read your saved accounts, while hidden `frame.html` persists across reloads inside the host site but starts with an empty partition (which needs to be filled).

[`window.postMessage()`](https://html.spec.whatwg.org/multipage/web-messaging.html#posting-messages) is not partitioned, so `pick.html` can hand a scoped grant straight to `frame.html`. To prevent the host page from sitting in the middle of that handover, Port Authority splits traffic across two strictly typed channels:

| Channel | Created by | Held by | Carries |
| :--- | :--- | :--- | :--- |
| **Site ↔ Iframe** | Host site (`openFrame()`) | Host site and `frame-worker.js` inside `frame.html` | Prompts and streamed replies |
| **Popup ↔ Iframe** | Router popup (`findFrame()`) | `pick.html` and `frame.html` | Verified host origin, ephemeral public key, grant, encrypted key copy, and `stop` command |

The core piece is that any port created or touched by the host page (the Site ↔ Iframe port) is treated as untrusted. Even if a hostile page overrides `window.MessageChannel`, `MessagePort.prototype.postMessage`, `window.postMessage`, and `window.open` before importing `router.js` (which the [hostile-site test suite](https://github.com/PaulKinlan/port-authority/blob/main/test/hostile.mjs) and the live [Attack Lab](https://port-authority.dev/ai-router/attacks/) do), tapping those ports only logs the host's own prompts, streamed answers, and public state (`ready`, `model`, `left`). Credentials, grants, encrypted key blobs, and control commands never cross a host-created port.

To open the Popup ↔ Iframe port without letting the host broker the introduction, `pick.js` creates the `MessageChannel` inside its own `llmchannel.dev` realm (where host monkey-patches do not exist) and relies on the narrow cross-origin `Window` surface defined in the [HTML Standard (`CrossOriginProperties`)](https://html.spec.whatwg.org/multipage/nav-history-apis.html#crossoriginproperties-(-o-)): although reading [`window.opener`](https://developer.mozilla.org/en-US/docs/Web/API/Window/opener) DOM or storage throws `SecurityError`, `opener.length` and indexed frames `opener[i]` remain exposed for `postMessage()`:

```js
// pick.js: findFrame()
for (let i = 0; i < count; i++) {
  tries.push(new Promise((resolve) => {
    const line = new MessageChannel();
    line.port1.onmessage = (event) => {
      if (event.data && event.data.t === "site" && event.data.site) {
        resolve({ line: line.port1, ...event.data });
      }
    };
    try {
      opener[i].postMessage({ router: "picker" }, location.origin, [line.port2]);
    } catch { /* not ours */ }
  }));
}
```

I didn't realise that this was possible at all until working on this with my LLM, but it allows `llmchannel.dev` to talk to the `llmchannel.dev` iframe embedded in the host page directly. It relies on two browser features to block decoy iframes and relay attacks.

1. Pinning `targetOrigin` to `location.origin` (`https://llmchannel.dev`) forces the browser to verify each frame's real origin before delivering the message or transferring `line.port2`. If the hostile page plants decoy iframes ahead of the real one (a same-origin `srcdoc` frame, a `data:` frame, or even `<iframe sandbox="allow-scripts" src="https://llmchannel.dev/frame.html">`, which has an opaque `"null"` origin without `allow-same-origin`), the browser drops the message and `port2` for every decoy.
2. [Transferring](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) a `MessagePort` moves ownership rather than copying it: `line.port2` in `pick.html` is delivered directly to the genuine `llmchannel.dev` iframe so that neither end ever passes through the host page, and [Same-Origin Policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) throws `SecurityError` if the host tries to read `contentDocument`, read storage, attach `message` listeners, or overwrite `postMessage` on either the iframe or the `window.open()` popup handle.

Without this, I can't think of a way to securely transport the `MessagePort` in a way that can show there is no interception or relaying of the messages.

Beyond that handover, there are three checks that attempt to guard against forgery and spoofing. First, `frame.js` accepts only one handshake from its parent and ignores any popup message whose browser-stamped `event.origin` is not `https://llmchannel.dev`. Second, `frame-worker.js` separates privileged control messages from untrusted site ports, so a host page cannot inject grants or stop commands over its prompt port. Third, both the iframe and popup refuse nested frames (`parent !== top` and `opener !== opener.top`) and sandboxed or opaque origins (`"null"`), reading the requesting site directly from the browser's `event.origin` so a hostile page should not be able to claim to be `https://bank.example` or embed a trusted site to borrow its name.

If you find a bypass that slips past these checks, I want to know about it.

## Hardening the key inside the router origin

Because of key partitioning for `localStorage` *and* because I don't want to keep the Router picker open, we have to transport keys to the nested iframe. Once `pick.html` has a browser-authenticated port to `frame.html`, the remaining problem is moving and using the API key inside `llmchannel.dev` itself with as small an exposure surface as the browser allows.

In the router's [account store](https://github.com/PaulKinlan/port-authority/blob/main/sites/router/store.js), each API key sits encrypted in `IndexedDB` under a per-account, non-extractable 256-bit `AES-GCM` `CryptoKey`. When `frame.js` answers the popup, [`seal.js`](https://github.com/PaulKinlan/port-authority/blob/main/sites/router/seal.js) creates an ephemeral `ECDH` `P-256` key pair and sends only the public key to `pick.html`. Clicking **Allow** uses Web Crypto [`unwrapKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/unwrapKey) and [`wrapKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/wrapKey) (carrying arbitrary key bytes through an `HMAC` key) to re-encrypt the API key directly to the iframe's ephemeral key without surfacing a plaintext JavaScript string in the popup. `host.js` derives a non-extractable `["decrypt"]` `CryptoKey` and stores it alongside the ciphertext in the iframe's partitioned `IndexedDB`. Although this keeps raw keys out of `IndexedDB` exports, `postMessage` payloads, and `frame.js` / `frame-worker.js` memory, it does not stop XSS on `llmchannel.dev` itself because `wrapKey()` requires `extractable: true` on the transient handle.

**See the Web Crypto reseal() code (seal.js)**

```js
// seal.js: reseal()
const pair = await crypto.subtle.generateKey(CURVE, false, ["deriveKey"]);
const to = await crypto.subtle.deriveKey(
  { name: "ECDH", public: await theirs(pub) },
  pair.privateKey,
  AES,
  false,
  ["wrapKey"],
);
// HMAC accepts arbitrary key byte lengths, carrying the API key bytes inside Web Crypto.
const inside = await crypto.subtle.unwrapKey(
  "raw",
  bytes(kept.sealed.data),
  kept.key,
  { name: "AES-GCM", iv: bytes(kept.sealed.iv) },
  { name: "HMAC", hash: "SHA-256" },
  true,
  ["sign"],
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const data = await crypto.subtle.wrapKey("raw", inside, to, { name: "AES-GCM", iv });
return { from: await crypto.subtle.exportKey("jwk", pair.publicKey), iv: text64(iv), data: text64(data) };
```


Because `frame.html`, `pick.html`, and `frame-worker.js` are all served with `connect-src 'none'`, none of the contexts holding the grant can contact a provider API. Decryption and outbound HTTPS requests move to a separate [Dedicated Worker per provider](https://github.com/PaulKinlan/port-authority/blob/main/sites/router/call-worker.js) at `/call-worker/<provider>.js`. Under [W3C Content Security Policy Level 3](https://w3c.github.io/webappsec-csp/), a Worker takes the `Content-Security-Policy` header from its own script response rather than inheriting the spawning document's policy (note: this doesn't work in Safari yet):

```http
Content-Security-Policy: default-src 'none'; script-src 'self'; connect-src https://api.anthropic.com/v1/messages
```

Unlike an HTML document, [`new Worker()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker) has no DOM, no `location.href` navigation, no `<form>`, and no `<img>` or `<link>` elements to leak data through navigations or subresources. When you switch providers, `host.js` drains active requests, terminates the old worker, and spawns the new one. Because CSP `connect-src` still leaves gaps around preloads, DNS prefetch, WebRTC, and WebTransport on HTML contexts, [the worker](https://github.com/PaulKinlan/port-authority/blob/main/src/worker.js) also emits Chrome's draft [WICG `Connection-Allowlist`](https://github.com/WICG/connection-allowlists) header ([spec](https://wicg.github.io/connection-allowlists/)) to lock down all network traffic except the call to the LLM.

**See the per-provider worker routes and CSP self-check**

Each provider in [the router's endpoint map](https://github.com/PaulKinlan/port-authority/blob/main/src/worker.js) gets its own single-endpoint route:

| Route | Allowed `connect-src` endpoint |
| :--- | :--- |
| `/call-worker/anthropic.js` | `https://api.anthropic.com/v1/messages` |
| `/call-worker/openai.js` | `https://api.openai.com/v1/chat/completions` |
| `/call-worker/openrouter.js` | `https://openrouter.ai/api/v1/chat/completions` |
| `/call-worker/gemini.js` | `https://generativelanguage.googleapis.com/v1beta/openai/chat/completions` |
| `/call-worker/ollama.js` | `http://localhost:11434/v1/chat/completions` |

Because Worker CSP enforcement has varied across browser engines, `call-worker.js` checks its active policy before accepting an encrypted key or port:

```js
// call-worker.js
const heldTo = () => new Promise((resolve) => {
  const late = setTimeout(() => resolve(null), 1500);
  addEventListener("securitypolicyviolation", (event) => {
    clearTimeout(late);
    resolve(event.originalPolicy);
  }, { once: true });
  fetch("/csp-self-check-expected-to-be-blocked").then(
    () => { clearTimeout(late); resolve(null); },
    () => {},
  );
});
```

If CSP holds, that `fetch()` fires a [`securitypolicyviolation`](https://developer.mozilla.org/en-US/docs/Web/API/SecurityPolicyViolationEvent) event whose `originalPolicy` must match `callWorkerPolicy(provider)`. If the browser skips worker CSP, the server returns `204 No Content` immediately so the worker replies `{ t: "unfit" }` right away, and we fall back to a hidden `/call/<provider>` iframe using `connect-src` plus `base-uri 'none'; form-action 'none'` to keep things locked down.


So far all we have been building is a simple chat interface. I wanted to really push this model and see if we can build a coding agent using the same `MessagePort` method across multi-turn tool calls, file edits, and untrusted code execution, where a typical local setup leaves an API key in an environment variable that any executed code can read.

Well... It turns out that you can. [`port-authority.dev/pi/`](https://port-authority.dev/pi/) runs that loop in the browser with zero API keys anywhere in the port-authority site. Pi's agent loop comes from my favourite harness, [`pi`](https://github.com/earendil-works/pi), wired to the router with a thin `streamFn` adapter that forwards `messages` and `tools` into `ai.chat.completions.create()` over the `MessagePort`.

The nice thing is that LLM execution, context and the tool calling are run on two different origins. For example, the three storage backends are managed with one interface: an [Origin Private File System](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system) workspace (`pi-harness-v1`), an in-memory fallback, and a local folder opened with [`showDirectoryPicker({ mode: "readwrite" })`](https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker) and are managed in the host client (not `llmchannel.dev`), and it's the same for the execution of the seven `AgentTool`s (`ls`, `read`, `edit`, `write`, `grep`, `delete`, and `run_js`).
Going one step further, you can even run untrusted code (via `run_js`) inside a temporary [`<iframe sandbox="allow-scripts">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox) with no `allow-same-origin` and CSP `default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'`, denying network access, cookies, DOM access, and OPFS.

I think this is a pretty fun model, and I was very happy to see it all work without changing the pure channel API and semantics provided by `llmchannel.dev`.

Overall I am very happy with how this turned out and I think it's an area that we should explore more. What turned out as a passion project has turned into something that might be an interesting way to provide access to secrets and enable more seamless access to 3P APIs without every site requiring access directly. It reminds me of my "[Off by default web"](https://paul.kinlan.me/the-off-by-default-web/) post where I posited that we should work from the principle of least permission and not allow direct access to dangerous APIs, instead maybe only allow one site we trust to have access. I think this project shows that this is very possible to do.

You may have got here and asked: "Why all this complexity with the iframe?" and it's a great question. The simplest and likely more secure option is to just always keep the `llmchannel.dev` window open. It's certainly a lot less surface area, there is no need to transport the keys to get around the origin partitioning of localStorage data. The answer for me was: I don't think people want a window just hanging around all the time. That being said, I might move back to that model.

Going forwards I want to explore capabilities that an LLM router in the browser might be able to do. For example, because `llmchannel.dev` is the single route to the LLM we could check each message to see if keys are exposed, or we could add better accounting, or we could add in cost-based or latency-based routing like OpenRouter does. The browser is our oyster it seems.


---

Canonical: https://aifoc.us/in-browser-ai-router/
