ccr-relay-e2ee/1

This is the frozen binary encoding for the end-to-end channel inside opaque relay WebSocket frames. All integers are unsigned network byte order. Reject any unknown version, type, or length. WebCrypto primitives are Ed25519, X25519, HKDF-SHA-256, HMAC-SHA-256, and AES-256-GCM. The relay sees only routing metadata and the bytes below; it is not an authentication authority for application access.

#Relay admission compatibility

The outer relay WebSocket transport is separate from the encrypted channel below. The host's first JSON message advertises "caps":["admitted"] to request a binary opcode 7 acknowledgement on cid=0 after the relay accepts and saves its host-key binding. The relay sends that opcode only when the capability is present; an older host without caps remains connected when the relay is upgraded first. A host whose key is not bound and that sends no registration proof is closed with 4412 (registration required); other admission failures, including bad tokens and the auth deadline, use 4401, except a well-formed token outside its time window, which is closed with 4425 (clock skew): the sender's clock is more than two minutes ahead of the relay's, or so far behind that its four-minute token had already expired. A host registering for the first time is judged the same way: its registration proof has the same two minutes. The sender may keep retrying; a phone shows “Check this device's clock”, a host reports closeReason: "clock_skew" in GET /api/relay/status, and neither treats it as a lost pairing or registration. A host or phone older than 4425 reads it as a dropped connection and retries. A host clears its saved registration only on 4412; 4402 is a managed relay's data cap and leaves it alone. Without the admitted frame (an older relay), a host treats a socket still open after the relay's 5-second auth deadline as connected but not registered. A host connector ignores unknown relay control opcodes on cid=0 so later relay features can be added without disconnecting it. The strict unknown-type rule below still applies inside the encrypted end-to-end channel.

#Identities and handshake

The host has a persistent Ed25519 key and random 16-byte host ID. The QR pins its full 32-byte raw public key, host ID, relay origin and optional 32-byte one-use pairing secret. A device stores a nonextractable Ed25519 private key in IndexedDB. The relay pairing admission value is HKDF-SHA-256 with 32-byte pairing secret as input, 16-byte host ID as salt, UTF8(ccr-relay-pair-admit/1) as info, and 32-byte output. It lets the relay gate a pairing socket without learning the secret that the host consumes. kid is unpadded base64url of the first 16 bytes of SHA-256(raw 32-byte device public key).

Each connection uses newly generated X25519 pairs and independent random 16-byte nonces. The client sends 01 01 | client X25519 public[32] | client nonce[16]. The host sends 01 02 | host X25519 public[32] | host nonce[16] | Ed25519 signature[64].

The signature covers exactly this canonical transcript, with no JSON encoding:

UTF8("ccr-relay-e2ee/1\\0")
uint16(length of UTF8(canonical relay origin)) | UTF8(canonical relay origin)
host ID[16]
UTF8("client\\0host\\0")
client X25519 public[32] | host X25519 public[32]
client nonce[16] | host nonce[16]

Canonical relay origin is new URL(origin).origin, excluding path, query, fragment and trailing slash. The client checks the signature using the QR-pinned host key before transmitting a pairing secret or device proof. Both sides reject a low-order X25519 public point or an all-zero derived secret. They discard the ephemeral private-key reference after deriving the shared secret, and zero their local shared-secret buffer after HKDF.

HKDF salt is SHA-256(transcript). Input key material is the 32-byte X25519 shared secret. Each 32-byte output uses UTF8("ccr-relay-e2ee/1/" + label) as info, with labels client-to-host/aes-256-gcm, host-to-client/aes-256-gcm, client/finished, and host/finished. The last two outputs are HMAC keys.

