Port Authority

Port patterns / Capabilities and trust boundaries

Prove who holds the other end of a MessagePort

On a MessagePort, event.origin is always "" and event.source is null. Because a port is a bearer capability, whoever you handed it to can silently forward it to a third party without the browser telling you. Here Trusted Client generates a non-extractable ECDSA P-256 key pair, registers its public key with Service, and proves possession on a fresh 128-bit nonce challenge. Once Trusted Client forwards that exact port to Third Party, the very next challenge catches the handover — Third Party doesn't have the private key, so its replay is refused and Service closes the port.

When you'd use this

A service receives a MessagePort forwarded through an introducer popup or SharedWorker hub and needs to know the real client still holds the far end before executing a privileged action. Because MessageEvent.origin is always empty on ports and any holder can silently forward a port onward, challenging the port with a fresh nonce against a non-extractable ECDSA key proves current possession rather than just who opened the original channel.

Code

// Trusted Client: private key is non-extractable, so it can't be copied or leaked
const keys = await crypto.subtle.generateKey(
  { name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]
);

// Service: event.origin is always "" on a MessagePort, so issue a fresh 128-bit nonce
const nonce = crypto.getRandomValues(new Uint8Array(16));
port.postMessage({ nonce });
const { sig } = await nextMessage(port);
const ok = await crypto.subtle.verify(
  { name: "ECDSA", hash: "SHA-256" }, clientPublicKey, sig, nonce
);
if (!ok) port.close(); // wrong key or replayed signature

In practice

// A broker popup handed our service a port that claims to be the billing app.
// Because event.origin on port messages is always "", verify before trusting it.
async function verifyHolder(port, expectedPublicKey) {
  const nonce = crypto.getRandomValues(new Uint8Array(16));
  const reply = new Promise((resolve) => {
    const timer = setTimeout(() => resolve(null), 1500);
    port.addEventListener("message", (e) => {
      clearTimeout(timer);
      resolve(e.data?.sig || null);
    }, { once: true });
    port.start();
  });
  port.postMessage({ type: "challenge", nonce });
  const sig = await reply;
  const ok = Boolean(sig) && await crypto.subtle.verify(
    { name: "ECDSA", hash: "SHA-256" }, expectedPublicKey, sig, nonce
  );
  if (!ok) port.close();
  return ok;
}

How it works

When a message arrives over window.postMessage, the browser populates event.origin and event.source, and the sender can't forge them. On a MessagePort, both fields are useless for identity: event.origin is always "" and event.source is always null.

That's by design — ports are bearer capabilities. Checking event.origin once during the initial window handshake tells you who you handed the port to, not who still holds it five minutes later. Any holder can transfer its end down another channel to a third party, and your side gets no event when ownership moves.

If you need to know who's at the far end right now, bind the port to a non-extractable ECDSA key pair created with crypto.subtle.generateKey(..., false, ["sign", "verify"]). Because the private key isn't extractable, even compromised JavaScript in the client can't copy the raw bytes out to another origin.

Whenever you accept a relayed port — or before authorising a sensitive action on a long-lived port — send a fresh 128-bit random nonce and verify the returned signature against the client's known public key. A fresh nonce kills replay attacks; a signature mismatch tells you to call port.close() immediately.

Step by step

What each press of Next does in the demo above.

  1. Client registers public key. Trusted Client creates a channel and transfers one port plus its ECDSA P-256 public key to Service. The private key stays non-extractable inside Trusted Client.
  2. Service challenges the port. Service posts a random 128-bit nonce down the port. Trusted Client signs it with its private key, and Service verifies the signature.
  3. Client forwards the port. Trusted Client transfers its end of the port to Third Party. Service isn't notified — the same channel now terminates in Third Party.
  4. Service challenges again. Service sends a fresh nonce down the exact same port. Third Party can only replay the old signature, Service catches the mismatch with crypto.subtle.verify(), and slams the port shut.

What you can build with it

Other ideas

  • Re-verifying a client after a MessagePort has been passed through a broker, introducer popup, or SharedWorker mesh.
  • Step-up authentication on a long-lived port before authorising destructive writes, payments, or account changes.
  • Mutual authentication between two origins whose Service Workers were paired through a third-party hub page.

Things to try

  • Run Step 2 first and watch Trusted Client's signature verify cleanly even though event.origin logs as "".
  • Forward the port to Third Party in Step 3, then watch Service challenge the exact same port in Step 4 and slam it shut when Third Party tries to replay the old signature.
  • Compare this with keeping signing keys behind a port: even if a key isn't extractable, you must never transfer the private CryptoKey object itself over a port.

Gotchas

  • Public key distribution still needs a root of trust. In production, fetch the client's public key from its HTTPS origin (or pin it during an origin-checked window.postMessage handshake), rather than trusting whatever key arrives inline on an unverified port.
  • A single challenge at startup only proves who held the port at that instant. If the client might forward the port later, re-challenge before sensitive operations or sign each critical payload with a per-request nonce.
  • Web Crypto (crypto.subtle) requires a secure context (HTTPS or localhost), and non-extractable keys can still be cloned if you accidentally pass the CryptoKey itself to postMessage — keep the private key strictly in closure scope or IndexedDB.

References

The web platform features this page mentions, with what each one is, its documentation on MDN and the specification that defines it.

MessagePort
One end of a message channel. Whatever is posted into it comes out of the other end, and it can be sent to another page, frame or worker. MDNHTML Standard
MessageEvent.origin
The origin of the page that sent a message. MDNHTML Standard
MessageEvent.source
The window, port or worker that sent a message. MDNHTML Standard
SharedWorker
A worker that every page on the same origin can connect to. Each page that connects gets a port to it. MDNHTML Standard
Window.postMessage()
Sends a message to another window or frame, which can be on a different origin. The receiver has to check who sent it. MDNHTML Standard
Web Crypto API
The browser's built-in functions for making keys, signing, encrypting and hashing. MDNWeb Cryptography
Service workers
A worker the browser starts for an origin to handle its network requests and events, even when no page is open. The browser stops it when it is idle. MDNService Workers
CryptoKey
A key made by the Web Crypto API. It is an opaque object: code can use it to sign or encrypt, but a key marked as not extractable can never be read out, even after it is posted to another page. MDNWeb Cryptography
MessagePort.postMessage()
Sends a message through a port. A second argument lists the objects to move instead of copy. MDNHTML Standard
IndexedDB
A database in the browser that belongs to one origin. It can store most things that can be posted, including a CryptoKey. MDNIndexed Database API

For more, see Further reading: articles, talks, papers, libraries and the specifications, collected in one place.