Skip to content
pi-c Remote control, stage 2: the relay protocol
Login

Remote control, stage 2: the relay protocol

Status: accepted; landed. Tether (ticket ed086ebc04) is remote control of a running pic from a phone: a phone is one more sender and observer of the journal, through ssh (stage 1, pic attach and pic send, in grapevine and the inbox) or through a relay that sees only ciphertext (this note). Done: ssh; pairing, pic remote and the phone page at remote.zeitforge.app (pic-relay); the reply streamed as it is written; Web Push when a request ends; /rc in one step with a short link and QR code per conversation; the interface following a phone's request; a login agent (pic remote install) so pic remote comes back after a restart. The invariants are in the relay side, the user's view in remote control. Deferred: durable questions (an approval answered from the phone), and with them a "needs input" notification, which waits for that work; images and other commands from the phone; opening the relay beyond invitations (open question 1).

Tier: bundled (pic remote, pairing in /rc, push; seams: the inbox and the read view), external (the relay and the phone page, repository pic-relay). Clock: pi, os. Record: a pic_inbox row or a keyed admission per command, the sender remote:DEVICE on what it caused; device and key rows in ~/.pic/pic.sqlite. Default: off; nothing dials out until pic remote is run.

This note is the wire contract between two implementations written in parallel: pic (C11, BearSSL) and pic-relay (TypeScript: a Cloudflare Worker with one Durable Object per mailbox, and the phone page, on WebCrypto). Everything either side must agree on is here and in the test vectors (section 8). Where this note says "must", a vector or a test in section 10 checks it.

The short form: a phone is one more sender and one more observer of the journal. pic remote is a process beside the others on the shared store. It dials out to a relay that forwards ciphertext, speaks a Noise session to each paired phone, turns each command into a journal row before anything acts on it, and rebuilds events from committed rows as pic attach does. It holds no lease and no state the journal and the user database do not already hold.

Durable questions (an approval answered from the phone) are a later ticket and are not here.

Notation

1. Roles and keys

Party Runs Trusted with
pic pic remote, and /rc while pairing everything: it is the machine being controlled
phone the page, in a browser or installed to the Home Screen everything a local user of pic has (section 4)
relay the Worker and its Durable Objects availability and routing only; sees ciphertext and the metadata in section 3
page host the same Worker, serving the page's files the integrity of the page's code (section 9)
push service Apple, Google or Mozilla delivering an encrypted notification; sees its size and time

Keys

Key Type Made Kept
pic static P-256 ECDH first /rc picu_remote_key row static: public in the clear, private sealed
pic VAPID P-256 ECDSA first /rc row vapid, the same way
mailbox owner token 32 random bytes first /rc row mailbox, sealed; its public column is the mailbox id
phone static P-256 ECDH, one per pairing at pairing IndexedDB, as a CryptoKey made with extractable: false
channel token 32 random bytes, one per pairing by the phone at pairing IndexedDB; pic keeps only the channel id
pairing secret 32 random bytes per /rc offer memory of the /rc process; shown once in the QR code
ephemerals, session keys per handshake memory only, on both sides

Three keys, three uses: the static key only does ECDH inside Noise, the VAPID key only signs VAPID tokens, and the owner token is only ever shown to the relay. No key is used for two algorithms.

pic's storage. Two tables in ~/.pic/pic.sqlite:

The device row is sealed although it holds no private key: a row that does not open under the master key is not a device, so adding a phone takes the passphrase, not just write access to the file. The relay's address is the setting remote.relay.

The phone's storage. One IndexedDB database, pic-rc, with one object per pairing: the static CryptoKeyPair ({name: "ECDH", namedCurve: "P-256"}, extractable: false, usage deriveBits), pic's static public key, the mailbox id, the channel token, the device id, pic's VAPID public key and pic's name. CryptoKey objects are stored by structured clone; the private key's bytes never exist in script. A second store, outbox, holds commands not yet answered (section 4). Conversation content and cursors are held in memory only and are gone when the page closes.

Unpairing

A revoked phone still holds a channel token and a static key that no longer open anything: pic refuses a handshake whose static key is not in the table, and the relay refuses a deleted channel.

2. Pairing

Primitives

One suite, in pic from BearSSL and in the page from WebCrypto, with no other cryptographic code on either side:

Function Choice BearSSL WebCrypto
DH P-256 br_ec_p256_m31 mulgen and mul generateKey, deriveBits with ECDH
cipher AES-256-GCM, Noise AESGCM (12.4) br_gcm over br_aes_ct_ctr (or x86ni), br_ghash_ctmul32 AES-GCM, 96-bit iv, 128-bit tag
hash SHA-256, Noise SHA256 (12.5) br_sha256 digest
HKDF Noise's (4.3) br_hmac sign with HMAC

Noise defines no P-256 DH function, so this note does, in the form section 4.1 asks for:

The same suite with the same deviations is in deployed use: the hybrid transport of CTAP 2.2 (passkeys across devices) is Noise_KNpsk0_P256_AESGCM_SHA256 and Noise_NKpsk0_P256_AESGCM_SHA256 started from a QR code.