The client then sends 01 03 | HMAC-SHA-256(client finished key, transcript)[32]; after checking it, the host sends 01 04 | HMAC-SHA-256(host finished key, transcript)[32]. Neither side accepts a data frame yet. The client sends an encrypted proof as its first AES-GCM frame. The plaintext is 01 05 | device name byte length[1] | raw Ed25519 public[32] | Ed25519 signature[64] | optional pairing secret[32] | UTF8 device name[0..60]. The signature covers UTF8("ccr-relay-e2ee/1/device-proof\\0") | transcript. The pairing secret travels only under AEAD, and the admission token is never used in-channel. A relay device admission carries an advisory kid; the host recomputes kid from the signed proof key and rejects a mismatch or a pairing proof on a device admission. A relay pairing admission permits only a proof containing the pairing secret; its kid is null or absent. A proof without a secret must match an enrolled, nonrevoked device. A proof with a secret atomically consumes it and records the key. If the proof's key is already enrolled, the host opens the channel as that device whatever the secret (the signature has shown it is the same phone): it adds no entry, counts no failure, announces no pairing, and still consumes a live secret. The host drops control and format characters (bidi overrides, zero-width marks, line breaks) from a device name before storing it. A name sent with a live secret names the entry, for a new phone and for an enrolled one pairing again: the owner has just made that code for this phone. Any other proof (no secret, or a secret that is not live) only replaces a placeholder name (Phone, Device) left by an older phone app; a phone that has a name keeps it. The host sends encrypted 01 06 only after proof verification. Application plaintexts can flow only after this ready message. Unexpected handshake frames fail closed.

#Short codes

ccr-short-code/1 lets a person type an 8-character code instead of scanning the QR. It resolves to the same one-use pairing payload {v:1, relay, hostId, hostKey, secret, name?}, after which the handshake above runs unchanged: the phone shows the host fingerprint, pins hostKey and sends secret only under AEAD.

Code. Eight characters of Crockford base32 (0-9, A-Z without I L O U), 40 bits from a CSPRNG. Input is upper-cased, spaces and - are dropped, O reads as 0 and I/L as 1. The first four characters are the *route*; the whole canonical code is the password.

Rendezvous. The relay serves /v1/codes/<route>/host and /v1/codes/<route>/client (WebSocket, text frames, no query). One Durable Object per route holds at most one host and one phone. A host that finds the route taken is closed with 4409 and draws a new code; a phone that finds no host gets 4404. The relay sends the host {"t":"ready"} on accept, {"t":"join","s":n}, {"t":"msg","s":n,"d":text} and {"t":"leave","s":n}; the host answers {"t":"msg","s":n,"d":text} or {"t":"end","s":n}. Phone frames are the bare d strings. Limits: 2048 characters per message, four messages per phone, a phone for 30 seconds, a host for 11 minutes, five phones per client address (IPv6 by /64) and 30 per host socket, then 4429. Upgrades pass the same per-IP limiters as other sockets, under separate keys. A deployment without the CODES binding answers 404 and hosts fall back to the QR link.

Exchange. CPace (draft-irtf-cfrg-cpace) with X25519 and SHA-512, the phone as initiator: PRS = the canonical code, CI = lv_cat("ccr-short-code/1", relay origin, route), sid = 16 random bytes from the phone, ADa = "phone", ADb = "host", and the initiator/responder transcript. Either side aborts on a low-order share.

  1. Phone: {"v":1,"t":"hello","sid":b64url,"share":b64url(Ya)}
  2. Host: {"v":1,"t":"reply","share":b64url(Yb)}
  3. Phone: {"v":1,"t":"confirm","tag":b64url(HMAC-SHA-256(Kc, "confirm"))}
  4. Host, only if the tag verifies: {"v":1,"t":"payload","iv":b64url[12],"data":b64url(AES-256-GCM(Ks, iv, payload JSON, AAD "ccr-short-code/1\0payload"))}

