RELAYLINK

P2P direct and relay fallback

Document ID: DES-011
Status: Implemented (verified across automated matrix, cross-host LAN, and cross-region cloud WAN hole-punching; unreachable paths and symmetric/restricted NATs automatically fall back to same-mode relay)
Version: v1.1.0
Updated: 2026-11-29
Research Date: 2026-11-27

1. Scope and Implementation Summary

In authorized peer access where both endpoints run RelayLink Agents, the Server remains the authority for mapping permissions, admission control, and quotas. When the two Agents can establish a direct path, business traffic flows directly between them; when direct connectivity fails, traffic routes through the same Server relay while strictly preserving the target channel's configured encryption mode. For example, an RDP client always dials 127.0.0.1:<port> on the caller Agent, and the target Agent dials the private host port per channel configuration.

flowchart LR
    A["Caller Agent"] <-->|"Direct: Encrypted QUIC 1.3 or Plaintext ICE-TCP"| B["Target Agent"]
    A <-->|"Fallback: TCP Data Tunnel"| S["RelayLink Server"]
    S <-->|"Fallback: TCP Data Tunnel"| B

Phase-1 capabilities are implemented in v0.1.0-rc.18 per ADR-0043:

  • Control protocol and capability negotiation: Wire v5 adds control frames PeerDirectStart (42) through PeerDirectClosed (52). Register and RegisterAccepted explicitly negotiate peerDirectQuicReady, peerDirectPlainTcpReady, and peerDirectPolicy. Legacy peers or mismatched capability pairs continue using the existing relay.
  • Configuration and routing policy: Channels default to peerRoutingPolicy = "relayOnly". Administrators may enable "preferDirect" only on channels with authorizedClientsOnly=true and applicationProtocol="raw" (TCP and unicast UDP). HTTP/HTTPS and automation loopback channels remain locked to "relayOnly". Server-side peerDirect config governs optional STUN hosting, probe windows, lease durations, and rate limits; Agent-side peerDirect config specifies allowedCidrs, allowedPortRanges, allowedInterfaces, and stunServers.
  • Encrypted and plaintext dual paths: Encrypted direct (quic_encrypted) uses QUIC 1.3 multiplexed onto the same UDP socket (with 0-RTT business data disabled), pinned target certificate SHA-256 verification, and an HMAC-SHA256 access proof. When encryption is explicitly disabled (endToEndEncryptionEnabled=false), plaintext direct (tcp_plaintext) uses ICE-TCP bidirectional binding challenges plus channel access proofs.
  • Suspend-aware monotonic leases and SQLite restart recovery: Agents track initial leases and renewals using suspend-inclusive monotonic clocks (Windows TickCount64, Linux CLOCK_BOOTTIME, macOS CLOCK_MONOTONIC). The Server persists occupancy in SQLite table direct_lease_occupancy prior to issuing the first lease, conservatively waiting a full maximum lease horizon after restart before reclaiming stale occupancy (server_restart_lease_expired).
  • Admin UI and observability: AdminWeb and AgentWeb surface Prefer Direct, Direct QUIC, Direct TCP, and audit transportPath, deduplicating caller-reported direct bytes by monotonic reportSeq.
Ingress Type Current Implementation Behavior
Encrypted authorized raw TCP (preferDirect) Attempts QUIC 1.3 direct when both ends advertise peerDirectQuicReady; falls back automatically to encrypted relay if capabilities are missing or candidates exhaust
Encrypted authorized unicast UDP (preferDirect) Creates an independent session per source; direct path forwards 4-byte length-framed datagrams over a reliable QUIC stream, falling back to encrypted UDP relay
Plaintext authorized raw TCP (preferDirect) Forwards business bytes over mutually bound ICE-TCP direct connections; falls back to plaintext TCP relay when unreachable
Plaintext authorized unicast UDP (preferDirect) Each source session uses an independent ICE-TCP direct connection with 4-byte datagram framing; falls back to plaintext UDP relay when unreachable
Authorized HTTP/HTTPS and automation channels Locked to mandatory inner TLS and relayOnly; HTTP/HTTPS preserves ingress context proofs and Host/Origin rules
Cloud apps or public browsers hitting Server ports Handled directly by the Server over standard relay tunnels (no caller Agent participates in negotiation)

