Port Authority

Port patterns / The four primitives

Give a frame limited access, then revoke it

Holding a port is the permission to use it. Instead of exposing full write access, the owner creates a new channel, keeps one end, and only answers read on it. To revoke access, it closes its end — no tokens, no ACLs, no trusting the guest to clean up.

When you'd use this

Say you're building a document editor and want to support third-party plugins like a word counter. When the user turns the plugin on, you hand it a read-only port; when they turn it off, sign out, or open a private document, you call revoke(). You don't have to trust the plugin to clean up after itself, and each plugin gets its own channel so revoking one won't affect any others.

Code

function readOnly(counter) {
  const { port1, port2 } = new MessageChannel();
  port1.onmessage = (e) => port1.postMessage(e.data === "read" ? counter.value : "denied");
  return { port: port2, revoke: () => port1.close() };
}

In practice

// document editor + third-party word-count plugin in an iframe
const grant = readOnly(counter);
plugin.contentWindow.postMessage({ counter: grant.port }, pluginOrigin, [grant.port]);

// inside the plugin: const port = event.data.counter;
port.postMessage("read");
port.onmessage = (e) => show(e.data);

// user disables the plugin, signs out, or opens a private doc
offButton.onclick = () => grant.revoke();

// The plugin still holds its port, but nothing answers it now.
// No close event fires, so the plugin needs a timeout to notice.

How it works

The owner holds full authority (here a counter it can read and increment), but wants to hand a guest read-only access. So it creates a new channel, keeps one end behind a narrow handler that only answers read, and transfers the other end to the guest.

The restriction lives entirely on the owner's side of the port. The guest can post whatever it likes; anything outside the allowlist is ignored or refused.

Revocation is one line: port1.close(). Because each grant gets its own channel, revoking one plugin never affects any other plugin — and you don't need token lists or trust the guest to stop.