Noise's HKDF(ck, ikm, n) is computed as three HMAC calls, as section 4.3 writes it, on both sides. The page does not use WebCrypto's HKDF algorithm, because Split() passes a zero-length key and importing one fails in some browsers; with HMAC the key is always the 32-byte ck.

Patterns

Use Protocol name (section 8) Pattern
pairing Noise_IKpsk1_P256_AESGCM_SHA256 <- s ... -> e, es, s, ss, psk / <- e, ee, se
session Noise_IK_P256_AESGCM_SHA256 <- s ... -> e, es, s, ss / <- e, ee, se

IK (7.5) is the pattern for an initiator that already knows the responder's static key, which the QR code gives the phone. It takes one message each way, it carries the phone's static key encrypted to pic's, so pic learns which device is calling from the handshake itself and several phones can share one code path, and it is the pattern WireGuard uses for the same shape of problem. IKpsk1 (9.4) is the same pattern with the one-time pairing secret mixed in at the end of the first message, so the first message's payload already proves the sender scanned the code. The names are 31 and 27 bytes long, so h starts as the name padded with zeros to 32 bytes (5.2). In the psk protocol each e token also calls MixKey(e.public_key) (9.2).

Rejected: XX and XXpsk3 spend a third message to transmit a static key the phone already has and would still need the comparison IK does for free; KK needs pic to know which device is calling before it can read the first message, which means a cleartext device name; NK gives the phone no key to be recognized by later.

The prologue (section 6) of both handshakes is 41 bytes:

"pic-rc/1" || 0x00 || mailbox id (16) || channel id (16)

with the pairing channel's id when pairing and the device's channel id in a session. A handshake replayed onto another mailbox or channel, or between protocol versions, fails.

The offer and the QR code

/rc unlocks the credential store (asking for the passphrase if it is locked), makes the keys and the mailbox on first use, and then for each offer:

ps          = 32 random bytes                      the pairing secret
psk         = HMAC(ps, "pic-rc/1 pair psk")        Noise's psk
pair_token  = HMAC(ps, "pic-rc/1 pair token")      shown to the relay
P           = trunc16(SHA256("pic-rc/1 channel" || pair_token))

It registers channel P as a pairing channel with a lifetime of 600 seconds, opens that channel's stream, and shows a QR code of

https://RELAY/#p1.<b64u(0x01 || mailbox id (16) || pic static public (65) || ps (32) || expires (8))>

expires is Unix seconds. The offer is 122 bytes and the address about 200 characters, which is a version 9 QR code. Everything secret is in the fragment, which a browser does not send to a server. The relay is the address's own origin. The relay learns pair_token, from which psk cannot be computed.

An offer admits one device. It ends when a device is paired or refused, at expires, when /rc is closed, or after 5 first messages that fail to verify.

The handshake

The phone opens the address. The page reads the fragment, removes it from the address bar (history.replaceState) before anything else runs, refuses an expired offer, and makes: a static key pair, a channel token D (32 random bytes) with its channel id C = trunc16(SHA256("pic-rc/1 channel" || D)), and a session id (8 random bytes).

  1. Phone to pic, on channel P with pair_token: message 1 with the payload {"v":1,"name":NAME,"channel":b64u(C)}. NAME is a label the phone picks ("iPhone, Safari"), at most 64 bytes.
  2. pic reads it. A message that does not verify counts against the offer and is otherwise ignored. One that does proves its sender knew ps and holds the static key it sent. pic answers with message 2 and the payload {"v":1,"device":b64u(id),"name":HOST,"vapid":b64u(VAPID public)}.
  3. Both sides now hold the handshake hash h (11.2) and the two transport keys. Each computes

    sas = decimal(uint32(HMAC(h, "pic-rc/1 sas")[0..4]) mod 1000000), 6 digits, zero-padded

  4. The phone shows the code and sends the transport message {"type":"pair_ready"}.

  5. On pair_ready, the terminal shows the device's name and the code and asks: "Pair NAME? It should show 333 054. [y/N]". Nothing has been written yet.

  6. On yes, pic commits the device row, registers channel C as a device channel, sends {"type":"paired"} and deletes channel P. On no, or at expiry, it sends {"type":"error","payload":{"code":"pair_refused"}} and deletes P.

  7. On paired, the phone stores the pairing and opens its first session on C.

A crash of /rc between the row and paired leaves a device that never connects and shows as "never seen" in the list; the phone reports that pairing failed. The channel registration is repeated by the next pic remote (section 7).

What stops a relay in the middle

The relay carries every handshake byte and never sees the fragment. To answer the phone as pic it needs pic's static private key, since the phone encrypts to the public key it read from the screen (es, ss). To call pic as a phone it needs psk, which is derived from ps. It has neither, so it can only drop or delay messages.

The code on both screens covers the case the secret does not: a QR code that leaked (a photograph, a shared screen). Whoever uses it first holds the offer, and the terminal then shows a name and a code that the owner's own phone is not showing; the owner's phone shows a failure. The prompt defaults to no.

