> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fau.run/developer/llms.txt
> Use this file to discover all available pages before exploring further.

# Wire specification (fau/1)

> Normative contract between relay, node, agents, and approval apps.

This document is the contract between the **node** (Python, `node/`) and the **relay**
(Go, `relay/`). Both sides are implemented against this file; change it before changing
either implementation.

Version: `fau/1`

***

## 1. Roles

```
agent ---TLS(SNI: <node-id>.relay.example.com)---> relay :443 (no decryption)
                                                     |
                                        raw TCP bytes over tunnel stream
                                                     v
                                          node tunnel client -> 127.0.0.1:<tls_port>
                                                     |
                                              node terminates TLS
                                                     v
                                               MCP / phone API
```

The relay never terminates TLS for a node hostname. It reads the SNI server name from
the first TLS `ClientHello` and pipes bytes. Its own control hostname
(`relay.example.com`) is the single exception: that hostname is terminated by the relay
itself.

## 2. Tunnel

One outbound WebSocket per node: `wss://relay.<domain>/tunnel`, subprotocol `fau.1`.
Multiplexed with the frame format below (a deliberately small yamux substitute so the
Python side needs no extra dependency).

### 2.1 Frame format

Every WebSocket message is exactly one binary frame:

| Offset | Size | Field |
| - | - | - |
| 0 | 1 | version = 1 |
| 1 | 1 | type |
| 2 | 4 | stream id (uint32, big endian; 0 = connection-level) |
| 6 | 4 | payload length (uint32, big endian) |
| 10 | n | payload |

Max payload: 262144 bytes (256 KiB). Frames larger than that MUST close the connection
with reason `frame_too_large`.

### 2.2 Frame types

| Type | Name | Direction | Payload |
| - | - | - | - |
| 0x01 | `HELLO` | node → relay | JSON `{"protocol":"fau/1","node_id":str,"agent":str,"capabilities":[str]}` |
| 0x02 | `CHALLENGE` | relay → node | JSON `{"nonce":base64url(32B),"server":str,"protocol":"fau/1"}` |
| 0x03 | `AUTH` | node → relay | JSON `{"node_id":str,"key_id":str,"alg":"ed25519","signature":base64url}` |
| 0x04 | `AUTH_OK` | relay → node | JSON `{"hostname":str,"queued":int,"heartbeat_seconds":int}` |
| 0x05 | `AUTH_FAIL` | relay → node | JSON `{"error":str}` then close |
| 0x06 | `PING` | both | JSON `{"t":epoch_ms}` |
| 0x07 | `PONG` | both | JSON `{"t":epoch_ms}` (echoes `t`) |
| 0x10 | `STREAM_OPEN` | relay → node | JSON `{"kind":"tcp","sni":str,"peer_ip":str}` |
| 0x11 | `STREAM_DATA` | both | raw bytes |
| 0x12 | `STREAM_CLOSE` | both | empty (half-close: no more data from sender) |
| 0x13 | `STREAM_RESET` | both | JSON `{"error":str}` |
| 0x20 | `QUEUED` | relay → node | JSON `{"request_id":str,"received_at":epoch_ms,"envelope":base64url}` |
| 0x21 | `QUEUED_REPLY` | node → relay | JSON `{"request_id":str,"envelope":base64url}` |
| 0x22 | `QUEUED_ACK` | node → relay | JSON `{"request_id":str}` |

Stream ids are allocated by the relay (all streams are relay-initiated) and are
monotonically increasing per connection.

### 2.2.1 `key_id`

Derived from the node's Ed25519 public key, so both sides compute the same value
without exchanging it:

```
key_id = "k_" + hex(sha256(raw 32-byte public key))[:12]
```

Authentication is the signature in §2.3, never the `key_id`. Its purpose is rotation:
after `POST /v1/node/rotate-key` the relay recomputes it, so a `key_id` that disagrees
with the key the relay has on file means the node is still signing with its old key.
That signal is only meaningful because the derivation is shared — a locally invented id
would disagree on every healthy connect.

### 2.3 Signature input for `AUTH`

Ed25519 over the ASCII string:

```
fau/1 tunnel-auth\n<node_id>\n<challenge nonce, base64url>\n<relay server id>
```

### 2.4 Liveness and reconnect

* Relay sends `PING` every `heartbeat_seconds` (default 20). Node replies `PONG`.
  Two missed replies (2 × heartbeat + 5 s) ⇒ relay drops the connection.
* Node also pings if it has seen no relay traffic for `heartbeat_seconds`.
* Node reconnect backoff: 1 s, doubling to 60 s max, ±20 % jitter, reset after a
  connection stays up 60 s.
* Exactly one live tunnel per node id. A successful newer `AUTH` displaces the older
  connection (`STREAM_RESET` on all streams, close reason `replaced`).

### 2.5 Flow control

Sender-side window per stream: 512 KiB of unacknowledged `STREAM_DATA`. The receiver
acknowledges implicitly by consuming; both sides MUST stop reading from their local
socket when the peer's window is full (backpressure), never buffer without bound.

