# Relay protocol v2 This is the public interoperability contract for independently implemented relay services and clients. It does not require access to Horizon's private server source. See [relay setup](relay-setup.md) for configuration and service boundaries. HTTP wire version 2 is distinct from app releases and the unchanged v1 cryptographic domains. The authoritative transport schema is [`proto/relay.proto`](../proto/relay.proto). This is a direct switch to Protobuf: there are no v1 HTTP routes, JSON fallback, or compatibility/migration layer. Breaking wire changes require a new version; unknown fields are rejected. No capability negotiation is implemented. See the [deployment status](releases/protobuf.md). ## Encoding and identity Identifiers and key IDs are lowercase UUIDv4 strings. Times are signed 64-bit Unix milliseconds. Transport binary fields use Protobuf `bytes`. Domain models, identity cards and cryptographic transcripts use canonical unpadded base64url. Public keys are uncompressed 65-byte P-256 points. Mailbox addresses are lowercase hex SHA-256 fingerprints of signing public-key bytes. Signatures are raw 64-byte ECDSA P-256/SHA-256 `(r,s)` values with low-S normalization. Protobuf parsers enforce proto2 required-field presence (including explicit false and empty values), reject unknown fields recursively, and enforce the existing key, signature, audience and size validation. Text must be valid UTF-8; an optional cursor must be nonempty when present. Decoding limits nesting to 32 levels. Standard Protobuf merging rules apply to repeated occurrences: singular scalars take the last value, singular messages merge, and repeated fields append. Field order is not cryptographically significant. HTTP authentication signs the exact received body before decoding, while message proofs sign the explicitly defined transcripts. Never use Protobuf serialization as a canonical signature transcript. Cards, encrypted plaintext and local state remain JSON. Their parsers reject duplicate or unknown members, nulls, missing required fields, invalid UTF-8, and trailing data. JSON ordering and whitespace have no cryptographic meaning. `Fields(domain, values...)` concatenates the UTF-8 domain with each value prefixed by its unsigned 32-bit big-endian byte length. Nested transcripts are raw bytes, not JSON. Integers in transcripts use canonical decimal text. Domain strings separate keys, peers, cards, manifests, copies, proofs, HTTP requests, and grants. The complete field orders are specified below. Cards use `confer.agent.v1.` or `confer.device.v1.` followed by base64url JSON. The self-signature binds the card kind, IDs, identifying labels, public keys, and issuance time. Import permits at most one hour of age and five minutes of future clock skew. Names are self-asserted; the human supplies the trust decision. ## HTTP authentication Application requests include `X-CONFER-Key`, `X-CONFER-Time`, and `X-CONFER-Signature`. The signed transcript is: ``` Fields("confer/http/v1", method, lowercase_host_with_port, exact_path_and_query, hex_sha256(body), timestamp, signing_public) ``` The timestamp must be within five minutes of relay time. Authentication derives the mailbox address from the supplied key. Mailbox paths must name that address. Clients reject redirects. HTTPS is mandatory except for loopback development. Readiness routes are unsigned. Replays of mutations are constrained by durable operation identity or permission-version checks, not an extra session/nonce table. | Method and path | Body / result | | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `POST /v2/questions` | `Batch` containing a question or answer; returns `question_id`. | | `GET /v2/mailboxes/{address}/questions?cursor=...` | `Page` with records and optional `next_cursor`. | | `GET /v2/mailboxes/{address}/questions/{id}` | One `Record`, containing a question and optional answer. | | `GET /v2/mailboxes/{address}/senders?cursor=...` | Allowed-sender records, including disabled tombstones. | | `PUT /v2/mailboxes/{address}/senders/{sender}` | `SenderUpdate`; returns the resulting allowed-sender record. | | `DELETE /v2/mailboxes/{address}` | Empty body; retires the identity and deletes up to forty mailbox/permission records; returns `{complete: bool}`. Repeat until complete. | Pages contain at most twenty records. Cursors are the last question UUID or sender fingerprint in the caller's partition, never arbitrary DynamoDB keys. Question pagination is UUID order; clients sort the verified inbox by creation time. ## Encrypted messages A manifest binds `version`, `kind`, `question_id`, `operation_id`, `created_at`, `question_hash`, `sender`, and sorted `recipients`. Each peer contains its address and full public key bundle. The audience contains the origin and one to eleven unique devices. Contact names and routing metadata are absent. Each recipient gets independently sealed HPKE ciphertext using P-256 / HKDF-SHA256 / AES-128-GCM, info `confer/message/v1`, and this associated data: ``` Fields("confer/message-aad/v1", manifest_transcript, recipient_address) ``` Each copy contains `recipient`, `enc`, and `ciphertext`. A signed proof binds the manifest and an ordered list of every recipient's copy hash. Consequently each recipient can authenticate the complete audience while receiving only its own ciphertext. The proof hash binds both its transcript and signature. Question plaintext is `{type: "question", title, source, content: {html}}`. Only type `question` is supported. An answer is `{answer}`. Titles allow 120 Unicode scalars; sources 80; HTML 12 KiB; answers 4096 UTF-8 bytes. All are nonblank. The serialized plaintext cap is 16 KiB and submission cap 512 KiB. HTML is rendered directly in WebKit with JavaScript, forms, navigation and external requests enabled. It is not sanitized. Native answer controls are separate from the document; submitting a web form does not answer the question. The web session is nonpersistent and has no native bridge. Agents should use absolute resource URLs. Trusting an agent includes trusting its web content. Agent input accepts exactly one of `content.text` or `content.html`. Text is escaped into paragraphs with line breaks before encryption. The wire format contains only HTML, with no legacy plaintext fallback. See [the HTML release status](releases/html-content.md). A question has an empty `question_hash`. The relay atomically creates all copies, checking that every device mailbox allows the signing identity. The origin's own copy needs no grant. Any failed permission or existing conflicting ID rejects the whole delivery. An exact retry succeeds even after later permission removal. An answer binds the original proof hash and exact original audience. Its signer must be one of the devices in that audience, never the question's origin. Existing question records authorize only this specific reply; devices need no broad write grants to one another. Atomic conditional updates select one answer across every remaining mailbox. A retired recipient's copy is skipped without changing the signed audience. If retirement races with an answer, the transaction may fail and can be retried unchanged. Exact retries succeed; a different accepted answer yields 409. No later operation edits an accepted answer. A device verifies a question against its locally trusted sender's complete keys, checks its own recipient keys, then decrypts. It verifies an answer against the original question's audience and hash. The agent performs the same checks using its own original question identity. Relay assertions alone establish no trust. ## Allowed senders and removal `SenderUpdate` contains `enabled`, `previous`, and a fresh `operation_id`. Its version is the hash of the domain-separated previous version, operation UUID, and Boolean. The first change expects an empty previous version. Subsequent changes must match the stored version. A retry of the current version succeeds; a stale update gets 409. Disabled records are retained so old enable requests cannot restore permission. Clients fetch current state before a new deliberate change; uncertain changes can be reconciled on the next sync. Removing a sender blocks **new questions**. Existing questions still authorize answers by their original audience, including copies to all original recipients. Local removal stops trusting that origin immediately. Removing a device from a contact changes future audience selection, not already-delivered messages. ## Device reset Signed `DELETE /v2/mailboxes/{address}` is restricted to that mailbox's owner. It permanently creates a retirement marker before removing this address's permission records and encrypted mailbox copies. Each call deletes at most twenty records from each partition in a transaction. A false `complete` result, timeout, or lost response requires retrying the same endpoint with the old key. No new local identity is generated until cleanup is confirmed. Permission updates and message writes transactionally check retirement, so an old signed first-grant request cannot recreate deleted permissions and an in-flight answer cannot recreate deleted messages. Retired identities cannot submit questions or answers. New questions addressed to any retired recipient are rejected. Other recipients can still answer existing questions, retaining the complete signed audience while omitting storage for retired identities. Reset is irreversible and does not delete copies belonging to other identities. Horizon’s reference storage uses these record types (other implementations may use any database with equivalent atomicity and retirement semantics): - `MAILBOX#
` / ``: encrypted question, optional answer, and proof hashes for conditional updates. - `ALLOWED_SENDERS#
` / ``: enabled state, version, and update time. - `RETIRED#
` / `identity`: key-only permanent retirement marker. There is no server-side identity registry, contact directory, key rotation service, message deletion/retention job, shared revocation log, or migration layer. The relay observes public keys, participant relationships, timing, status, and ciphertext sizes. It cannot read titles, sources, questions, or answers. ## Domain shapes and transport mapping The following notation describes the internal JSON domain models, not HTTP bodies. HTTP requests/responses are the corresponding Protobuf messages in `proto/relay.proto`. `Keys.encryption_public`, `Keys.signing_public`, `Proof.signature`, `Copy.enc`, and `Copy.ciphertext` are raw bytes on the wire; adapters convert them to canonical unpadded base64url before computing existing transcripts/hashes. UUIDs and hex hashes remain strings. `Manifest.version` remains **1**, identifying the unchanged cryptographic envelope, even though HTTP routes use `/v2`. `Receipt` and `ResetResult` are named schema messages. No bytes of ciphertext are re-encrypted when transcoding. Storage and durable retry batches still use the domain models. The following domain notation describes member names and types, not literal JSON. `?` marks a member omitted when absent, never encoded as null. Lists are JSON arrays; empty response lists must be `[]`. All other members are required, even when a string is empty or a Boolean is false. Do not include additional members. ```text Keys = {encryption_key_id: UUID, encryption_public: Base64URL, signing_key_id: UUID, signing_public: Base64URL} Peer = {address: Hash, keys: Keys} Manifest = {version: 1, kind: "question" | "answer", question_id: UUID, operation_id: UUID, created_at: Milliseconds, question_hash: Hash | "", sender: Peer, recipients: [Peer]} Copy = {recipient: Hash, enc: Base64URL, ciphertext: Base64URL} CopyHash = {address: Hash, hash: Hash} Proof = {manifest: Manifest, copies: [CopyHash], signature: Base64URL} Batch = {proof: Proof, copies: [Copy]} Delivery = {proof: Proof, copy: Copy} Record = {question_id: UUID, question: Delivery, answer?: Delivery} Page = {questions: [Record], next_cursor?: UUID} SenderUpdate = {enabled: Boolean, previous: Hash | "", operation_id: UUID} AllowedSender = {address: Hash, enabled: Boolean, version: Hash, updated_at: Milliseconds} SenderPage = {senders: [AllowedSender], next_cursor?: Hash} ``` `Hash` is 64 lowercase hexadecimal characters, representing SHA-256. A peer's address must equal the hash of its decoded signing public key. The manifest's creation time must be positive and no more than five minutes in the future at submission. The HTTP timestamp must be fresh even when retrying an old manifest. The manifest audience has 2–12 peers, sorted strictly ascending by address, without duplicates, and includes the sender's full peer. Both proof copy hashes and batch copies have exactly the same count and recipient order. Validate all keys and signatures before storing. Each copy hash must match the corresponding ciphertext. `enc` is a valid 65-byte uncompressed P-256 point. Ciphertext has 16–16400 bytes after base64url decoding. Return only the requesting mailbox's copy, together with the whole proof; never return other recipients' ciphertexts in a `Delivery`. A signed card is a JSON object with `kind`, `display_name`, `keys`, `issued_at`, and `signature`, plus these kind-specific fields: - Agent: `kind = "agent_installation"`, `installation_id` (UUID), `hostname`. Omit `device_id` and `platform`. - Device: `kind = "device"`, `device_id` (UUID), `platform = "ios" | "macos" | "android"`. Omit `installation_id` and `hostname`. Display name is nonblank, at most 256 UTF-8 bytes. Agent hostname is nonempty, at most 256 UTF-8 bytes. A card is at most 8192 text bytes including its prefix. Cards are exchanged by people between endpoints; relays have no card-registration endpoint and never need private keys. Device identity and signing fingerprint are different identifiers. Keep the complete public key bundle when trusting a peer. ## Exact transcripts and cryptography In this section `F` means `Fields`, `H` is SHA-256 encoded as lowercase hex, `T(x)` is a raw transcript byte string, and `B64` is canonical unpadded base64url. For an omitted optional card string, use an empty string in its transcript. Array elements below expand into consecutive fields; there is no separate array count. Prefix the length of each field, including nested transcript bytes. Do not base64-encode nested transcripts before passing them to `F`. ```text T(keys) = F("confer/keys/v1", encryption_key_id, encryption_public, signing_key_id, signing_public) T(peer) = F("confer/peer/v1", address, T(keys)) T(card) = F("confer/card/v1", kind, installation_id, device_id, hostname, display_name, platform, T(keys), decimal(issued_at)) T(manifest) = F("confer/manifest/v1", decimal(version), kind, question_id, operation_id, decimal(created_at), question_hash, T(sender), T(recipients[0]), ..., T(recipients[n-1])) copy_hash = H(F("confer/copy/v1", recipient, enc, ciphertext)) T(proof) = F("confer/message-signature/v1", T(manifest), copies[0].address, copies[0].hash, ..., copies[n-1].address, copies[n-1].hash) proof_hash = H(F("confer/message-hash/v1", T(proof), signature)) permission_version = H(F("confer/allowed-sender/v1", previous, operation_id, "true" or "false")) ``` Sign the SHA-256 digest of `T(card)` or `T(proof)` using the sender's P-256 signing key. Signatures are `B64(r32 || s32)` with unsigned big-endian fixed-width integers, not DER. Enforce `0 < r < n` and `0 < s <= floor(n/2)` where `n` is the P-256 group order. A signer normalizes a high S value by replacing it with `n-s`. HTTP signatures use exactly the same signature encoding and hashing convention. HPKE is RFC 9180 base mode (mode 0), DHKEM(P-256, HKDF-SHA256) KEM ID `0x0010`, HKDF-SHA256 KDF ID `0x0001`, AES-128-GCM AEAD ID `0x0001`. Info is the raw UTF-8 bytes `confer/message/v1`. Create a fresh sender context for each recipient copy; seal one plaintext at sequence number zero with the associated data above. Encode encapsulated public key and ciphertext (including authentication tag) as B64. Sign the complete set of copy hashes after encrypting. No pre-shared key, server-held decryption key, or shared symmetric group key is used. A framing example: `F("demo", "A", "")` has hexadecimal bytes `64656d6f000000014100000000`. `H("")` is `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`. A GET/DELETE with an empty body uses that body hash in its HTTP transcript. ## Responses, failures, and retries All successful protocol operations return HTTP 200 with Protobuf and `Content-Type: application/protobuf`. POST/PUT requests must use that exact media type (otherwise 415); clients send `Accept: application/protobuf` and reject successful responses with another media type. Health/readiness remain JSON. API Gateway Lambda responses base64-encode the binary body and set `isBase64Encoded: true`; the gateway decodes it back to Protobuf for clients. Authentication headers must each occur exactly once. GET and DELETE bodies must be empty. Requests and responses must not be cached. Preserve the public host and exact encoded URI through proxies when verifying signatures; rewriting either invalidates authentication. | Status | Meaning / client action | | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | 400 | Invalid Protobuf, identifiers, proof, or request. Correct the request. | | 401 | Missing/invalid signature or timestamp. Check keys, canonical transcript and clock. | | 403 | Wrong mailbox owner, missing delivery permission, retired identity, or operator admission denied. Resolve access; do not silently narrow recipients. | | 404 | Record does not exist in that mailbox. | | 409 | Conflicting question/answer or stale permission version. Read current state and reconcile. | | 413 | Request body exceeds 512 KiB. | | 415 | POST/PUT Content-Type is not application/protobuf. Correct the request. | | 503 | Temporary storage/service failure. Preserve the exact operation for retry. | Error bodies may be plain text, not Protobuf; clients rely on the HTTP status. Unknown paths and unsupported methods may return 404/405. Infrastructure may also return other non-200 statuses; treat these as failures, not answers. A question submission response is a `Receipt` naming the submitted UUID. Empty repeated lists in `Page` and `SenderPage` decode to empty lists (an empty page can serialize to zero bytes). Omit `next_cursor` at end of pagination; if provided, follow it even if the page is empty. Permission responses return the requested sender address, computed version and actual `enabled` value. Reset responses contain the required `ResetResult.complete` Boolean. Persist a batch before sending. A timeout is an unknown outcome; retransmit the same manifest, ciphertexts, operation IDs and signature using a fresh HTTP timestamp/signature. Read state after a conflict. Never create a new question ID merely because a response was lost. A first accepted answer is final and must be committed atomically across the still-active audience. A relay must not acknowledge partial delivery as success. ## Retention and implementation checks There is no message acknowledgment, automatic expiry, TTL field, quota negotiation, or migration API in v2. Reading/answering does not delete a message. The reference relay retains copies until mailbox reset, and retains retirement markers permanently. An operator must disclose any service-level retention policy separately, maintain anti-replay/retirement guarantees, and account for offline participants and retries. Do not advertise automatic deletion merely because payloads are encrypted. Before claiming interoperability, test with fresh agent and device identities: 1. Reject missing/invalid signatures, altered hosts/paths/bodies, stale timestamps, missing required Protobuf fields, nested unknown fields and malformed keys. 2. Deny a new question until every non-origin recipient grants permission; grant updates must survive retry and reject stale previous versions. 3. Submit an encrypted question to two devices, verify each can decrypt its own copy, and verify neither a different identity nor a changed proof is accepted. 4. Retry the exact submission and confirm one logical question. Race two answers; only one wins and every active mailbox agrees. Verify the answer at the agent. 5. Page through more than twenty questions and senders, including empty/end pages. 6. Revoke permission: new questions fail but existing audience replies still work. 7. Reset a mailbox in repeated calls, retry after lost responses, and prove old signed mutations cannot recreate it. Other participants retain their copies. Health probes (`GET /health`, `GET /ready`) are unsigned operational endpoints in the reference deployment, returning `{"status":"ok"}` when healthy. They are not proof of protocol compatibility, admission, delivery or decryption.