Identity & Trust
A RuntimeCoordinate names each side of a connection, a crypto identity in durable storage proves it, and trust-on-first-use pins the key. Actions and realms both rely on this one identity model.
Every secure connection has two ends, and each end has a name and a proof. The name is a
RuntimeCoordinate. The proof is a crypto identity backed by your storage. Trust-on-first-use
(TOFU) ties a name to a key, so the second connection can tell it’s really the same peer. The whole
stack rests on this one identity model: action routing, realm avatars, and devtools admission all
read it.
Coordinates — the network label
Section titled “Coordinates — the network label”A RuntimeCoordinate labels a runtime environment and routes traffic to the right side. It’s exported
from @nice-code/wire (and re-exported by @nice-code/action), and it lives in your shared module so
both ends reference the exact same value:
RuntimeCoordinate.env("backend"); // a named environmentRuntimeCoordinate.env("backend").withPersistentId("worker-1"); // env + a persistent idRuntimeCoordinate.env("backend").withPersistentId(id.toString()); // env + a persistent idRuntimeCoordinate.unknown; // unspecifiedThe identity you pass to createWireClient (or that an ActionRuntime is built from) is a
coordinate, and the peer you dial is the other side’s coordinate. A realm defaults its avatar’s
persistentId / instanceId from the connection’s authenticated coordinate. So “who is this
avatar?” is answered by the same handshake that authenticated the socket.
The concise getters coordinate.persistentId and coordinate.instanceId expose those concepts in
application code. The existing perId and insId own fields remain the serialized wire shape for
compatibility.
The crypto identity lives in your storage
Section titled “The crypto identity lives in your storage”A secure connection authenticates with an Ed25519 keypair, held by a ClientCryptoKeyLink that
createWireClient builds over the storage you give it. That storage holds this runtime’s signing
keys and the verify keys of peers it has met. It’s why a secure connection needs storage and a
fully none connection doesn’t.
The handshake runs once, before any protocol frame: each side sends its coordinate and public key, then proves it holds the matching private key by signing a fresh, single-use challenge that binds both nonces, both identities, the wire-dictionary version, the security level, and every key exchanged. A replayed or tampered handshake produces a different challenge and fails. After that one exchange, every message travels inside the already-authenticated session, with no per-message crypto. The level of protection that session gives, identity only or identity + encrypted frames, is covered in Security Levels.
It needs WebCrypto
Section titled “It needs WebCrypto”The keys are made and used with WebCrypto (crypto.subtle). A browser provides it only to a
secure context: a page served over HTTPS, or opened on localhost. The same app opened at
http://192.168.1.20:3050 from a phone has none. React Native has none until its
polyfill is installed.
A secure carrier checks for it before it dials. Without it, connect() and every action reject with
crypto_unavailable, whose reason is insecure_context or no_webcrypto. Nothing is dialed and
the redial ladder does not retry, since no retry can change the answer. A secure: false carrier
is not affected, and a chain that lists one after a secure carrier falls through to it.
An older browser can have crypto.subtle without the curves: a Chrome before 137 has no Ed25519.
It passes that check and fails at its first key. The answer is the same crypto_unavailable, with
reason: "algorithm_unsupported" and the curve in algorithm, and it parks and falls through in
the same way. authenticated uses Ed25519; encrypted uses X25519 as well. To decide what to
offer a browser before connecting, ask it: await probeWebCryptoSupport() from @nice-code/wire
answers { ed25519, x25519 }.
import { err_wire_connect } from "@nice-code/wire";
try { await client.connect();} catch (e) { if (err_wire_connect.isExact(e) && e.hasId("crypto_unavailable")) { const { reason } = e.getContext("crypto_unavailable"); // "insecure_context": ask for the page to be opened over HTTPS. // "no_webcrypto": the WebCrypto polyfill was not installed before connecting. // "algorithm_unsupported": the browser is too old for the curve in `algorithm`. }}One identity per storage
Section titled “One identity per storage”Every connection you build over the same storage adapter shares one identity: createWireClient
and connectChannel keep a single key link per adapter, so two connections in one page present the
same keys. Pass the same adapter object to each of them.
The first use of a fresh store mints the keys. Two connections that dial at the same moment, or two
tabs opened at once on a new browser, could otherwise each find the store empty and each mint a key.
The peer pins the first one it sees and refuses the other with identity_pin_mismatch, for good.
The mint is therefore guarded:
- Where the runtime has Web Locks (browsers, in a secure context), a lock named for the storage’s key prefix is held while the store is read, the key made and the key written. Every tab and worker of the origin waits its turn and adopts the key that is already there.
- Without Web Locks (React Native, some server runtimes), the same turn is taken inside the one JavaScript runtime, and the store is read once more after the key is made and before it is written. Two separate processes over one store can still race in that last step.
When a connection is made over a storage adapter that an earlier connection already used, the store is read again first. If your app cleared it in between (a sign-out), the new connection mints and stores a fresh identity; it never presents one that the next reload would not find.
Trust-on-first-use (TOFU)
Section titled “Trust-on-first-use (TOFU)”The first time a peer sees a given identity, it pins that identity’s verify key. The identity is
keyed by the coordinate’s envId + its persistent id, falling back to the per-boot instance id
when none is set. A later handshake presenting a different key for the same identity is rejected with
identity_pin_mismatch. That is what stops a third party who merely knows your id from impersonating
you: they can’t produce the pinned key’s signature.
withPersistentId is therefore a trust decision as well as a routing name. It tells the peer
“remember my key under this id, forever.”
With no persistent id, the pin is keyed by the instance id, which is new on every boot. Such a client is never refused for a changed key, and nothing pins it across boots: to the peer, each boot is a new client.
Your storage must be durable — the mistake that bites
Section titled “Your storage must be durable — the mistake that bites”The verify key lives in storage. If that store is memory- or session-backed, the keypair regenerates
on every reload while the pinned id stays the same. The first load works and every load after
it is rejected, permanently, for that identity. In a browser use createWebLocalStorageAdapter. On
React Native back it with AsyncStorage (see React Native / Expo).
Memory adapters are for tests. createWireClient / connectChannel warn at construction when they see
a persistent id paired with a known-ephemeral store.
A per-session identity is fine as long as the id is minted fresh too:
RuntimeCoordinate.env("web").withPersistentId(crypto.randomUUID()) at startup. Declare it with
ephemeralIdentity: true to acknowledge the pairing and silence the warning.
One persistent id per install, not per user
Section titled “One persistent id per install, not per user”Give each install of an app its own persistent id, minted once and kept in the same durable store as its keys. An id per user breaks the day a user signs in on a second phone: that phone has keys of its own, and the peer refuses it under the id the first phone pinned. The persistent id names the device. Who the user is belongs to your own sign-in.
Recovering from a pin mismatch
Section titled “Recovering from a pin mismatch”A pin mismatch is permanent for that identity+key pair. The keep-alive redial ladder parks on it rather than retrying a handshake that can never succeed. Two things do not recover it, and two do:
- Does not work: retrying or redialing. The same identity and key get the same rejection every time, which is why the ladder parks.
- Does not work: clearing only the client’s crypto storage. A fresh key under the same persistent id is exactly what the pin rejects.
- Works: connect under a new persistent id (a fresh identity), or remove the peer-side pin via the verify-key resolver’s storage.
A mismatch has three usual causes: a store that forgets (above); a store your app cleared while keeping the persistent id; and two connections or tabs that each minted a key on a fresh store, which a version without the guard in One identity per storage allowed. A device refused for that last reason stays refused after an upgrade: the peer still holds the other key. Recover it the same way.
A rejected handshake shows up as a rejection from connect() (or the first dispatch), so don’t
fire-and-forget that promise. The mismatch is typed, so an app can branch on it:
import { err_wire_connect } from "@nice-code/wire";
try { await client.connect();} catch (e) { if (err_wire_connect.isExact(e) && e.hasId("identity_pin_mismatch")) { // Permanent for this identity+key pair — recover under a new persistent id, // or clear the peer-side pin. Retrying the same pair never succeeds. }}On Cloudflare: persist the pins
Section titled “On Cloudflare: persist the pins”A Durable Object host keeps its identity and its trusted-peer pins in DO storage (the default in
serveWireDurableObject). A pin that lived only in memory would be lost on every hibernation wake. The next key
to show up would be trusted as a first contact, which defeats the protection, so on Cloudflare persistence isn’t optional. See
Serving a Realm.
serveWorker is the exception. Its pins are in memory by default and last as long as the Worker
isolate does, so the next isolate takes a changed key as a first contact. That suits an endpoint
whose clients mint a fresh identity for each page. For pins that hold, pass a resolver over durable
storage:
import { createStorageTofuVerifyKeyResolver } from "@nice-code/action";
serveWorker(appChannel, { identity: serverCoord, storage, verifyKeyResolver: createStorageTofuVerifyKeyResolver(storage), handlers: [appHandler],});KV is eventually consistent, so two first contacts in different locations can both be taken before either sees the other’s pin. Where that matters, serve from a Durable Object, whose storage is strongly consistent.
The resolver has two storage layouts. The default, "document", keeps every pin in one pins map
and rewrites the whole map each time a new identity connects. That is fine for a handful of peers.
With many peers, pass { layout: "per_identity" }:
createStorageTofuVerifyKeyResolver(storage, { layout: "per_identity" });Each identity then gets its own record, keyed by a SHA-256 hash of the identity. A new peer writes one small record and never touches anyone else’s pin. Two first contacts for the same identity are run one after the other inside the resolver, so they cannot both win.
The store must still be durable. If anyone on the internet can connect, authorize or cap which identities may reach first contact, because each one costs you a stored pin.
Switching an existing host from "document" to "per_identity" is safe: on each identity’s next
contact its legacy pin is honored and migrated to a per-identity record, and the legacy pins
document is left in place so rolling back is also safe. The reverse switch is not migrated —
per-identity records are invisible to the "document" layout.
What rests on this
Section titled “What rests on this”TOFU is not certificate-authority PKI. It’s strong against an outsider who never held the key, but if
first contact happens over a hostile network, the pin is of whoever answered. That matters most for a
realm, whose entire authority model, every alter rule included, rests on the avatar identity
this pin establishes. See Realm Security for the realm-layer consequences, and the
Error Reference for branching on identity_pin_mismatch and its neighbours.