## 3. Relay control API

`https://relay.<domain>` — terminated by the relay. JSON bodies, `application/json`.
All error responses: `{"error": "<code>", "detail": "<human string>"}`.

Rate limits are per source IP and per target email; the relay MUST NOT reveal which
limit was hit (`429 rate_limited`).

### 3.1 `POST /v1/register`

Request: `{"email":"user@example.com","node_pubkey":base64url(ed25519),"box_pubkey":base64url(x25519)}`

Response `202`: `{"registration_id":str,"expires_at":epoch_s,"code_length":6}`

The relay emails a 6-digit code to the address. Codes expire in 15 minutes, 5 attempts,
max 3 outstanding registrations per email per hour.

Registration responses are identical whether or not the address already has a node.

### 3.2 `POST /v1/register/confirm`

Request: `{"registration_id":str,"code":"123456"}`

Response `200`:

```json theme={null}
{
  "node_id": "n_7f3a...",              // random, 128 bits, base32
  "hostname": "n7f3a....relay.example.com",
  "node_token": "rt_...",              // bearer for control API calls
  "acme": {"endpoint": "https://relay.example.com/v1/acme", "username": "...", "password": "..."},
  "heartbeat_seconds": 20
}
```

The directory stores `HMAC-SHA256(relay_secret, lowercase(email))` → node id. The
plaintext email is discarded after the verification code is consumed.

### 3.3 `POST /v1/resolve`

Called by agents. Request: `{"address":"user@example.com"}`

Response `200` — **identical shape for known and unknown addresses**:

```json theme={null}
{
  "relay": "relay.example.com",
  "hostname": "n7f3a....relay.example.com",
  "box_pubkey": "base64url",
  "queue_endpoint": "https://relay.example.com/v1/queue"
}
```

For an unknown address the relay derives a stable decoy from
`HMAC(decoy_secret, address)`: a well-formed hostname that resolves and accepts TCP but
never completes a TLS handshake, indistinguishable from an offline node. `box_pubkey` is
likewise derived. Timing is equalised to the p50 of real lookups.

### 3.4 Offline queue

* `POST /v1/queue/{hostname}` — body
  `{"envelope": base64url, "reply_pubkey": base64url, "request_id"?: str}` where the
  envelope is sealed to the node's `box_pubkey` (libsodium sealed box) and
  `reply_pubkey` is a 32-byte X25519 key the agent also embeds in the sealed
  plaintext. Response `202 {"request_id": str, "expires_at": epoch_s}`. The relay
  cannot read the envelope; it stores `reply_pubkey` for claim challenges and so
  the node can seal the answer to the agent.
* `GET /v1/queue/reply/{request_id}` — when `reply_pubkey` was supplied, the caller
  must prove possession: without `X-FAU-Queue-Claim`, the relay returns
  `401 {"error":"claim_required","challenge":base64url}` (nonce sealed to
  `reply_pubkey`). With a valid claim header, `200 {"envelope": base64url}` when
  the node has answered (envelope sealed to `reply_pubkey`), `204` while pending,
  `404` after TTL. Claims are reusable for `204` and consumed on `200`.
  `?wait=N` long-polls for up to 60 seconds; reply wakeups are per relay process.
* Signature age on queued replay is evaluated as of **queue receive time**, not
  wall-clock replay time (live `/mcp` stays ≤ 300 s window skew).
* Limits: 64 KiB per envelope, 32 envelopes per node, TTL 24 h, at-least-once
  delivery. `request_id` is the idempotency key; the node caches only **terminal**
  replies in `seen_requests` and never re-executes those.

### 3.5 ACME DNS helper (`acme-dns` shaped)

Node authenticates with `acme.username` / `acme.password` (HTTP Basic) issued at
registration; the credential is scoped to `_acme-challenge.<its own hostname>` only.

* `POST /v1/acme/present` — `{"subdomain":str,"txt":str}` → `200 {}`
* `POST /v1/acme/clear` — `{"subdomain":str}` → `200 {}`

The relay never sees the node's certificate private key.

### 3.6 Node self-service (bearer `node_token`)

* `POST /v1/node/rotate-key` — `{"new_node_pubkey":base64url,"signature":base64url}`
  signed by the *current* key over `fau/1 rotate\n<node_id>\n<new_pubkey_b64>`.
* `DELETE /v1/node` — deregister and purge directory entry.
* `GET /v1/node/status` — `{"connected":bool,"queued":int,"server":str}`.

### 3.7 `GET /v1/health`, `GET /v1/transparency`

`/v1/health`: `{"status":"ok","nodes_connected":int,"version":str}`.
`/v1/transparency`: static JSON listing exactly what the relay can observe.

## 4. Agent → node (over the tunnel, TLS terminated by the node)