3. Transport over the relay

Mailboxes and channels

A mailbox belongs to one pic install. A channel is one phone's lane in it, or one pairing offer's. Both are named by a hash of a random token, so presenting the token proves the right to use the name and the relay stores no secrets:

mailbox id  M = trunc16(SHA256("pic-rc/1 mailbox" || owner token))
channel id  C = trunc16(SHA256("pic-rc/1 channel" || channel token))

pic creates the mailbox and registers every channel in it (section 6); a phone can use only a channel pic registered. Tokens travel only in the Authorization: Bearer b64u(token) header, over TLS, never in an address.

Each channel has two one-way lanes. A lane is an ordered pipe with a short memory, not a queue for an absent reader:

Lane Writer Reader
up the phone: POST .../c/C/up pic: one stream for all its device channels
down pic: POST .../c/C/down the phone: GET .../c/C/down

Both directions are server-sent events down and POST up, on both sides. pic reads its stream with pic_http_get and the framer in src/sse.c. The page reads its stream with fetch and a ReadableStream, not EventSource, which cannot send the Authorization header.

Records

The unit the relay forwards is a record, opaque to it:

First byte Record Layout after the first byte
0x01 handshake message 1 session id (8), Noise message
0x02 handshake message 2 session id (8), Noise message
0x03 transport session id (8), counter n (8), ciphertext
0x04 reset session id (8)

The session id is the initiator's 8 random bytes; it only tells sessions on one channel apart. The channel's kind decides which protocol a message 1 starts. A record is at most 16417 bytes.

A POST body is application/octet-stream: records one after another, each behind its length as 2 bytes; at most 32 records and 256 KiB. A stream event is

id: N
event: frame
data: b64u(record)            a channel's stream
data: b64u(C).b64u(record)    pic's mailbox stream

Transport messages

After message 2, Split() (5.2) gives two cipher states: the first encrypts up, the second down. A transport record carries its nonce, as section 11.4 provides for transports that can lose messages:

ciphertext = ENCRYPT(k, n, zerolen, plaintext)      nonce = 0x00000000 || n (8 bytes), section 12.4

Rules, each side for the lane it writes:

Rules for the lane it reads:

The plaintext is one flag byte and up to 16383 bytes of an envelope message: 0x00 when more of the message follows in the next record, 0x01 on its last record. A message's records are consecutive. A gap inside a message discards the part received. A message is at most 4 MiB.

Sessions

  1. The phone opens its stream and posts message 1 with the payload {"v":1}.
  2. pic reads it and looks up the static key it carried. The key must be a device in the table, and that device's channel must be the channel the record came on; otherwise the record is dropped without an answer. pic answers with message 2, payload {"v":1}, and holds the session as unconfirmed.
  3. The phone sends its first transport message (a sessions or sync, section 4). When it verifies, the session is confirmed.

pic sends nothing but message 2 on an unconfirmed session and acts on nothing from it. Message 1 of IK can be replayed by anyone who recorded it (7.7), and a replay gets exactly that: a message 2 it cannot use. Unconfirmed sessions are dropped after 30 seconds, and a channel has at most two. A confirmed session replaces the device's earlier ones.

v is the highest version the sender speaks; this note defines 1. An incompatible change gets a new prologue label, so the two versions cannot complete a handshake with each other.

A session outlives its streams: when a stream breaks, both sides reconnect and continue with the same keys. pic drops a session that has been silent for 10 minutes. The page sends {"type":"ping"} every 60 seconds while it is visible and pic answers {"type":"pong"}. A transport record for a session pic does not have is answered with a reset record, which is not authenticated and so may cause one thing only: the phone starts a new handshake, at most once every 5 seconds.

What the relay sees

For every record: the mailbox id, the channel id, the direction, the length, the time, and the record's cleartext head (its type, the session id and the counter). For every connection: the address, the TLS and HTTP details any server sees, the bearer token, and so which mailbox or channel is connected and when. From registration: how many devices a mailbox has, and when an offer was open.

It does not see: any key but the tokens, pic's or the phone's static public key, the device's name, which conversation or workspace is in use, any command, event or text, or anything about push (pic talks to the push service itself).

Lengths are not padded in version 1. The size and rhythm of records shows when a reply is streaming and roughly how long it is.

Reconnecting

4. The envelope

An envelope message is one JSON object with up to five members:

Member Meaning
type what this is, from the tables below
session a conversation: W/C, the workspace's id (picu_workspace.journal) and the conversation's id; +W for a conversation not yet made
seq a position in that workspace's journal: pic_entry.seq
key a command's idempotency key: 16 to 43 characters of [A-Za-z0-9_-], 16 random bytes as b64u by default
payload a Pi RPC command, response or event, unchanged, or the type's own object

Pi's commands and events are carried as they are (RPC commands, events); the envelope adds addressing and nothing else. Members a receiver does not know are ignored; a type it does not know is answered with {"type":"error","payload":{"code":"unknown_type"}}.