2. Control Frames and 7-Step Establishment State Machine

All new v5 direct control frames (42..52) travel exclusively over authenticated control TLS connections:

Frame ID Name Direction and Role
42 PeerDirectStart Server -> Both: distributes PeerRelayBinding, attemptSeq, directMode, serverChallenge, probe/lease parameters, and ephemeralBindKey (plaintext) or targetCertificateSha256 (encrypted)
43 PeerDirectCandidates Both -> Server -> Peer: exchanges validated IP/port candidates and ICE credentials for the attempt
44 PeerDirectReady Both -> Server: reports handshakeId and directPath bound to the single authenticated underlying transport
45 PeerDirectLeaseGrant Server -> Both: grants initial lease or renewal (leaseId, serverNonce) after committing start audit and direct_lease_occupancy
46 PeerDirectPrepare Server -> Target: authorizes target dial with a fresh random preparationId once both peers confirm the initial lease
47 PeerDirectTargetReady Target -> Server -> Caller: signals target socket/dial readiness via control TLS so caller can release buffered bytes or UDP first packets
48 / 49 PeerDirectCancel / PeerDirectCancelAck Mutually confirms clean pre-grant cancellation of the direct attempt and reports whether the target dialed
50 PeerDirectLeaseRenew Caller -> Server: renews active lease with monotonic reportSeq and cumulative per-direction direct byte counters
51 / 52 PeerDirectRevoke / PeerDirectClosed Server-initiated revocation or endpoint-reported close with final byte counters

Connection Establishment Flow

  1. Authorization: Caller submits requestId and mappingId. Server authenticates the caller from its session, verifies mapping, target channel, encryption mode, online status, and quotas, and allocates one connectionId shared across direct and fallback attempts. Direct negotiation starts only when both Agents advertise matching capability.
  2. Candidate discovery: Both Agents exchange candidates and short-lived ICE credentials over control TLS. Encrypted paths gather UDP candidates and may query the Server-hosted RFC 8489 STUN endpoint from the exact UDP socket reserved for QUIC. Plaintext paths gather TCP candidates separately. Control-socket source ports and cross-protocol endpoints are never accepted as data candidates.
  3. Connectivity checks: Agents probe only candidates matching the channel mode within strict count and timeout budgets. Private LAN candidates are usable when explicitly permitted by policy; reachable IPv6 addresses may also participate. Plaintext mode pairs active and passive ICE-TCP candidates and falls back if neither side exposes a reachable passive listener, without assuming cross-platform TCP simultaneous open (RFC 8445, RFC 6544 §3).
  4. Peer verification: Encrypted paths establish QUIC 1.3 over the selected UDP pair, pin the target's exact certificate SHA-256 fingerprint, and verify the channel accessSecret HMAC proof inside the TLS 1.3 stream (ADR-0011, RFC 9001). Plaintext paths verify the ephemeral binding key challenge and channel access proof over the selected TCP connection. Both bind identities, roles, sessions, mapping, channel, protocol, encryption mode, connectionId, attemptSeq, and random nonces.
  5. Single-connection binding (Ready): Only one transport connection per attempt may complete authentication. Both peers generate fresh nonces, incorporate role-sorted nonces plus step-4 context into an identical handshakeId, bind it permanently to that specific QUIC/TCP connection and stream, and send PeerDirectReady (44). Changing handshakeId for the same role or mismatching between peers aborts the connection immediately with zero fallback.
  6. First-lease commit and dial gate: The Server serializes authorization checks, config version verification, start audit commit, and direct_lease_occupancy persistence inside one SQLite transaction before issuing PeerDirectLeaseGrant (45). Only when both peers acknowledge valid initial leases under active authorization does the Server issue PeerDirectPrepare (46) to allow target TCP dialing or UDP socket setup (duplicate instructions do not re-dial; single-sided lease delivery yields zero target dials; ADR-0013).
  7. Target readiness confirmation: Once the target socket is ready, the target echoes the one-time preparationId in PeerDirectTargetReady (47) over control TLS. The Server validates and relays confirmation to the caller; only if local state and the initial lease remain valid does the caller flush TCP bytes or hand off the UDP queue. Raw data bytes never advance state, and target dial failure or revocation immediately closes the connection.