Kc and Ks are HMAC-SHA-256(ISK, "ccr-short-code/1/phone-confirm") and HMAC-SHA-256(ISK, "ccr-short-code/1/host-to-phone/aes-256-gcm"). A payload that decrypts also proves the host held the code. Unknown versions, types or orders fail closed. The host runs one session per code: a join while one is live, while codes are paused, or for a code already revoked gets end with no reply. It counts each attempt at join, refunds the one that reaches step 4, and sends end after any other; ten counted attempts in ten minutes revoke every open code and pause new ones for ten minutes. The route is public to the relay (20 bits), so a hostile relay's chance is bounded by online guesses at the other 20 bits: at most ten per host per window. Known limits, tracked for later: a route with no host answers 4404 at once, so routes can be enumerated (at the edge's 60 client upgrades per minute per address), and /host takes no host proof, so a route can be squatted. Both cost availability only; a squatted route makes the host draw another code. A code closes once it delivers its payload, when its pairing secret is used or expires, or when the host stops. Payloads stay in host memory; a restart drops open codes.

Over direct access no exchange is needed: POST /api/pair {"code"} accepts the short code as well as the 22-character link code, refuses with 429 after five wrong short codes per client address in ten minutes, and drops and pauses short codes after ten wrong ones across the server. Using either form of a pairing uses both.

#Application frame

01 07 | uint64 sequence | AES-256-GCM ciphertext and 16-byte tag. The 96-bit IV is four zero bytes followed by the sequence. AAD is UTF8("ccr-relay-e2ee/1\\0") | UTF8(direction) where direction is client-to-host or host-to-client. Directional keys are distinct. Sequence starts at zero separately per direction; encryption refuses at 2^64 - 1024 and requires a fresh handshake. Plaintext is at most 1,048,576 bytes. The receiver authenticates before advancing its replay state. It accepts bounded reordering within the latest 64 sequence values, rejecting duplicates and older frames. The encrypted API layer must implement durable action IDs for mutation retry after reconnect; frame replay protection alone does not provide exactly-once execution.

#Artifact files