Up: phone to pic

type Members Meaning
sessions payload optional send the list of conversations, and again when it changes; with {"workspace":W}, once, every conversation of that workspace
sync session, seq, key follow this conversation from after seq; -1: from the start of its latest request. key names this follow (below)
fetch session, payload {"after":A,"to":B}: the events in (A, B]; {"before":X,"limit":N}: the N entries before X
command session, key, payload a Pi RPC command
presence payload {"visible":true} or false
push payload {"subscription":{...},"notify":"all"\|"remote"} or {"subscription":null} (section 5)
ping, unpair, pair_ready

Down: pic to phone

type Members Meaning
sessions payload {"sessions":[{"session","name","workspace","lastMs","running","seq"}],"workspaces":[{"id","workspace"}],"unavailable":[{"workspace","reason"}]}; to a sessions with a workspace, {"workspace":W,"sessions":[...]}
event session, seq, key, origin, payload a Pi event rebuilt from committed rows
sync session, seq, key, payload a mark: the phone has everything through seq; {"running":BOOL,"earlier":SEQ}, earlier absent when the follow shows the first request
fetch session, seq, payload the end of a fetch: {"done":true}
live session, seq, payload the reply being streamed, as one value (below)
ack key, session for +W, payload the command is committed: {"state":"pending"}
response key, session for +W, payload the Pi RPC response line
error key if it answers a command, payload {"code","message"}
pong, paired, unpaired, bye

Following and catching up

A phone is a replica of one conversation at a time, and its cursor is the seq of the last mark it received.

What is rebuilt is what pic attach rebuilds today (the inbox): agent_start, message_start and message_end, tool_execution_start and tool_execution_end, agent_end. Anything pic attach learns to rebuild, the phone gets with no change here.

The reply as it streams

Streamed text is not journaled. From the landing that adds it (section 10), the pic running a request publishes its message_update lines as grapevine's stage 3 describes, and pic remote folds them into one value per conversation, in memory: the partial reply so far.

{"type":"live","session":S,"seq":N,"payload":{"rev":R,"offset":K,"text":T}}

seq is the last committed entry the text comes after, rev goes up with every value sent, and text is the reply's text from character K on (pic keeps the last 8 KiB). The phone keeps the value with the highest rev and discards it when an event with a greater seq arrives. A value replaces the one before; it is never appended to. pic sends at most one every 250 ms per phone and never queues one behind another: when a post finishes it sends the newest value or nothing. A lost live message is never repaired. It promises nothing, as in grapevine.

The page also refuses a value whose seq is behind an event it has already applied, drops the value when a mark says nothing is running, and forgets it, with the rev it had reached, when a new session starts (a restarted pic remote counts rev from the start again). It shows the value after the committed events, as one item, with a leading ellipsis when offset is not 0; the committed message that follows replaces it, so the text is never shown twice.

Commands, keys and exactly once

Every command that changes anything is a committed journal row before pic remote answers it:

So a command that was acknowledged is delivered once or reported as not delivered, whatever the network, the relay, pic remote or the phone did in between: the promise of durability, unchanged. Expiry is the inbox's: 10 minutes for a steer or an abort, a day for a follow-up.

Which commands, and what "the same as local" means

Commands How From landing
get_state, get_messages, get_entries, get_tree, get_session_stats, get_last_assistant_text, get_fork_messages, get_commands, get_available_models, get_available_thinking_levels answered from the journal through the narrow open; no row 1: the first two; 2: get_session_stats and the two get_available_ lists; later: the rest
steer, follow_up, abort the inbox 1
prompt keyed admission, or the inbox while a request runs 1; with images, 4
new_session then prompt prompt with session +W; the response names the conversation 2
set_model, set_thinking_level held by pic remote for the conversation's next request, as pic --mode rpc holds its own; that request records it 2
set_session_name the conversation's name, written as pic --mode rpc writes it 2
compact pic compact --now in a process of its own; refused while a request runs 2
clear_queue, cycle_model, cycle_thinking_level, set_steering_mode, set_follow_up_mode, set_auto_compaction, set_auto_retry, abort_retry, bash, abort_bash, fork, clone, rewind the inbox, each added there as grapevine adds commands later
switch_session not carried: the envelope's session selects the conversation
export_html, extension_ui_response, login, logout, get_auth_status not carried; answered not_available

A paired phone has the permissions of the person at the terminal. Exactly:

  1. There are no roles, no read-only devices and no per-device list of commands or conversations. A paired phone sees every conversation of every workspace this user's pic knows, and may send any carried command to any of them.
  2. A prompt from the phone starts a request whose tools run as the user, in that conversation's workspace, with no approval step that a local prompt would not have. Through bash, in a tool or as the command, that is a shell as the user: a paired phone can read and change anything the user can, including ~/.pic.
  3. Its text is the user's own. It is not framed as a peer's message, and the limits grapevine puts on peers (hops, wakes, no waking an idle conversation) do not apply to it.
  4. Hooks run as they do locally and may refuse. They see origin remote:DEVICE, so a policy stricter than this note's is a hook, not a setting here.
  5. It is recorded: the sender is on the inbox row or the request, so the journal says which device asked for what.
  6. What it cannot do is what is not carried: sign in or out of a provider, pair or unpair another device, change settings files, or take a conversation's lease.