Each business TCP connection owns one dedicated peer stream (QUIC 0-RTT business data disabled; plaintext uses the authenticated TCP socket), preserving bounded backpressure and unidirectional half-close. Idle timers track business payload activity rather than transport keepalives (RFC 9000).

3. Plaintext Security Boundary and Unicast UDP Direct

Plaintext Direct Authentication and Visibility

For each plaintext direct attempt, the Server delivers a short-lived ephemeralBindKey over both authenticated TLS control sessions. Over the chosen TCP socket, caller and target perform mutual challenge-response authentication proving possession of the ephemeral key, while the target also verifies the caller's channel accessSecret HMAC-SHA256 proof using distinct domain separation prefixes. Keys never cross the plaintext wire and bind tokens are single-use. Passive listeners open strictly during the probe window, cap unauthenticated accepts (maxUnauthenticatedPlaintextTcpAccepts, default 16), and close listeners plus losing sockets once routing resolves. Application bytes share the verified TCP connection with ICE checks using ICE-TCP framing (RFC 6544 §10).

Challenge-response protects connection authorization only. RelayLink provides no confidentiality or tamper protection on plaintext payloads: path observers can read payloads and active attackers can modify them. Enable plaintext preferDirect only when both direct and relay network segments are trusted and isolated, or when the application protocol itself enforces encryption and authentication (ADR-0016).

Unicast UDP Direct

  • Per-source sessions and queuing: Local UDP ingress isolates sessions by (source IP, source port). Each source session owns a dedicated connectionId, QUIC/TCP stream, and target UDP socket. The first packet and subsequent arrivals during setup enter one 32-datagram bounded queue (newest dropped on overflow). If the attempt falls back prior to grant, the winning relay path takes ownership of that queue once so the first packet is never duplicated.
  • Framing and idle cleanup: Direct streams preserve the 4-byte big-endian length + 0–65507-byte payload framing (0 is a valid empty datagram); out-of-range lengths or truncated records terminate the session. Successful forwarding in either direction resets udpIdleTimeoutSeconds; UDP has no half-close. See REQ-001L.
  • Reliable stream tradeoff: Both encrypted and plaintext direct UDP use reliable streams to reuse existing framing and avoid .NET 10 System.Net.Quic limitations (no public RFC 9221 DATAGRAM API and path-MTU framing constraints; .NET 10 QuicConnection, RFC 9221 §5), accepting head-of-line retransmission delay within a source session on lossy links.

4. Fallback State Machine, Lease Recovery, and Probe Budgets

When Fallback Is Permitted

Condition Connection Handling
Channel is relayOnly, peer lacks direct capability, missing local dependency (e.g., libmsquic), or zero permitted candidates Starts directly on the relay when both ends support the business protocol; rejects if either peer lacks protocol support
Mode-matching candidates exhausted and unreachable before grant When both control sessions are healthy, PeerDirectCancel/CancelAck confirms clean cancellation without auth errors, and no grant was issued, switches to same-mode relay within the remaining setup budget
Pinned fingerprint mismatch, invalid access proof, auth/config change, handshake mismatch, or audit gate failure Terminates immediately with zero target dial and zero relay fallback
Initial lease already granted, ambiguous grant outcome, target dial failure, or mid-session drop Closes logical connection and drops remaining queues without replaying bytes or datagrams across paths (TCP apps reconnect; UDP starts a new session on next datagram)