You can apply the exact same principle to direction to build a one-way data diode (see the one-way figures widget below): put a valve in the middle that copies plain JSON forward without a transfer list (so ports can't sneak through) and drops everything sent backwards.

Step by step

What each press of Next does in the demo above.

  1. Share read-only. The owner creates a channel, keeps one end that only answers read, and transfers the read-only port to the guest.
  2. Guest reads. The guest reads the counter through its port and gets 41.
  3. Guest tries to add. The guest tries to increment the counter and gets denied by the owner's handler.
  4. Owner adds one. The owner increments its own counter to 42.
  5. Revoke. The owner closes its end of the guest's channel, cutting the cable immediately.
  6. Guest reads. The guest tries again and hears silence — closing a port doesn't fire an event on the far side.

What you can build with it

Built and running below.

Access that runs out after eight seconds

Time-limited or use-limited access: count calls in the handler and close the port at the limit.

The owner lends the guest a port to its diary, and starts a clock. While the clock runs, the guest's questions are answered. When it stops, the owner closes its end. The guest still holds a port. Nothing comes back from it. There was no token to expire and no session to clean up.

Code

const { port1, port2 } = new MessageChannel();
port1.onmessage = () => port1.postMessage(diary.today());
guest.postMessage({ cmd: "port" }, guestOrigin, [port2]);
setTimeout(() => port1.close(), 8000);      // that is the whole expiry

Step by step

What each press of Next does in this demo.

  1. Lend the diary for 8 seconds. The guest is given a port. The owner will close its end in eight seconds.
  2. Guest: ask what is on today. Inside the time, the guest gets an answer.
  3. Guest: ask what is on today. Time is up. The guest asks again and hears nothing.

Pass access on to a third party, with less than you were given

Delegation chains where each intermediary hands on less authority than it holds.

The owner lets an assistant read the diary and add to it. The assistant passes part of that on to an intern: reading only. The intern's port ends at the assistant, and the assistant's ends at the owner. Nobody in the chain can hand on more than they hold. When the owner cuts off the assistant, the intern is cut off too, without the owner knowing the intern exists.

Code

// the assistant, passing on less than it was given
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => {
  if (data.do !== "read") return port1.postMessage({ refused: "read only" });
  ownerPort.postMessage(data);            // forwarded up the chain
};
give(intern, port2);

Step by step

What each press of Next does in this demo.

  1. Give the assistant read and add. The assistant gets a port that reads and adds.
  2. Assistant: pass on read only. The assistant makes a weaker port and gives it to the intern.
  3. Intern: read. The intern's question goes to the assistant, then to the owner, and the answer comes back down.
  4. Intern: try to add. The assistant refuses. It never reaches the owner.
  5. Owner: cut off the assistant. The owner closes the assistant's port.
  6. Intern: read. The intern asks again. The chain is broken above it, and nothing comes back.

An embed that is shown two fields of your app's state, and no others

Third-party embeds that should only see a narrow slice of your app's state.

This page's state has a name, an email address, a theme and a basket. A reviews embed from another origin needs to match the theme and show how many things are in the basket. It is given a port that carries those two fields, each time they change. A change to the email address sends nothing, and asking for it is refused.

Code

const view = ({ theme, basket }) => ({ theme, basket });     // the whole of what the embed may know
const { port1, port2 } = new MessageChannel();
onStateChange((state, changed) => {
  if (changed in view(state)) port1.postMessage(view(state));
});
embed.postMessage({ cmd: "port" }, embedOrigin, [port2]);

Step by step

What each press of Next does in this demo.

  1. Give the embed a narrow view. The embed gets a port, and the two fields it may see.
  2. Switch the theme. The theme is in the view, so the embed hears of it.
  3. Add to the basket. So is the basket.
  4. Change the email address. The email address is not in the view. Nothing is sent.
  5. Embed: ask for the email address. The embed asks anyway, and is refused.

Give a chart widget your figures on a port it cannot answer on

Feeding sensitive figures one-way to a locked-down chart widget that can't talk back.

The widget stands in for someone else's code. It is a sandboxed frame with an opaque origin and a Content Security Policy that forbids it any network access. This page sends it a month of spending to draw. The widget receives the figures on a real port, and then tries two ways to send them somewhere: a network request, and a message back into the port. The browser blocks the first. The second reaches this page's valve and stops there, and this page counts it.

Code

const link = oneWay();
widget.postMessage({ cmd: "feed" }, "*", [link.receive]);

link.send.postMessage({ figures });       // the widget draws them

// the widget, trying
port.postMessage({ stolen: figures });    // stops at the valve
fetch(somewhere, { body: figures });      // blocked: default-src 'none'

Step by step

What each press of Next does in this demo.

  1. Give the widget a one-way port. This page makes the two channels and gives the widget the end it can hear on.
  2. Send this month's spending. The figures go down the port, and the widget draws them.
  3. Widget: try to send the figures out. The widget posts the figures back into its port and tries a network request. Neither arrives anywhere.

A stream given as read-only still lets the reader signal the writer

Understanding why a transferred ReadableStream isn't strictly one-way — timing reads creates a covert back-channel.

A ReadableStream looks one-way: the holder can read and has nothing to write into. But a stream asks its source for the next chunk only when the reader wants one, so the writer can see when each read happens. The frame here holds only a readable stream. It spells a word by choosing when to read: a short wait for a 0, a long wait for a 1. This page reads the word back from nothing but the times its own pull() was called. Then the same frame gets a one-way port. Messages on a port are pushed on the sender's clock rather than pulled by the reader, closing the back-pressure timing channel (though a busy receiver on a shared thread can still contend for CPU).

Code

// the writer sees when the reader reads
const readable = new ReadableStream({
  pull(controller) { times.push(performance.now()); controller.enqueue("tick"); },
}, { highWaterMark: 0 });
frame.postMessage({ readable }, "*", [readable]);

// the reader, holding only the readable, sends bits with its timing
for (const bit of bits) { await wait(bit ? 360 : 120); await reader.read(); }

Step by step

What each press of Next does in this demo.

  1. Give the frame a read-only stream. The frame gets a stream it can read. It has nothing to write into.
  2. Frame: spell a word by when it reads. The frame reads slowly or quickly, one bit per read. This page works the word out from the times its source was asked.
  3. Give the frame a one-way port. Now the same ticks go to the frame as messages on a one-way port.
  4. Frame: try the same on the port. The frame takes its messages on the same rhythm as before. This page sends on its own clock and sees no difference.

Things to try

  • Share read-only, read, try to add, then revoke and read again.
  • Share read-only again after revoking — a fresh channel works without changing the guest's code.
  • Try the one-way diode and covert timing demos below to see where one-way guarantees end.

Gotchas

  • Attenuation only holds if the guest never also receives the unattenuated port.
  • A port is a bearer capability: the guest can forward its limited port to someone else, who inherits that limited access until you revoke it.
  • Closing your end doesn't fire an event on the guest's side — the port close event was removed from the HTML spec in October 2026. Their calls simply go silent.

References

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

Transferable objects
Objects that can be moved to another page or worker instead of copied. After the move the sender can no longer use them. The transfer list is the argument to postMessage that names them. MDNHTML Standard
Content Security Policy
A header that limits what a page may load and where it may connect. MDNContent Security Policy
ReadableStream
A source of data that is read a piece at a time. It can be moved to another page or worker. MDNStreams Standard

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