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

AI Focus

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

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

I have a very soft spot for the MessageChannel API. I think it’s magical, and I’ve been building a side-passion project 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” 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

  1. 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, Anthropic’s third-party app accounts. 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’s opaque CryptoKey handles in IndexedDB: 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 (source on GitHub, live router origin at 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 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, 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 (or Chrome’s built-in LanguageModel 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.)

Connecting to router on llmchannel.dev...

Grants are scoped to this article origin and lent via bounded MessagePorts.

Manage keys ↗

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.

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 from the router origin. Most browser AI code already expects the OpenAI Chat Completions shape rather than a bespoke protocol, so the router exposes ai.chat.completions.create() directly over the grant:

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, a single-file MessagePort RPC library inspired by Comlink that batches chained calls in one microtask, forwards AbortSignals, cleans up async iterators via Symbol.dispose and 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:

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

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() 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.

First, why do the popup and hidden iframe have to talk across that boundary at all? Under Client-Side 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, IndexedDB, the Cache API, SharedWorker, BroadcastChannel, and Service Workers 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() 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:

ChannelCreated byHeld byCarries
Site ↔ IframeHost site (openFrame())Host site and frame-worker.js inside frame.htmlPrompts and streamed replies
Popup ↔ IframeRouter popup (findFrame())pick.html and frame.htmlVerified 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 and the live Attack Lab 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): although reading window.opener DOM or storage throws SecurityError, opener.length and indexed frames opener[i] remain exposed for postMessage():

// 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 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 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, 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 creates an ephemeral ECDH P-256 key pair and sends only the public key to pick.html. Clicking Allow uses Web Crypto unwrapKey() and 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)
// 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 at /call-worker/<provider>.js. Under W3C Content Security Policy Level 3, 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):

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

Unlike an HTML document, new 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 also emits Chrome’s draft WICG Connection-Allowlist header (spec) 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 gets its own single-endpoint route:

RouteAllowed connect-src endpoint
/call-worker/anthropic.jshttps://api.anthropic.com/v1/messages
/call-worker/openai.jshttps://api.openai.com/v1/chat/completions
/call-worker/openrouter.jshttps://openrouter.ai/api/v1/chat/completions
/call-worker/gemini.jshttps://generativelanguage.googleapis.com/v1beta/openai/chat/completions
/call-worker/ollama.jshttp://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:

// 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 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/ 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, 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 workspace (pi-harness-v1), an in-memory fallback, and a local folder opened with showDirectoryPicker({ mode: "readwrite" }) and are managed in the host client (not llmchannel.dev), and it’s the same for the execution of the seven AgentTools (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"> 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” 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.

Add a note

Notes are reviewed before other readers see them.

Subscribe to the Newsletter

Get the latest essays and projects on how AI is changing the medium of the web delivered straight to your inbox.

labs and areas that I am exploring - 2026-12-01

my chrome extensions are just prompts - 2026-11-18

My voice harness is my new operating system - 2026-11-16

extensible web apps - 2026-11-08

Latest stats on Claude Commits - 2026-11-01

wat the heck: why ship javascript when nobody reads the code? - 2026-10-30

setting goals - 2026-10-25

how might a modern lighthouse work with large language models? - 2026-07-03

does a url in a prompt steer an llm's output toward its content? - 2026-07-03

please mind the model gap - 2026-06-07

I think i've got it: WebMCP is the new web intents - 2026-06-06

building a claw in the browser - 2026-05-22

shipping a prompt - 2026-05-22

how fast do ai models go stale? - 2026-05-18

are pwas cooked? - 2026-05-17

a business in a box - 2026-05-10

How might a browser be developed? - 2026-05-03

agent-do: my agent loop - 2026-05-01

webmcp is the new web intents ... maybe - 2026-04-27

damn claude, that's a lot of commits - 2026-03-30

the token salary - 2026-03-27

the llm whisperer - 2026-03-08

the prompt is the program - 2026-02-21

If NotebookLM was a web browser - 2026-01-25

the browser is the sandbox - 2026-01-25

the projects behind my ai focus posts - 2026-01-02

hyper content negotiation - 2025-11-27

headless cms was a stopgap - 2025-11-23

dead framework theory - 2025-10-12

intercepting the web with an llm - 2025-09-21

calling apis from the browser shouldn't mean exposing keys - 2025-08-22

hypermedia was always the point - 2025-08-18

web components are packaging for ai-generated ui - 2025-07-16

what happens to the cms when ai can build the site? - 2025-07-05

what token slinging taught me about ai costs - 2025-06-30

on-device ai needs a trust model - 2025-06-12

AI Assisted Web Development - 2025-06-04

embedding is the web's composability superpower - 2025-05-28

ai agents make mashups worth revisiting - 2025-05-24

what falling ai model latency means for the web - 2025-05-22

A link is all you need - 2025-05-17

llms are becoming the new super-apps - 2025-05-12

this transition feels different - 2025-05-09