Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions docs/adr/0009-lan-offline-signaling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# ADR 0009: LAN signaling between SonicRelay clients without RelayControl

- Status: Accepted
- Date: 2026-11-17
- Issues: RelayControl #40 (architecture), desktop_dotnet_SonicRelay #75 (implementation)

## Context

Every SonicRelay session used to depend on RelayControl for discovery, session creation and
signaling. A publisher and a viewer on the same desk could not stream when the internet, the API
or coturn was down. Issue #40 approved a LAN/intranet mode; this ADR records that decision and the
refinements made while implementing it (#75), including the owner's priority order.

## Decision

Discovery, signaling transport and media/ICE policy are **separate decisions**:

| Concern | Options, in priority order |
| --- | --- |
| Discovery | mDNS/DNS-SD on the link (or through a reflector / unicast DNS-SD) → QR code or typed `address:port` + code → remembered endpoints of a paired desktop |
| Signaling | The desktop's own authenticated TLS host (`/lan/v1/signaling`) → RelayControl's existing WebSocket |
| Media | WebRTC/Opus P2P with host candidates → (cloud-signaled only) srflx → TURN as last resort |

Each client has a local `connectivityMode`:

- `auto`: LAN first for paired desktops; RelayControl otherwise, decided **before** the session
starts. A live session is never migrated between transports.
- `lanOnly`: RelayControl, STUN and TURN are never contacted. LAN-signaled peers use
`iceServers: []`.
- `cloudOnly`: the previous behaviour.

RelayControl stays a control plane (ADR 0001): it is not contacted in LAN sessions and never
becomes a media relay. When it carries the signaling, ICE still prefers a direct pair, so audio
between two LAN devices stays local even when the signaling went through the internet.

The desktop hosts LAN signaling and plays the backend's session roles for LAN viewers
(`session.joined`, authoritative `participant.capabilities`, `from` stamping, reconnect grace,
`session.ended`). In `auto` a desktop session is dual-homed: the same session id is reachable
through RelayControl and the LAN host.

### Security model

- mDNS/DNS-SD is discovery only. TXT records carry `v=1` and a non-identifying 6-hex hint — no
name, pin or credential.
- The desktop identity is a self-signed ECDSA P-256 certificate. Phones pin SHA-256 of its DER,
learned from the QR code or (for a typed code) a 40-bit prefix verified during the 120 s window.
- Pairing secrets are single-use, expire in 120 s, close after 5 failures, are compared in constant
time and rate-limited per address.
- Pairing issues a per-device 256-bit LAN credential; the desktop stores only its hash. The API
bearer token is never reused as a peer credential, and there is no custom cryptography.
- Trust is revocable locally. A revocation made in the cloud cannot reach a desktop while the
devices are offline; users revoke locally as well.

## Consequences

- RelayControl needs no runtime change. The protocol is specified in
[`protocol/lan-signaling-v1.md`](../protocol/lan-signaling-v1.md) and implemented by both clients.
- **Negative case:** remote signaling cannot bypass a missing IP route or blocked UDP between the
devices. Then TURN (cloud) or a network change is required; clients must report it
(`ice.no_direct_route`) rather than claim a P2P path.
- mDNS does not cross routers. Routed subnets rely on QR/typed bootstrap, an mDNS reflector, or
operator-published unicast DNS-SD records.
- The desktop opens an inbound listener as the current user (no elevation, no firewall changes);
the OS may prompt once.

## Rejected alternatives

- **A local copy of the API/database on the desktop:** duplicates the domain and its migrations.
- **Four separate WebRTC session types, one per priority level:** the levels differ in discovery
and signaling only; media is the same WebRTC session.
- **Mutual TLS for phones:** generating and storing client certificates in Dart on Android/iOS is
fragile; pinned server TLS plus a revocable per-device credential gives the same guarantees.
- **`HttpListener` on Windows:** HTTPS requires admin URL ACL and certificate binding.
1 change: 1 addition & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,4 @@ flowchart TD
- [ADR 0005: Symmetric device credentials with a parallel DeviceBearer scheme](adr/0005-device-identity-credentials.md) — extended in Phase 2 to sessions, signaling and TURN credential issuance
- [ADR 0006: Remove ASP.NET Core Identity and owner-scoped Device CRUD](adr/0006-remove-identity.md)
- [ADR 0007: Model bidirectional audio as a session mode with backend-owned publish permission](adr/0007-duplex-audio-sessions.md)
- [ADR 0009: LAN signaling between SonicRelay clients without RelayControl](adr/0009-lan-offline-signaling.md) — protocol: [LAN signaling v1](protocol/lan-signaling-v1.md)
118 changes: 118 additions & 0 deletions docs/protocol/lan-signaling-v1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# LAN signaling protocol v1

Status: implemented by SonicRelay Desktop (publisher, host) and SonicRelay Mobile (viewer, client).
Decision record: [ADR 0009](../adr/0009-lan-offline-signaling.md). RelayControl is not involved.

## Transport and identity

- HTTPS/WSS (TLS 1.2+) served by the desktop on an automatic port (remembered across runs) or a
user-fixed port ≥ 1024, on every interface.
- Server certificate: self-signed ECDSA P-256, 5-year validity.
- **Pin** = base64url, no padding, of SHA-256 over the certificate DER. Clients accept no CA and
no other certificate.
- Limits: 16 connections, 8 KiB request headers, 4 KiB pairing body, 64 KiB WebSocket message,
10 s handshake. Five failed pairing/auth attempts per remote address per minute → `429` for 60 s.
- Only the two routes below exist; anything else is `404`. There is no unauthenticated info route.

## Pairing window and codes

The desktop opens one window at a time: `pid` (GUID), 80-bit `secret`, TTL **120 s**, single use,
closed after **5** failed attempts.

### QR payload v2

```json
{
"v": 2,
"cloud": { "challengeId": "<guid>", "code": "<cloud pairing code>" },
"lan": {
"pid": "<guid>",
"sec": "<base64url 10 bytes>",
"pin": "<base64url sha256(cert DER)>",
"did": "<publisher device id, guid>",
"name": "<desktop name>",
"ep": ["192.168.1.20:47321", "[fd00::20]:47321", "desk.local:47321"]
}
}
```

Either block may be absent, never both. `ep` lists at most 4 entries (`host:port`, IPv6 bracketed),
Ethernet first, VPN/tunnel last, then `<hostname>.local`. A payload without `v` is the legacy
cloud-only `{challengeId, code}`.

### Typed code

16 Crockford base32 characters shown as `XXXX-XXXX-XXXX-XXXX`, encoding 80 bits: the first 5 bytes
of the pin digest followed by the first 5 bytes of the secret. Decoding is case-insensitive,
ignores spaces and `-`, and maps `O→0`, `I/L→1`. The client accepts a certificate during pairing
only if its digest starts with the typed prefix, and stores the full pin returned by the desktop
only if it matches both the prefix and the certificate actually presented.

Test vector: pin `A5BYxvLAy0ksUzsKTRTvd8wPeKvMztUofYShogEc-4E` (SHA-256 of bytes `01 02 03`) and
secret `10 20 30 40 50 60 70 80 90 A0` → `0E85-HHQJ-20G3-0G2G`.

## `POST /lan/v1/pair`

Request (JSON): `{ pid, sec }` **or** `{ code }`, plus `viewerDeviceId` (GUID), `viewerName`,
`platform` (each ≤ 128 chars).

| Status | Body | Meaning |
| --- | --- | --- |
| 200 | `{ credential, publisherDeviceId, publisherName, pin }` | Paired. `credential` is 256-bit base64url; the desktop stores only SHA-256 of it. Re-pairing replaces the previous credential. |
| 400 | `{ "error": "pairing_invalid" }` | Wrong/reused secret or code, malformed body, no open window. |
| 410 | `{ "error": "pairing_expired" }` | Window older than 120 s. |
| 429 | `{ "error": "rate_limited" }` | Too many failures from this address. |

## `GET /lan/v1/signaling` (WebSocket)

Headers: `Authorization: SonicRelay-Lan <credential>`, `X-SonicRelay-Device: <viewerDeviceId>`.

Messages use the cloud signaling envelope `{ type, sessionId, to?, from?, payload? }` and the same
types (`viewer.ready`, `webrtc.offer|answer|ice_candidate|renegotiate`, `participant.*`,
`session.*`, `ping`/`pong`). The desktop hub plays the backend's roles:

- On connect it sends the viewer its own `session.joined` (no `from`) and the publisher's
`session.joined` (`from` = publisher id, `role: publisher`); the viewer answers `viewer.ready`.
- It **stamps `from`** on every viewer message; a client-supplied `from` is ignored.
- Viewers may only send `viewer.ready`, `webrtc.*` addressed `to` the publisher, `participant.capabilities`,
`participant.audio_state_changed` and `ping`. Anything addressed to another viewer, to another
session, or of another type is dropped.
- It is the only authority for `participant.capabilities`: `audioSendAllowed` starts `false`
and `canSendAudio` is clamped to `false` until the publisher grants it (duplex).
- A dropped socket emits `participant.disconnected`; reconnecting within **30 s** emits
`participant.reconnected`, otherwise `session.left`.
- Ending the session sends `session.ended` then closes with `4410`.

| Close code | Meaning | Client action |
| --- | --- | --- |
| 4401 | Unknown device or wrong credential | Stop; pair again |
| 4403 | Revoked | Stop; pair again |
| 4409 | No live session, or full | Stop; report |
| 4410 | Session ended | Stop |
| 1009 | Message over 64 KiB | — |

Clients retry other closes at most 5 times, then report `lan.unreachable`.

## mDNS / DNS-SD

| Service | Announced by | TXT |
| --- | --- | --- |
| `_sonicrelay._tcp` (instance `SonicRelay-<hint>`, SRV port = host port) | Desktop | `v=1`, `id=<hint>` |
| `_sonicrelay-viewer._tcp` (instance `SonicRelay-<hint>`) | Phone, while in the foreground | `v=1`, `id=<hint>` |

`hint` = first 6 hex characters of SHA-256 over the UTF-8 device id. It only helps a client guess
which paired device it sees; identity is proven by the pinned TLS handshake.

Operators can make routed subnets discoverable with unicast DNS-SD:

```text
_sonicrelay._tcp.<domain>. PTR SonicRelay-<hint>._sonicrelay._tcp.<domain>.
SonicRelay-<hint>._sonicrelay._tcp.<domain>. SRV 0 0 <port> <desktop-host>.<domain>.
SonicRelay-<hint>._sonicrelay._tcp.<domain>. TXT "v=1" "id=<hint>"
```

## ICE

LAN-signaled peers use `iceServers: []` and `iceTransportPolicy: all` on both sides, in every
connectivity mode. If signaling succeeds but ICE fails, the media path is blocked (firewall, ACL,
client isolation) and clients report `ice.no_direct_route`.
36 changes: 36 additions & 0 deletions docs/superpowers/plans/2026-11-17-lan-offline-signaling-docs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# LAN / Offline Signaling (RelayControl docs) Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Record the LAN/offline decision that #40 approved but never committed, and publish the canonical LAN signaling protocol both clients implement.

**Architecture:** Documentation only. RelayControl's runtime does not change: in LAN mode it is not contacted; in Auto/Cloud it keeps signaling as today and never becomes a media relay.

**Tech Stack:** Markdown.

**Spec:** desktop_dotnet_SonicRelay `docs/superpowers/specs/2026-11-17-lan-offline-signaling-design.md`

## Global Constraints

- Values (routes, headers, close codes, TTLs, sizes, QR v2 shape, manual code layout, mDNS records) copied verbatim from the spec; the protocol doc is the single source both clients link to.

## Review Focus

1. The ADR must state the negative case: remote signaling cannot bypass a missing IP route or blocked UDP.
2. The protocol must state which side stamps `from` (the LAN host) and that viewer-to-viewer messages are dropped.
3. The cloud-revocation-offline limit is documented.
4. ADR index/links (`docs/architecture.md`, `docs/protocol.md`) point to the new files.
5. Naming follows `docs/naming.md` (`SonicRelay`).

---

### Task 1: ADR 0009 and LAN protocol v1

**Files:**
- Create: `docs/adr/0009-lan-offline-signaling.md` (context, decision: discovery/signaling/media separated, priority order, Auto/LAN only/Cloud only, RelayControl stays control-plane-only, security model, consequences, rejected alternatives)
- Create: `docs/protocol/lan-signaling-v1.md` (routes, payloads, headers, close codes, QR v2, manual code, mDNS/DNS-SD records incl. unicast DNS-SD operator records, host emulated messages, limits, security properties)
- Modify: `docs/architecture.md`, `docs/protocol.md` (links)

- [ ] Step 1: write both documents from the spec.
- [ ] Step 2: verify every relative link resolves (`rg -o "\]\(([^)]+\.md)" docs` and check each file exists).
- [ ] Step 3: commit `docs: ADR 0009 and LAN signaling protocol v1 (SonicRelay #75)`.
Loading