Under high-RTT or concurrent cancellation races, thread-safe disposed guards and SafeCancel in PeerDirectAgentAttempt prevent ObjectDisposedException and keep control sessions connected across fallback transitions.

Revocation, Suspend-Aware Leases, and Restart Recovery

  • Revocation: Disabling clients, deleting mappings, changing channel configs, or admin disconnects cancel pending grants, halt renewals, and emit PeerDirectRevoke (51) so both Agents immediately tear down local business sockets and direct transports (ADR-0009).
  • Suspend-aware monotonic clock: Before sending its first PeerDirectReady, each Agent snapshots a suspend-inclusive monotonic clock (Windows TickCount64, Linux CLOCK_BOOTTIME, macOS CLOCK_MONOTONIC) to anchor initial and renewal lease deadlines without requiring cross-host clock sync. After OS resume, expired requests and leases are invalidated before any I/O; platforms unable to guarantee suspend accounting do not advertise direct capability.
  • SQLite restart occupancy recovery: Before issuing the first lease, the Server commits direct_lease_occupancy (Server instance, connectionId, clients/sessions, channel, quota units, and frozen max lease duration) alongside the start audit. On restart, a single-instance Server reconstructs global, per-client, and per-channel occupancy before admitting new shared-quota connections, waits conservatively for each record's full max lease duration plus skew margin from the local monotonic moment the new instance assumes exclusivity, and then clears occupancy idempotently with server_restart_lease_expired.
  • Metering and UI: Callers report cumulative per-direction direct bytes in PeerDirectLeaseRenew (50) and PeerDirectClosed (52) deduplicated by reportSeq; unconfirmed tail bytes between the last report and close are recorded as unknown rather than zero-filled. AdminWeb and AgentWeb display Prefer Direct, Direct QUIC, Direct TCP, and audit transportPath (Audit & Traffic Design).

Probe Allowlist and Cross-Session Budgets

Before sending any UDP probe or TCP SYN, the probing Agent enforces strict policy validation:

  • Destination allowlist: Accepts IP literals only (unmapping IPv4-mapped IPv6 addresses first) with deny-first rules blocking unspecified, loopback, broadcast, multicast, link-local (including scoped IPv6), and site-excluded endpoints. Public reflexive candidates require verified binding on a trusted STUN server correlating observed source endpoint, control session, and attempt; private LAN direct paths require explicit allowedCidrs, allowedPortRanges, and allowedInterfaces (overlapping non-attributable ranges are skipped; peer-advertised interface metadata never expands local policy).
  • Cross-connection budgets: Deducts rate and concurrency budgets across connections per authenticated peer identity (maxProbesPerMinutePerPeer default 60, maxConcurrentProbesPerPeer default 8) and per normalized destination IP (maxProbesPerMinutePerDestIp default 30, maxConcurrentProbesPerDestIp default 4). Changing connectionId, reconnecting, or rotating ports never resets budgets. If zero candidates qualify up front, zero probes are sent and the Server can authorize same-mode relay directly (RFC 6544 §12).

5. Compatibility, Verified Boundaries, and Acceptance Matrix

On Linux, encrypted QUIC direct transport requires native libmsquic; when libmsquic is absent, Agents automatically downgrade peerDirectQuicReady to false while continuing to support peerDirectPlainTcpReady and encrypted Server relay (.NET QUIC platform dependencies). JsonProtocolSerializer strips new policy fields for legacy v3/v4 Agents; v4+ Agents lacking direct capability use same-mode UDP/TCP relay, and v3 endpoints reject UDP while keeping TCP compatibility (ADR-0025).

Verified Scope and Honest Boundaries