5. Web Push

A notification is sent by pic remote, straight to the phone's push service, when a request ends in a conversation the phone could see. The relay has no part in it and learns nothing of it.

Subscribing

The page subscribes with pushManager.subscribe({userVisibleOnly: true, applicationServerKey}), the key being pic's VAPID public key from pairing, and sends the result up in push: the endpoint, and keys.p256dh (65 bytes) and keys.auth (16 bytes) as b64u. pic checks the endpoint (https, port 443, a host name, not an address) and seals it into the device's row. At the start of every session the page compares pushManager.getSubscription() with what it last sent and sends push again when they differ; pushsubscriptionchange is not relied on.

notify is this device's choice, made on the phone: all (the default when absent), every request that ends, or remote, only those a phone started or steered. pic seals it into the device's row with the subscription and sends to a device only what both its notify and the setting remote.notify allow. {"subscription":null} turns the device's notifications off.

The page keeps one service worker registration for each paired computer, at scope /push/DEVICE/ (the pairing's device id), because a subscription belongs to one VAPID key and each computer has its own. The registration's scope also tells the service worker which computer a push came from, so the plaintext carries nothing about it. The browser decrypts the push (RFC

  1. with keys it made for the subscription and hands the service worker the plaintext: no page or worker code decrypts, which is why vector 5 is checked by decrypting as a browser would. The page asks for permission only from a tap, and on iOS and iPadOS offers notifications only in the installed page. It sends presence at the start of every session as well as when it is hidden or shown.

A subscription ends when the push service says so: a 404 or 410 (RFC 8030 section 7.3) removes it from the row, as do three refusals in a row with 400 or 403. Unpairing removes it with the row. A new VAPID key (after a reset) invalidates every subscription, which is why reset unpairs everything.

On iOS and iPadOS, push works only from 16.4, only for a page added to the Home Screen (a manifest with "display":"standalone"), and only after permission was asked for from a tap inside that installed page. The installed page has storage of its own, apart from Safari's, so a pairing made in a Safari tab is not there: the phone pairs inside the installed page. The camera opens a scanned address in Safari, so on iOS the Safari page offers "Copy pairing link" and the installed page offers "Paste"; the offer's ten minutes cover it. Every push must show a notification, so pic sends none it means to be silent. Safari also clears the storage of a site not on the Home Screen after seven days without a visit, which unpairs a phone that only used a tab.

The request

One POST to the endpoint, with pic_http_post:

TTL: 3600
Urgency: normal
Topic: b64u(trunc16(HMAC(auth, "pic-rc/1 topic" || 0x00 || session)))
Content-Encoding: aes128gcm
Authorization: vapid t=JWT, k=b64u(VAPID public)

Topic (RFC 8030 section 5.4) lets a newer notification for a conversation replace an undelivered older one, and tells the push service nothing about which conversation it is.

VAPID (RFC 8292). The token is a JWT (RFC 7519) signed with ES256 (RFC 7518 section 3.4): the header is exactly {"typ":"JWT","alg":"ES256"}, the claims are aud (the endpoint's origin), exp (12 hours ahead, as RFC 8292 section 2 allows up to 24) and sub (the relay's origin, an https: address; never a mail address). The signature is the 64 bytes r || s, from br_ecdsa_i31_sign_raw, which derives its nonce by RFC 6979 and so needs no randomness and gives the same token for the same input.

Encryption (RFC 8291, with the aes128gcm coding of RFC 8188). For each push pic makes a new P-256 key pair and a 16-byte salt, and computes, in RFC 8291 section 3.4's names:

ecdh_secret = DH(as_private, ua_public)
IKM   = HMAC(HMAC(auth_secret, ecdh_secret), "WebPush: info" || 0x00 || ua_public || as_public || 0x01)
PRK   = HMAC(salt, IKM)
CEK   = HMAC(PRK, "Content-Encoding: aes128gcm" || 0x00 || 0x01)[0..16]
NONCE = HMAC(PRK, "Content-Encoding: nonce" || 0x00 || 0x01)[0..12]
body  = salt (16) || 0x00001000 || 0x41 || as_public (65) || AES-128-GCM(CEK, NONCE, plaintext || 0x02)

One record, no padding beyond the delimiter. The plaintext is at most 3993 bytes; pic's is far smaller.

One line

The plaintext is {"v":1,"title":T,"body":B,"session":S,"seq":N}.

The push service cannot read it. The phone's lock screen shows it, which is the point.

When

For each request that pic remote sees end while it is following (it never sends for one that ended before it started, so a restart repeats nothing), and for each device with a subscription, unless that device has a confirmed session whose last presence was visible. At most one per conversation every 30 seconds. A push is sent once and never retried: it is a hint, and the page catches up from the journal whatever happened to it. The setting remote.notify is all (the default), remote (only requests a phone started or steered) or off.

The page's service worker shows the notification with tag set to the device id and the conversation, and a tap opens the page at that conversation on that computer (/#s=SESSION&c=DEVICE, or a message to a page already open), where a normal session and sync begin.

6. The relay

One Worker, in the repository pic-relay, on the owner's Cloudflare account. It serves the page's files and the API below. Each mailbox is one Durable Object, addressed by the mailbox id.

Endpoints

Ids in paths are b64u. "Owner" means the bearer token hashes to the mailbox id; "channel" means it hashes to the channel id and the channel is registered in the mailbox. Both are checked on every request.

Request Who Does
PUT /v1/m/M owner makes the mailbox, or marks it used
DELETE /v1/m/M owner deletes it and its channels
GET /v1/m/M/c owner lists channels: [{"id","kind","expires"}]
PUT /v1/m/M/c/C owner registers a channel: {"kind":"device"} or {"kind":"pair","ttl":SECONDS}
DELETE /v1/m/M/c/C owner removes it; its readers get event: gone
GET /v1/m/M/up owner stream: the up lanes of all device channels
GET /v1/m/M/c/C/up owner stream: the up lane of one pairing channel
POST /v1/m/M/c/C/down owner records for the phone
GET /v1/m/M/c/C/down channel stream: the down lane
POST /v1/m/M/c/C/up channel records for pic
GET /, and the page's files anyone the page, its service worker and manifest

A POST answers 204 with Pic-Peer: 1 or 0: whether the lane's reader is connected, so the page can say "pic remote is not running on your computer" instead of waiting. Errors are a status and {"error":CODE}: 401 (a token that does not hash to the id), 404 (no such mailbox or channel; to a phone, the relay's unauthenticated word that the pairing is gone, never by itself a reason to forget it), 413, 429 with Retry-After.

A stream sends event: frame (section 3), event: peer when the other side connects or leaves, event: replaced to a reader another connection took the lane from (a lane has one reader), event: gone, and a comment line (:) as its first bytes, the moment it opens, and every 15 seconds after, on every stream: pic's mailbox stream, a phone's lane, and both lanes of a pairing channel. The relay may end any stream at any time.

On a phone's down lane, a peer of 0 is followed by event: seen with data: the Unix time in milliseconds pic was last seen: when its mailbox stream last closed, or, if it has not read it since the mailbox's object started, the last time it opened that stream (kept in the mailbox record) or else last used the mailbox. It is sent when the phone connects while pic is away and when pic leaves. pic's own streams carry no seen.

The idle timeout. Every stream carries at least a comment every 15 seconds, so a reader that has received nothing at all, not even a comment, for 45 seconds treats the stream as dead: it aborts it and reconnects with Last-Event-ID (section 3). Both pic and the page do this.

The API sends no CORS headers: the page is same-origin and pic is not a browser. The page is served with Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; manifest-src 'self'; worker-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none', Referrer-Policy: no-referrer and Cross-Origin-Opener-Policy: same-origin, loads nothing from any other origin, and ships no cryptographic code: it calls crypto.subtle and nothing else.

Retention

A record is held in the Durable Object's memory, never in its storage, until the lane's reader has acknowledged it (a later Last-Event-ID, or Pic-Ack: N on any of its requests) or it is 60 seconds old, whichever comes first. An object that is evicted loses what it held, which the endpoints see as a gap. Storage holds only the mailbox's record: when it was made and last used, and its channels with their kinds and expiry times. A mailbox whose owner has not connected for 90 days is deleted.

Limits

What Limit
a record 16417 bytes
a POST 32 records, 256 KiB
a lane's held records 256, or 1 MiB; over it the writer gets 429
a channel, per direction 120 requests and 8 MiB a minute
a mailbox 8 device channels and 1 pairing channel
a pairing channel 900 seconds, 16 records, 64 KiB
streams 1 reader a lane; 6 connections a minute a lane
new mailboxes 10 an hour from one address; a global daily cap set in the Worker's configuration

Creating a mailbox takes the Pic-Invite header, a secret in the Worker's configuration, until registration is opened (open question 1); pic sends the setting remote.invite.

Abuse

Nothing can be stored for longer than a minute or read by anyone without a token, so the relay is of little use as a drop. Channels cannot be made without the owner token, so a phone cannot widen its own access. A token that fails is answered 401 with no detail, and failures count against the address's rate. The Worker has no outbound requests at all: it fetches nothing on anyone's behalf.

Logs

The Worker logs, per request: the time, the route's pattern (never an id), the status, the byte count and an error code. It does not log ids, tokens, addresses, user agents or bodies, and Workers Logs' own capture of request headers is off. Counters (requests, bytes, open streams, refusals by code) are kept in aggregate. What Cloudflare records as the platform is outside this note and inside the threat model.

Cost

A stream keeps its Durable Object in memory, and pic remote holds one open as long as it runs, so a mailbox costs duration for as long as its owner's pic remote is up: about 0.125 GB-seconds a second. That is the price of SSE over a hibernating WebSocket and was accepted with the transport; the figure is to be measured in the first landing.

7. pic remote

pic remote runs in the foreground until it is stopped. It is the only process that talks to the relay outside pairing.

Start

  1. Takes ~/.pic/remote.lock exclusively (flock, through pic_platform, as a lease is taken). A second pic remote says one is running and exits. The kernel drops the lock when the process dies; the file is never removed.
  2. Asks for the credential store's passphrase on the terminal, every time: it does not take a key handed down by a parent (PIC_KEY_FD), and with no terminal it exits with a message.
  3. Opens the keys and the device rows. With no device paired it says so, names /rc, and waits for one.
  4. Reconciles the relay with the table: PUT the mailbox, list its channels, register every device's channel, delete every device channel that has no row.
  5. Opens the mailbox stream and prints one line: the relay, how many devices, how many workspaces.

Running

It never takes a lease, never opens a journal other than narrowly, never listens on any socket, and writes nothing to a journal but inbox rows.

Stopping and dying

SIGINT and SIGTERM send bye to each session and exit. SIGKILL, a crash or a power cut leave:

What After
commands that were acknowledged committed rows; delivered by whoever runs the conversation
a request it started running in its own process; unaffected
a command received and not yet committed never acknowledged; the phone sends it again
sessions, cursors, the live text gone; the phone starts a session and sends sync
a push not yet sent not sent
the lock released by the kernel

There is nothing to recover and no file to clean. Starting it again is the whole repair.

/rc shows whether a pic remote is running, by trying the lock for an instant, next to the devices and the pairing code.

8. Test vectors

Both implementations must reproduce, byte for byte, one file of vectors: test/pic/remote-vectors.json in pic, the canonical copy, and test/vectors/remote-v1.json in pic-relay, byte-identical. Each repository's tests check the file's SHA-256 against a constant, so the copies cannot drift without a test failing in the repository that changed. A change to the vectors lands in pic first and carries the new hash in its changelog line.

The file is made by a third implementation, tools/remote-vectors.js (Node's built-in crypto only, about 150 lines, kept in both repositories beside the file), so that neither product implementation is its own reference. It exists, and its handshake, transport keys and VAPID signature have been reproduced with the vendored BearSSL; it also reproduces RFC 8291's own example. The first file's SHA-256 is fa895483624944e6f7e36b690bc3344a19e6755c270d49d10c4a876869e0e4ab.

All private keys in it are counting bytes, 32 from the given first byte:

Input Value
pic static private 01..20
phone static private 21..40
pairing ephemerals: phone, pic 41..60, 61..80
session ephemerals: phone, pic 81..a0, a1..c0
pairing secret c1..e0
owner token, channel token 10..2f, 30..4f
VAPID private 51..70
push: phone private, auth secret, pic's ephemeral private, salt 71..90, 00..0f, 91..b0, f0..ff

What each side must produce from them:

  1. Derivations. The mailbox id 09060344e6cc9b82378e25518284a1cf, the psk, the pairing token and channel, the device channel 17ad112a3b7c0e38e0c245aa466c607d, and the offer's 122 bytes and its address for expires 1800000000.
  2. The pairing handshake, session id 0102030405060708, with the two payloads given as exact bytes: both records, the handshake hash d9941f270bb65ba3791e4c250514644f47fd26395f9052d44cd9d8c937d65a93, the code 333054, both transport keys, and the first transport record each way (pair_ready, paired).
  3. The session handshake, session id 1112131415161718: both records, the hash cb4a1cc231d2e46aab6a622d17cf5c24ab87244af781aa699508e1926c3f42a6, both keys, the transport records with n 0 each way and n 7 down, a 20000-byte message as two records (n 1 and 2 up, given by their SHA-256), and a reset record.
  4. VAPID. The token for the exact header and claims bytes in the file. pic must produce the signature itself, since RFC 6979 makes it unique; the page never signs, and pic-relay's test verifies it.
  5. Push. The body for the file's plaintext, keys and salt, the Topic value, and the body of RFC 8291 appendix A from that appendix's inputs.

Each implementation also has, as tests of its own with these keys: every initiator vector read by its responder and the reverse (so both roles exist on both sides, the unused one in tests only); and the refusals: a record with one bit changed anywhere, a replayed n, a message 1 with the wrong psk, with a public key not on the curve, with an unknown static key, and with the right key on the wrong channel. Each must be dropped with no state changed.

9. Threats, and what an outside reviewer checks

Who can do what

Attacker Can Cannot
the relay, malicious or compromised, as a message carrier drop, delay, reorder or replay records, which ends in a gap, a dropped record or a new handshake; refuse service; see the metadata of section 3; learn when you work and roughly how much the model writes read or change a command, an event or a notification; pair a device; pass as pic or as a phone; cause a command to run twice, or one the phone did not send
a network attacker what TLS allows a network attacker, and then at most what the relay can the same
a leaked QR code, within its ten minutes and before the owner's phone used it start a pairing, which shows the attacker's name and a code on the terminal that the owner's phone is not showing pair without a yes at the terminal; do anything once the offer is used or over; learn anything about later sessions
a leaked QR code, later learn pic's static public key and mailbox id, and so tell that a mailbox exists anything else: the secret is spent, the pairing channel deleted
a stolen phone, locked read notification lines on the lock screen, as the owner chose open the page
a stolen phone, unlocked everything the owner can, until it is unpaired at the terminal take the static key elsewhere: it is not extractable, so unpairing that one device ends it; reach anything while pic remote is not running
the page host, malicious or compromised (a changed page, a taken-over Cloudflare account or domain) serve script that, on each phone that loads it, reads what is on screen and sends commands as that phone, for as long as it is served: full control of every paired pic that has pic remote running export a phone's static key, so the control ends when the page is honest again; pair a new device; reach a pic whose pic remote is not running
the push service see that a notification was sent, its size and time, and pic's address and VAPID public key; drop it read it or forge one the phone's browser accepts
another user on the machine nothing: ~/.pic is 0700
the same user's other processes anything pic can, as before add a device without the passphrase, short of the above

The page host is the weak point of any design that runs in a browser, and this one does not hide it: the relay is blind to the data it carries, but the code that sees the data is served from the same place. A browser cannot check that code against anything. What limits the damage is that the key cannot leave, pairing needs the terminal, the page loads nothing from a third party, and nothing works unless the user has chosen to run pic remote. The ssh transport of stage 1 has no page and no relay and stays for anyone who will not take this trade.

Not defended: a compromised machine running pic; a user who answers yes to a code they did not check; traffic analysis; denial of service by the relay or the network.

The review

The cryptography is standard pieces in a named arrangement, and the arrangement is ours. Before registration is opened to anyone but the owner, someone outside the project reviews:

  1. The P-256 DH definition against Noise 4.1 and 14: point validation, the encoding, the X coordinate as the output, and that nothing depends on DHLEN being one number.
  2. IKpsk1 and IK as used: the payload properties of 7.7 against what each message carries, that pic sends and acts on nothing before a session is confirmed, and that a replayed message 1 gains nothing in either protocol.
  3. The explicit counter (11.4): strictly increasing, never reused, never persisted, the 2^32 and 24-hour ends, and that the unauthenticated head (type, session id, counter) and the reset record give an attacker nothing beyond a dropped session.
  4. Pairing: the derivations from ps, that the relay's token reveals nothing of psk, the offer's single use and failure count, the six digits against an attacker who races the owner's phone, and the order of the row, the channel and paired.
  5. The page: that the static key is not extractable and has only deriveBits, that the fragment is cleared before any request, the content security policy, the absence of third-party code, and what the session keys in script memory expose.
  6. The relay: that it stores nothing durable but routing, token checks in constant time, the limits, and the logs.
  7. Web Push: VAPID's claims and lifetime, RFC 8291's key schedule, a new key pair and salt for every push, the endpoint check, and the one-line rule against what can reach a lock screen.
  8. pic: sealing of keys and device rows, the passphrase at every start, the key handed to children, and that every command path commits before it answers.
  9. Both implementations against the vectors and the refusals of section 8, and the parsers (the record, the envelope, the stream) under a fuzzer.

10. Landings

Each landing is one change in each repository, tested alone against the vectors and together by the end-to-end test.

The end-to-end test lives in pic-relay: the Worker under wrangler dev, the page's protocol module (no DOM in it) driven from Node, and a real pic (named by PIC) with the scripted provider and a private HOME. pic's own suite needs no Worker: test/pic/remote.sh runs pic remote against a small loopback relay in the test harness that implements section 6 without limits, with the dev build's initiator playing the phone.

1. Pair, follow, prompt

The smallest thing that is useful: start a request from the phone, watch it, steer it, stop it.

2. Streaming text and the rest of the commands

3. Notifications

4. After

Images in a prompt, bash, fork, clone and rewind, padding of record lengths, and, after the review of section 9, opening registration.

Open questions

  1. Who may use the relay? It starts closed, behind an invite secret. Opening it to every pic user makes the owner's Cloudflare account pay for each running pic remote and makes the page host a target worth attacking. Open it after the review, keep it closed and document running your own, or both?
  2. The relay's name. Pairings are tied to the page's origin: moving it later unpairs every phone. Which domain?
  3. Which finished requests notify? The default here is all of them while the phone is not showing the page, which includes requests started at the desk. The alternative is only those a phone started or steered.
  4. iOS, twice or once? A phone that wants notifications must pair inside the installed page, by a copied link. Is that acceptable for landing 3, or should landing 1 already steer iOS users to install first so that they pair once?
  5. Who reviews, and when? This note gates opening registration on the review. Should it gate the owner's own daily use too, and who is asked?

Amendments

Deviations and additions made while building the relay and page, landing 2 of pic-relay. pic matches these.