ccr-artifact/1 seals a file (or a deck's bundle of files) for a short stay in a managed relay's object storage. The host draws a fresh 32-byte AES-256-GCM key per upload. The plaintext is split into 1,048,576-byte chunks; the last chunk may be shorter, and an empty file is one empty chunk. Chunk i is sealed with IV 00 00 00 00 | uint64 i (safe because the key is never reused) and AAD UTF8("ccr-artifact/1\0") | uint64 i | uint8 last | uint64 total plaintext size, where last is 1 only for the final chunk. The object is the concatenated ciphertexts, each with its 16-byte tag, so its size is the plaintext size plus 16 bytes per chunk. The hash is base64url SHA-256 over UTF8("ccr-artifact/1\0hash") followed by each chunk's 32-byte plaintext SHA-256, in order; WebCrypto has no streaming digest, and this keeps 32 bytes per MiB. The opener knows the exact length of every chunk from the size, decrypts each as it arrives, and fails closed on a bad tag, an extra or missing byte, or a hash mismatch.

Inside the encrypted channel, the phone sends GET /api/artifacts/:id/relay (a GET, so it is never written to the action journal). For a bundle up to 2 MiB of plaintext, the host answers {status:"inline",size,files,data}, where data is base64url of the bundle and files lists {path,offset,size,type}. The existing response chunk protocol carries this JSON in 120,000-byte parts under the frame and rate limits. Larger bundles use storage: the host answers {status:"uploading",sent,total} while it seals and uploads, waiting up to five seconds on the first request, and then {status:"ready",url,urlExpiresAt,key,size,hash,files}. key is the base64url file key; files lists the entry first, then a slides deck's own-folder files, sorted, without hidden files or node_modules, at most 1,000 files and 256 MiB of plaintext together (the phone holds the file in memory; larger files get 413 and open over direct access). The phone polls about once a second until it is ready, then fetches url; on a 400, 403 or 404 from storage (for example an expired URL) it asks once more for a fresh one. The host reuses an upload of the same unchanged files until 30 minutes before storage deletes it. If storage is unavailable, bundles above 2 MiB show a quiet direct-access note with their name and size.

#Host storage and recovery

relay-host-identity.json and relay-devices.json live in the host data directory with mode 0600. The former holds PKCS#8 private key material and host ID; keep backups encrypted and under the owner's control. No cloud escrow exists. Losing the host key means a new host identity and re-pairing every device. Losing a device means revoking its key on the host and pairing a replacement. Pairing secrets are 32 random bytes, stored as SHA-256 hashes, expire after ten minutes and are consumed once. Five failed pairing attempts per host in ten minutes also block legitimate pairing until that window ends; a proof from an already enrolled key is never a failed attempt and is not blocked. The relay registry is constructed with the raw 16-byte host ID. It stores both SHA-256(pairing secret) and base64url SHA-256(pairing admission value), and exposes unexpired {hash, exp} admission entries. It schedules expiry cleanup and emits changes on pairing creation, consumption, expiry, device enrollment and revocation so relay allowlists refresh; revocation also closes the live device channel. The transport must enforce a handshake deadline and pass the relay's advisory kid to the host handshake, which compares it with the signed proof key and closes a mismatch. Existing bearer-token devices remain for direct HTTP access.

Relay mode requires native Ed25519 and X25519: Chrome 137+, Firefox 130+, Safari 18.4+ subject to runtime feature detection. Unsupported browsers should use direct, LAN or Tailscale access. A compromised static app origin can still access browser device keys and plaintext; it is part of the trust boundary.

#Encrypted application messages

After device proof, UTF-8 JSON inside each sealed frame carries {t:"req",id,method,path,body?,actionId?} and {t:"res",id,status,body}. Paths are relative /api/ paths. Mutations require a random action ID, scoped to the verified device. The host writes a pending action record before dispatching to the same API router as direct HTTP, then writes the response before transmitting it. Repeated IDs with the same request hash return that response; different hashes return 409. {t:"outcome",actionId} lets a reconnecting phone check a lost response. A mutation still running after 30 seconds returns an uncertain 409 while its journal entry stays pending; when the route finishes, the host records its actual result for a later outcome lookup. Canceling a phone request removes its pending reply; if a mutation may have been sent, the phone retains its action ID for outcome lookup on reconnect and does not automatically repeat the canceled action. A pending record left by a host crash remains uncertain and is never executed again automatically. Records expire after 24 hours. The host retains up to 256 full outcomes, evicting oldest completed ones to keep mutations available; it retains evicted IDs for 24 hours so a late retry reports an uncertain outcome instead of rerunning. Pending records are retained and limited to 32 per device.

The host answers a phone's requests side by side, not in turn: up to six GETs per channel run at once, and mutations run one after another in the order the phone sent them, without waiting for GETs. A slow route (/api/setup checks the agents, creating a task clones) never holds the page's polls behind it. A 200 GET reply carries etag, the hex SHA-256 of its JSON body. A GET may carry ifNone, the etag of the reply the phone already holds for that path; when the body is unchanged the host answers {t:"res",id,status:200,same:true,etag} with no body, so a repeated 2.5-second poll of a large task list costs a few bytes. A reply over 2 MiB is not kept, which is one reason the page asks for the task list in parts (GET /api/sessions?window=50, with the older tasks' stubs from ?rest=50 once and afterwards only their versions and the changed ones; HTTP API): the whole list of a host with hundreds of tasks was sent in full on every poll. The phone keeps up to 24 such replies in memory, none over 2 MiB, and asks again without ifNone if it no longer has the one named. Older hosts ignore ifNone; older phones never send it.

Everything the host sends one phone (replies, their parts, events) shares one budget of 1.25 MiB a second, since the relay closes a phone (4429) past 2 MiB in any second, both ways together. A request that reaches its limit with nothing at all heard from the host since it was sent abandons the socket and reconnects at once (an iOS app back from the background can hold a socket that died without a close); the reconnect resends GETs.

A hidden page closes its channel with 1000, unless a file is going up, and a visible page, a pageshow or the network coming back opens a fresh one at once. iOS suspends a backgrounded app without closing its sockets, and the relay counts each open one against the account's connections until it notices, so reopening the app could otherwise find no room (4429). Requests made meanwhile wait and go out on the new channel; one still waiting after 60 seconds fails with the relay's last close reason.

The relay's copy of the page names its build (<meta name="ccr-app-build">, filled by prepare-assets.mjs with the same value as relay-build.json's cache). The page reads relay-build.json every minute and when it comes back to the front; when the relay has moved on, it reloads itself if it is not connected yet (and nothing is typed in the connect forms) or is coming back to the front, and otherwise shows the update banner. Drafts are kept across the reload.

A launch with a saved computer (or, over direct access, a saved sign-in) connects by asking for the task list and the workspaces. When that fails, the page tries again after 1, 2, 4, 8 and then every 15 seconds, saying why and offering Retry now; the network coming back or the app returning to the front tries at once. After two minutes it stops with the last reason and a Retry button. A refused sign-in, a phone removed from its computer (4403) and a browser without the relay's cryptography are not retried.

A request's time limit starts when it is sent on an open channel, not while the phone reconnects, and starts again with each part of a reply that arrives in parts (res_chunk, below), so a large reply on a slow network is not a timeout while it keeps arriving; time without a channel has its own 60-second limit, after which the page says it is reconnecting. A reconnect resends unanswered GETs on a fresh limit. A GET that reaches its limit is resent once under a new ID, so two replies never mix their parts, before it fails as a timeout; a mutation is never resent on a timeout, and its action ID is kept for an outcome lookup.

Responses too large for one application frame are sent as ordered {t:"res_chunk",id,part,total,data} messages. data is base64url of up to 120,000 bytes of the complete {t:"res",id,status,body} UTF-8 JSON. The client resolves the request only after reassembling and validating every part. The channel preserves their order, so these parts need no acknowledgments. A reply above 8 MiB returns 413.

#Attachments

A file attached in the composer (or with a question's answer) goes from the phone in pieces inside the channel; a relay request body is JSON and is never taken as a file. {t:"up",id,task,name,size,sha256} starts or resumes one: id is the phone's random 16-64 character ID, sha256 hex of the whole file. The host keys the upload by the verified device and id, checks it as a direct upload with size as its length (per-file limit, the task's unsent cap with the whole size counted from the start, the free-disk floor, a running task and a new enough runner) and answers {t:"up_at",id,offset} with the bytes it holds. {t:"up_chunk",id,offset,data} carries base64url of at most 98,304 bytes at offset; the host appends it and answers up_at with the new offset. A piece it already has is answered with the current offset. A piece past it (one before it was lost or reordered) is not written; the host answers {t:"up_at",id,offset,gap:true} with the offset it holds, and the phone sends again from there, once per gap, dropping pieces it had read for later offsets. More bytes than size end the upload with a 400. Once size bytes are in, the host checks the hash, sniffs the type and scans as a direct upload, and answers {t:"up_done",id,status,body} with what POST /api/sessions/:id/attachments answers (201 with the attachment, or the error). Refusals at up also come as up_done. {t:"up_cancel",id} drops it.

The phone keeps at most 288 KiB unacknowledged per upload and at most 1.25 MiB a second across uploads, under the relay's 2 MiB a second per phone. On reconnect it sends up again for each unfinished upload and goes on from the offset in the answer; the host keeps a partial upload for ten minutes after its last message and a finished one's answer for ten minutes too, and a host restart drops partial uploads (the phone's up then starts afresh). A device has at most 20 open uploads. The attachment ID in the answer goes out with a message (POST /api/sessions/:id/messages), as over direct access. Attachments shown in the feed have no download route, direct or relayed: the feed shows each file's name, size and scan result, and the agent reads it in its workspace.

{t:"sub",id,stream:"session"|"room",target,from} starts at an inclusive log offset. The host sends ordered {t:"ev",sub,offset,event} frames with a window of at most 64 unacknowledged events or 512 KiB. {t:"ack",id,offset} cumulatively acknowledges all sent events through that offset. An event too large for one relay frame is sent as ordered {t:"ev_chunk",sub,offset,part,total,data} messages, where data is base64url of a slice of the event's UTF-8 JSON. The client acknowledges each part with {t:"ack",id,offset,part} and applies the event only after assembling the final part. {t:"unsub",id} ends it. The client applies events in offset order. On reconnect, it subscribes from its last applied offset plus one; the append-only host log is authoritative.