* `POST /mcp` — MCP Streamable HTTP endpoint. Every request carries
  RFC 9421 signature headers (`Signature`, `Signature-Input`) and, once granted,
  `Authorization: Bearer <capability token>`. A live request may opt into holding
  for an approval with `X-FAU-Wait-Approval: 1` and optional
  `X-FAU-Wait-Approval-Timeout: N`; the node caps the hold at the approval TTL and
  90 seconds. Without the header, `approval_required` returns immediately.
* `GET /.well-known/fau-node` — `{"protocol":"fau/1","node":"<hostname>","auth":"rfc9421+capability"}`.

Signature requirements (RFC 9421):

* Covered components: `@method`, `@target-uri`, `content-digest`, `@authority`.
* Parameters: `created`, `expires` (≤ 300 s), `keyid`, `alg`, `nonce`, `tag="fau-agent"`.
* `keyid` = `<agent-domain>#<key id>` **or** `enrolled:<id>#<key id>` after claim-code
  enrollment (see [https://docs.fau.run/connect/enroll](https://docs.fau.run/connect/enroll)). DNS domains fetch keys from
  `https://<agent-domain>/.well-known/fau-agent` (JWKS-shaped, cached with the
  advertised TTL, min 5 min, max 24 h). Enrolled identities resolve keys from the
  node’s local store only — never over the network.

```json theme={null}
{"domain":"assistant.example","keys":[{"kid":"k1","kty":"OKP","crv":"Ed25519","x":"base64url"}]}
```

* `POST /agent/enroll` (unsigned) — spend a one-time claim code minted on the Mac or
  phone; body `{"claim_code","kid","pubkey"}` → `{"agent_id","keyid",…}`.

* Replay protection: the node rejects a `nonce` it has seen inside the `expires` window
  and rejects `created` skew > 60 s.

## 5. Capability tokens

Biscuit v3 (`biscuit-python` / `biscuit-go`), root key held by the node. Facts sealed
into the authority block:

```
agent("assistant.example");
grant_id("g_...");
tier("structured_read"|"free_form_read"|"raw_read"|"compose"|"send");
category("travel"); category("orders");            // one fact per allowed category
window(2026-01-01T00:00:00Z, 2026-04-01T00:00:00Z); // mail date range
expires(2026-10-17T00:00:00Z);
daily_cap(50);
bound_key("<sha256 of agent public key>");
```

Checks: `check if time($t), $t < expires;` plus tier and category checks added by the
gateway at authorization time. Revocation is by revocation-id list stored in the node
database; the gateway consults it on every request.

## 6. Phone approval API

Served by the node at `/papi/*` (reachable over the tunnel and on the LAN).

* `POST /papi/pair` — `{"pairing_code":"6 digits","device_name":str,"device_pubkey":base64url,"kind":"passkey"|"device_key"}` → `{"node_id":str,"device_id":str}`. The pairing code is shown in the setup wizard QR payload and is valid for 10 minutes, single use.
* `POST /papi/push-token` — device-signed body `{"token":"ExponentPushToken[...]"}` (or `{"token":""}` to clear) → `{"ok":true,"registered":bool}`.
* `GET /papi/pending` — device-signed (see below) → `{"approvals":[Approval]}`.
* `POST /papi/decide` — body `{"approval_id":str,"decision":"once"|"30_days"|"always_category"|"deny"|"send"|"reject","ts":epoch_s,"nonce":str}` plus signature → `{"ok":true}`.
* `POST /papi/pause` — `{"paused":bool}`.
* `GET /papi/activity?limit=` — recent audit entries in phone-friendly form.

Device request signing (simpler than RFC 9421 because both ends are ours): header
`X-FAU-Device: <device_id>`, `X-FAU-Timestamp: <epoch_s>`, `X-FAU-Nonce: <random>`,
`X-FAU-Signature: base64url(ed25519(...))` over:

```
fau/1 device\n<method>\n<target>\n<timestamp>\n<nonce>\n<sha256(body) hex>
```

`<target>` is the request target as it appears on the wire, **query string included**
(`/papi/activity?limit=50`, not `/papi/activity`), so a parameter cannot be altered in
flight. `<sha256(body) hex>` is the hash of the empty string for bodyless requests.

`Approval` object:

```json theme={null}
{
  "id": "ap_...",
  "kind": "access" | "send",
  "agent_domain": "assistant.example",
  "agent_verified": true,
  "match_code": "47",
  "created_at": 1760000000,
  "expires_at": 1760000300,
  "summary": "wants to read your travel email for 30 days",
  "requested": {"tier": "raw_read", "categories": ["travel"], "duration_days": 30},
  "detail": {"question": "...", "thread_subject": "...", "draft": {"to": [], "subject": "", "body": ""}}
}
```

Push notifications go out over Expo Push to each paired phone’s registered
token; the payload contains only the approval id, agent domain and match code —
never mail content. Phones register with `POST /papi/push-token`. Dead tokens
(`DeviceNotRegistered` and similar) are cleared from receipts on the next send.
The dashboard can fire a content-free check with `POST /api/settings/test-push`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.