Status: accepted; landing 1 (pair, follow, prompt) in pic. Stage 1 (the inbox, pic attach, ssh) is in
grapevine and the inbox.
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
||joins bytes. Integers on the wire are big-endian.b64uis base64url without padding (RFC 4648 section 5). JSON is RFC 8259, UTF-8, no byte order mark.SHA256(x)is FIPS 180-4;HMAC(k, x)is HMAC-SHA-256 (RFC 2104);trunc16keeps the first 16 bytes.- "Noise" is The Noise Protocol Framework, revision 34 (2018-07-11); section numbers are its.
- pic is the responder and the phone the initiator in every handshake.
upis phone to pic;downis pic to phone.
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:
picu_remote_key(name TEXT PRIMARY KEY, public BLOB, sealed BLOB NOT NULL, created_ms INTEGER NOT NULL).sealedispic_cred_seal(src/cred.h: ChaCha20-Poly1305 under the credential store's master key) with the additional dataremote-key:NAME.picu_remote_device(id BLOB PRIMARY KEY, sealed BLOB NOT NULL, paired_ms INTEGER NOT NULL, seen_ms INTEGER).idis 16 random bytes pic chose.sealedholds the JSON object{"name", "static", "channel", "push"}(the phone's name, its static public key and channel id asb64u, and its push subscription ornull) with the additional dataremote-device:and the id in hex.
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. Conversation content and cursors are held in memory only and are gone when the
page closes.
Unpairing
- At the terminal.
/rclists devices (name, paired, last seen) and unpairs one: the row is deleted in one transaction, which needs no passphrase. A runningpic remotesees the change within a second (it polls the user database'sPRAGMA data_version), sends that device{"type":"unpaired"}if it has a session, drops the session and deletes the channel at the relay. With nopic remoterunning, the next one deletes the channel when it reconciles (section 7). The row's deletion is the revocation; the relay's part only saves traffic. - On the phone. "Forget this computer" sends
{"type":"unpair"}when it has a session and deletes the pairing object either way. - Everything.
/rcreset deletes every device row and all three keys, and the mailbox at the relay. The next/rcstarts from nothing.
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:
GENERATE_KEYPAIR(): a P-256 key pair.- A public key on the wire is its 65-byte uncompressed encoding,
0x04 || X || Y(SEC 1 version 2, section 2.3.3). An encrypted static key is therefore 81 bytes. DH(pair, public): the 32-byte X coordinate of the shared point (SEC 1 section 3.3.1; whatderiveBitsreturns for 256 bits and what RFC 8291 uses).- A received public key must be a valid point on the curve other than the point at infinity
(NIST SP 800-56A revision 3, section 5.6.2.3.4).
br_ec_p256_m31.mulreturning 0 andimportKey("raw", ...)rejecting are that check; a handshake that fails it is dropped. DHLENis 65 for public keys and 32 for DH outputs. Nothing else in Noise depends on the two being equal.
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).
- Phone to pic, on channel
Pwithpair_token: message 1 with the payload{"v":1,"name":NAME,"channel":b64u(C)}.NAMEis a label the phone picks ("iPhone, Safari"), at most 64 bytes. - pic reads it. A message that does not verify counts against the offer and is otherwise ignored.
One that does proves its sender knew
psand 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)}. Both sides now hold the handshake hash
h(11.2) and the two transport keys. Each computessas = decimal(uint32(HMAC(h, "pic-rc/1 sas")[0..4]) mod 1000000), 6 digits, zero-padded
The phone shows the code and sends the transport message
{"type":"pair_ready"}.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.On yes, pic commits the device row, registers channel
Cas a device channel, sends{"type":"paired"}and deletes channelP. On no, or at expiry, it sends{"type":"error","payload":{"code":"pair_refused"}}and deletesP.On
paired, the phone stores the pairing and opens its first session onC.
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:
nstarts at 0 and goes up by one for every record sent. A value is never used twice under one key. Keys and counters live in memory only and a session is never resumed from storage, so a restart cannot repeat a nonce: it starts a new handshake.- A session ends, and the phone starts a new one, before
nreaches 2^32 in either direction or after 24 hours. pic asks for it with{"type":"bye","payload":{"reason":"rekey"}}.Rekey()(11.3) is not used: a new handshake is the one way keys change, and it brings new ephemerals.
Rules for the lane it reads:
- Keep
last, the highestnaccepted, starting at -1. A record withn <= lastis dropped before decryption (a replay, or a duplicate from a reconnect). A record withn > lastis decrypted with thatn; if it verifies,last = n. The relay keeps a lane in order, so no window is needed. - A record that fails to verify is dropped and changes nothing.
n > last + 1is a gap: records were lost. The transport reports the gap to the layer above and carries on. Reliability is the envelope's business (section 4), not the transport's.
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
- The phone opens its stream and posts message 1 with the payload
{"v":1}. - 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. - The phone sends its first transport message (a
sessionsorsync, 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
- Streams. Either side reconnects with
Last-Event-ID. The relay sends the records it still holds after that id, or all it holds when it does not know the id. Duplicates fall to the counter rule. - pic. Reconnects after 1 second, doubling to 60, each wait varied by a fifth either way; a connection that lasted 30 seconds resets the wait. It reconnects at least every 15 minutes. A record that has waited 30 seconds to be posted is dropped unsent, which the phone sees as a gap.
- The phone. The same schedule. A page that was hidden for more than 30 seconds, or that sees
a reset, or no
pongfor 150 seconds, starts a new session. - After any gap or new session, the phone sends
syncwith its cursor (section 4) and repeats the commands it has no answer for. That is the whole of resumption: the journal'sseqfor what flows down, idempotency keys for what flows up.
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 |
send the list of conversations, and again when it changes | |
sync |
session, seq |
follow this conversation from after seq; -1: from the start of its latest request |
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":{...}} 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"}]} |
event |
session, seq, payload |
a Pi event rebuilt from committed rows |
sync |
session, seq, payload |
a mark: the phone has everything through seq; {"running":BOOL} |
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, payload |
the command is committed: {"state":"pending"} |
response |
key, 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.
- On
sync, pic follows the conversation aspic attach --from SEQdoes: the same pass over committed rows (src/attach.c), run when the journal'sdata_versionchanges, with a sink in place of stdout. A newsyncreplaces the one before. - Each pass sends its events in order, each with the
seqof the entry it came from, then one mark with the highestseqthe pass read and whether a request is running. The first mark answers thesynceven when the pass had no events. - The phone shows events as they come and moves its cursor only at a mark. After a gap it drops
what it holds past the cursor and sends
syncfrom the cursor. Events are never applied twice and none is missed, because a pass is one read transaction and a mark closes it. fetchis for scrolling back and is answered once, without following.- An event larger than 256 KiB is sent as
{"type":"elided","eventType":T,"bytes":N}in the payload;fetchwith"full":truereturns it whole, up to the message limit.
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.
Commands, keys and exactly once
Every command that changes anything is a committed journal row before pic remote answers it:
- The row's key is
rc:DEVICE:KEY, with the device id asb64u, and its sender isremote:DEVICE. One phone cannot reuse or collide with another's keys. steer,follow_upandabortgo throughpic_inbox_accept, unchanged. pic answersackonce the row is committed, andresponsewith the row's response line when it leavespending.promptwith nothing running is a keyed admission: whatpic submit KEY TEXT --session IDdoes, followed bypic run --session ID, in one detached child in a session of its own (setsid), aspic attach -istarts a request today. A second admission with the key reports the first.promptwhile a request runs follows Pi: withstreamingBehaviorit is the steer or follow-up above, without it the response is Pi's error.- A known key with the same command returns the same
ackorresponseagain and changes nothing. The same key with another command is refused, as the inbox does. - The phone repeats a command with its key every 5 seconds, and at the start of each new session,
until it has an
ackor aresponsefor the key. It keeps asking for aresponseit lacks the same way.
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: 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 |
clear_queue, set_model, cycle_model, set_thinking_level, cycle_thinking_level, set_steering_mode, set_follow_up_mode, set_session_name, set_auto_compaction, set_auto_retry, abort_retry, compact, bash, abort_bash, fork, clone, rewind |
the inbox, each added there as grapevine adds commands | 2 and 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:
- 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.
- 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. - 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.
- Hooks run as they do locally and may refuse. They see
originremote:DEVICE, so a policy stricter than this note's is a hook, not a setting here. - It is recorded: the sender is on the inbox row or the request, so the journal says which device asked for what.
- 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.
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}.
Tis the conversation's name, or else the last part of the workspace's path; at most 60 characters.Bis the first line that is not empty of the text of the request's last reply, with runs of white space made one space and control characters removed, cut to 200 characters with an ellipsis. When the request ended with no reply text, it is how it ended: "Stopped", "Failed:" and the error's first line, or "Reached the request cap".- Nothing else is ever in a notification: no prompt, no tool input or output, no path beyond
T.
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 conversation, and a tap
opens the page at that conversation, 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, "unpaired"), 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 every 15 seconds. The relay may end any stream at any time.
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
- Takes
~/.pic/remote.lockexclusively (flock, throughpic_platform, as a lease is taken). A secondpic remotesays one is running and exits. The kernel drops the lock when the process dies; the file is never removed. - 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. - Opens the keys and the device rows. With no device paired it says so, names
/rc, and waits for one. - Reconciles the relay with the table:
PUTthe mailbox, list its channels, register every device's channel, delete every device channel that has no row. - Opens the mailbox stream and prints one line: the relay, how many devices, how many workspaces.
Running
- One loop, one extra thread. A thread reads the stream and writes whole records to a pipe;
like the inbox's watcher it never touches SQLite. The loop waits on that pipe and a 100 ms tick,
as
pic attachdoes. - Devices. It polls the user database's
PRAGMA data_versioneach second. A new row (paired in/rcmeanwhile) is served from then on; a deleted row ends that device's sessions. - Workspaces. The conversations a phone can see are those of every
picu_workspacerow whose path still holds that journal, opened withpic_open_narrow: the user's own file, this build's schema, no recovery, no migration. A journal the narrow open refuses is listed as unavailable with its reason.sessionslists the 50 most recently active conversations across them. - Following. One read connection per journal that has a followed conversation, and the
pic attachpass per followed conversation, each pass one read transaction whose output is queued and sent after the transaction ends, so a slow phone never pins a WAL. - Commands. Section 4: a row through
pic_inbox_accept, or a keyed admission in a child. A child gets the unlocked master key over the pipepic_cred_handoffmakes, as the terminal's children do, and is in a session of its own, so it outlivespic remote. - Several phones. Each has its channel, its sessions and its followed conversation. They share nothing but the journal.
- Sending. One post in flight per channel; records queue behind it and go out together. A
livevalue never queues.
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:
- Derivations. The mailbox id
09060344e6cc9b82378e25518284a1cf, thepsk, the pairing token and channel, the device channel17ad112a3b7c0e38e0c245aa466c607d, and the offer's 122 bytes and its address forexpires1800000000. - The pairing handshake, session id
0102030405060708, with the two payloads given as exact bytes: both records, the handshake hashd9941f270bb65ba3791e4c250514644f47fd26395f9052d44cd9d8c937d65a93, the code333054, both transport keys, and the first transport record each way (pair_ready,paired). - The session handshake, session id
1112131415161718: both records, the hashcb4a1cc231d2e46aab6a622d17cf5c24ab87244af781aa699508e1926c3f42a6, both keys, the transport records withn0 each way andn7 down, a 20000-byte message as two records (n1 and 2 up, given by their SHA-256), and a reset record. - 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. - Push. The body for the file's plaintext, keys and salt, the
Topicvalue, 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:
- 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
DHLENbeing one number. IKpsk1andIKas 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.- 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.
- Pairing: the derivations from
ps, that the relay's token reveals nothing ofpsk, 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 andpaired. - 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. - The relay: that it stores nothing durable but routing, token checks in constant time, the limits, and the logs.
- 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.
- 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.
- 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.
- pic. The two tables; the Noise module over BearSSL, both roles, passing vectors 1 to 3;
pairing in
/rc(the offer, the QR code, the code on screen, yes or no, the device list, unpair, reset);pic remote(lock, passphrase, reconcile, stream and post, sessions, backoff);sessions,sync,event, marks,ping;get_stateandget_messages;steer,follow_upandabortthrough the inbox;promptby keyed admission. Crash tests:pic remotekilled before and after a command's commit delivers once; killed mid-follow, a new session with the old cursor shows no gap and no repeat. pic-relay. The Worker and Durable Object with every endpoint, limit and the invite; the page: open an offer, pair, show the code, list conversations, follow one (messages, tool calls and their results, how a request ended), a box to type in (a prompt when idle, a steer while running) and a stop button; reconnecting, cursors and command retries; vectors 1 to 3 on WebCrypto in a real browser engine.- Left out: text as it streams, push, images, any other command, installing to the Home Screen.
2. Streaming text and the rest of the commands
- pic. The
livevalue (with grapevine's stage 3 publishing the text locally);fetchand elision; a new conversation from the phone; the model, thinking, queue, name and compaction commands as the inbox gains them; the remaining queries. pic-relay. The streamed reply, scrolling back, a conversation picker with new conversation, model and thinking controls.
3. Notifications
- pic. VAPID and RFC 8291 (vectors 4 and 5), the
pushandpresencemessages, the one-line rule,remote.notify. pic-relay. The manifest, the service worker, the permission prompt, the Home Screen flow on iOS with pairing by copied link, a mute switch per device.
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
- 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 remoteand makes the page host a target worth attacking. Open it after the review, keep it closed and document running your own, or both? - The relay's name. Pairings are tied to the page's origin: moving it later unpairs every phone. Which domain?
- 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.
- 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?
- 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 made while building landing 1.
- The relay answers 403, not 401, for a new mailbox without the invite; 409 when a mailbox already has its 8 device channels; and 400 for a body that does not parse.
- Registering a pairing channel replaces the mailbox's earlier one.
peerevents carry "1" or "0", or "C.1" or "C.0" on pic's mailbox stream.Pic-Ackapplies only to the lane the requester reads.- Failed tokens are capped at 60 an hour per address.
- Section 3, reconnecting, is amended: the wait doubles to 30 s, not 60. A stream that carries no
byte for 35 s (the relay comments every 15 s) is dead. A wake (pic: a tick 10 s late, or the wall
clock 10 s ahead of the monotonic one; the page: also
onlineandvisibilitychange) reconnects at once and posts what waits instead of dropping it as stale. - After a gap the phone syncs from its cursor in a new session, not the one with the gap: records of the old pass still in flight are then dropped by their session id, so no event is taken twice.
sessionscarriesworkspaces:[{"id","path","name","lastMs"}], every workspace pic knows, most recent first,idthe W ofW/C.promptwithsession+Wis in landing 1, and itsresponseenvelope carriessession, the new conversation'sW/C, on every retry of the key; a prompt's response names its conversation that way too.- User message events carry
originwhen the message did not come from the terminal running the request: the inbox sender, orremote:DEVICEfor a phone's prompt. - Section 2, step 6 is amended: pic deletes channel P only once the relay reports that the phone is
reading it (
Pic-Peer: 1on the post ofpaired, or apeerevent saying it came back), at most 30 s after posting (2 s when the relay sends noPic-Peer), so a phone that was reconnecting does not losepaired.