Validated on the v0.1.0-rc.18 release baseline (full evidence in Verification Status):

  • Automated regression: .NET Release unit tests 404/404, peer-TLS real-process integration tests 137/137, AdminWeb 20/20, and AgentWeb 9/9 passing.
  • Cross-host LAN verification (Windows <-> Ubuntu 24.04, libmsquic 2.6.4): Verified direct_quic and direct_tcp for TCP and 0/1/32769/65507-byte unicast UDP (zero relayed bytes on the Server data port), real-time admin revocation, and automatic same-mode fallback when allowedCidrs is empty.
  • Cross-region cloud WAN hole-punching (Tokyo Ubuntu 24.04 <-> Silicon Valley Ubuntu 26.04, libmsquic 2.6.4): Verified trans-Pacific direct_quic TCP and unicast UDP (0/1/32769/65507 B) hole-punching with firewalls allowing only control/data ports and STUN UDP (no ephemeral high UDP ports opened), automatic relay fallback for unexposed plaintext tk-p-tcp, and live admin connection revocation.
  • Restricted/proxied NAT fallback (local Windows -> Silicon Valley / Tokyo): Verified clean automatic fallback to inner-TLS relay when proxy egress drops UDP mappings, with zero ObjectDisposedException or control-session reconnects.
  • Explicit boundary: When both endpoints sit behind non-cone symmetric NATs or UDP-blocked egress firewalls, RelayLink automatically falls back to same-mode relay within the configured probe budget rather than guaranteeing 100% traversal.
Scenario Expected Observation
Encrypted/plaintext x TCP/unicast UDP x direct/fallback All 8 combinations pass confidentiality/readability checks, audit transportPath, and pre-grant audit gating
Default encryption, HTTP/HTTPS, automation channels Defaults stay encrypted; HTTP/HTTPS and automation channels enforce relayOnly and inner TLS
Plaintext candidates unreachable while UDP reachable, missing capability, cross-mode replay Never steals other mode's path; invalid proof/replay yields zero fallback and zero target dial; mode switch revokes active sessions
LAN, IPv6, and dual independent NAT hole-punching Logs selected candidate type and lossless large-stream transfers; Server data port carries zero direct bytes; TCP half-close delivers trailing responses
Concurrent unicast UDP sources, queue overflow, and fallback 0/1/32769/65507 B datagram boundaries and source isolation hold; fallback never duplicates queued first packets; 32-datagram overflow drops newest
UDP blocked, restricted NAT, and STUN unavailable Probes only permitted transport; falls back cleanly within budget and prepares target business socket at most once
Mixed versions (v3/v4/legacy v5) Peers without direct capability use same-mode relay; v3 rejects UDP while passing TCP regression and legacy digests
Wrong fingerprint, wrong proof, cross-session replay, audit failure Logical connection rejected with zero target dial; neither plaintext nor relay bypasses rejection
Probe timeout vs. readiness race, lost grant, mid-stream drop At most one active path and one target dial; zero payload replay; clean task, buffer, and quota release
Mapping revocation, manual disconnect, silent partition, Server restart Known disconnects close immediately; silent partitions halt before lease ceiling; other Server profiles stay unaffected
Single-sided initial lease, expired late grant, OS suspend past lease Target never receives PeerDirectPrepare without dual confirmation; expired instructions never dial or dequeue
Multiple reachable candidates with swapped Ready receipts handshakeId mismatch aborts with zero target dial and zero relay fallback; duplicate identical receipts are idempotent
Plaintext/new-capability fallback with target fail, stale data-stream ready byte, late control ready Caller withholds local business bytes and UDP queue until valid confirmation; legitimate early server greetings deliver intact
Disallowed destinations (loopback, link-local, overlapping private CIDRs) and cross-connection probe floods Zero outbound probes to denied addresses; per-peer and per-dest-IP budgets persist across new connections and port rotations
Global MaxConnections=1 silent partition across consecutive Server restarts New requests blocked while conservative lease horizon holds; post-expiry cleanup logs server_restart_lease_expired with unknown tail bytes
One peer reports unreachable while peer reports auth failure or unconfirmed cancel Logical connection aborts with zero fallback; relay fallback occurs only after mutually confirmed non-auth cancellation

Repository source