RELAYLINK

Secure Agent-to-Agent access

Document ID: DES-002
Status: Draft
Version: v1.15.0
Updated: 2026-11-29
Research Date: 2026-09-17

1. Scope and Overview

Authorized peer access lets a caller Agent expose controlled 127.0.0.1 loopback listeners so local applications or SDKs can reach private services behind a target Agent:

  • Default relay and opt-in P2P direct: Channels default to peerRoutingPolicy = "relayOnly", routing peer traffic through the Server frame relay. For authorizedClientsOnly=true channels using applicationProtocol="raw" (TCP or unicast UDP), administrators can opt in to "preferDirect" so Agents attempt authenticated encrypted QUIC 1.3 or plaintext ICE-TCP direct transport when probe policies allow, falling back automatically to the same encryption mode over the Server relay if direct connectivity fails. See Peer Direct & Relay Fallback (DES-011) for direct negotiation, probe budgets, and lease recovery.
  • HTTP/HTTPS peer access: Specified in REQ-001N, DES-008, and ADR-0026. The target Agent terminates peer HTTP via an in-process YARP/Kestrel virtual host after inner TLS and access-proof verification, supporting Host/Origin rewriting and nested browser HTTPS. HTTP peer access forbids disabling inner encryption and enforces relayOnly. The optional encryption and framing rules below govern raw TCP and unicast UDP; HTTP capability fields, proof contexts, and readiness markers must never be silently applied to legacy peers.

Control connections (Register / ConfigUpdate) distribute configuration separately from data connections (:7444). Whereas standard Open / BindData copies plaintext TCP bytes through the Server, authorized peer access verifies caller authorization and applies channel-configured end-to-end encryption or explicit plaintext mode.

Following TLS 1.3 (RFC 8446) and .NET SslStream, RelayLink layers an inner SslStream over the Agent-to-Agent framed stream by default rather than inventing custom cryptography. Certificate validation never unconditionally returns true: the caller Agent pins the target's exact SHA-256 certificate fingerprint. Administrators may explicitly disable inner TLS on raw TCP/UDP peer channels; access-key proofs remain mandatory, but business payloads are copied unencrypted and become visible to the Server and data-path observers. Because access secrets travel inside control snapshots, enabling peer access strictly requires Agent-to-Server control-plane TLS. Data ports (:7444) do not add outer TLS; binding tokens and metadata rely on trusted network boundaries. See ADR-0008 and ADR-0016.

2. Configuration Model and Identity

Server-side client files support the following incremental fields (missing fields preserve legacy defaults; see client.example.json for standard channel layout):

channels[].authorizedClientsOnly       : bool (default false)
channels[].endToEndEncryptionEnabled : bool (default true; applies when authorizedClientsOnly=true)
channels[].accessSecret              : Base64, exactly 32 bytes (required in authorized mode)
channels[].peerRoutingPolicy         : "relayOnly" (default) | "preferDirect" (authorized raw TCP/UDP only)
e2eCertificateSha256                 : Client-level 64-hex fingerprint pinned on first authenticated Agent register
outboundMappings[]:
  mappingId                          : Generated by Server as "<targetClientId>-<targetChannelId>" (legacy IDs remain supported)
  enabled                            : bool
  localAddress                       : Fixed 127.0.0.1
  targetClientId                     : Existing enabled target client ID
  targetChannelId                    : Target client's enabled authorized channel ID
  accessSecret                       : Base64 secret matching the target channel
  targetCertificateSha256            : Pinned target E2E certificate fingerprint

Certificate Pinning and Key Boundaries

  • Server generation and distribution: When authorized mode is enabled, the Server generates a high-entropy 32-byte random accessSecret. Each Agent reports its E2E certificate fingerprint during authenticated registration, and the Server pins it at the client level (e2eCertificateSha256) on first sight. When an admin adds an outbound mapping, the Server copies the target channel secret and pinned fingerprint into the caller Agent's configuration. High-security deployments should still verify fingerprints out-of-band using the Agent CLI output (ADR-0011). Never commit real secrets to repository examples.
  • Agent-local identity state: Local Agent configs store only Server connection details, client ID/secret, control TLS CA trust, and reconnect timers—never mappings or target access secrets. Each Agent auto-generates its E2E certificate private key as a local PFX in its config directory, protected by Windows current-user ACLs or Unix 0600 permissions. Run RelayLink.Agent --config <path> --show-e2e-fingerprint to print the local SHA-256 fingerprint for out-of-band verification. New certificates must never silently overwrite an already pinned fingerprint; legacy per-channel fingerprint fields are no longer supported. Multi-server Agents isolate identities per profileId (see Multi-Server Agent Design).
  • Platform key loading: Windows Schannel loads the PFX private key into the current-user key provider at runtime without requiring system certificate-store installation; Linux loads the same PFX with ephemeral in-process keys protected by 0600 directory and file permissions.

Port Ownership and Admin API Rules

  • Agent-owned loopback ports: outboundPortRangeStart / outboundPortRangeEnd default to 20000–59999. On first bind, the Agent selects a free port in range and persists the mapping-to-port assignment in <clientId>.ports.json. Subsequent restarts prefer the saved port and fall back to scanning for another free port with atomic file replacement (retrying briefly on Windows if UnauthorizedAccessException or IOException occurs from transient file locks, and dropping only that mapping if retries exhaust). Legacy Server-side localPort fields are read only for historical configs and never distributed.
  • Validation and redaction: The Server validates target references, matching secrets, matching pinned fingerprints, and prevents an authorized channel from simultaneously opening a public cloud-proxy listener. Access secrets never appear in anonymous APIs, traffic history, or logs; certificate fingerprints may be displayed as non-secret metadata in authenticated admin views and client status queries. Protected Admin APIs can generate and save secrets without echoing them back.
  • Create-only mappings: The Admin API for creating outbound mappings accepts only targetClientId and targetChannelId (defaulting to enabled, with no caller-supplied custom ID or enable override). Secrets and fingerprints are read from disk under the same write lock so stale memory copies cannot leak. Mappings are immutable: edits require delete-and-recreate (which revokes active connections and may allocate a new loopback port). Legacy custom mapping IDs remain readable and deletable.

3. Relay Protocol and Handshake State

Using the NTP1 magic, the wire protocol is currently at version 5: v3 added endToEndEncryptionEnabled, v4 added transportProtocol confirmation and UDP snapshots, v5 added HTTP context, relayControlReady, and mappingEncryptionStatus, and v0.1.0-rc.18 added P2P direct control frames 42–52 (see DES-011).

Newer Servers stay compatible with v3 Agents for TCP peer access, locking headers per session version and stripping UDP fields/digests for v3 snapshots. Unicast UDP requires both ends to be v4 or later (returning ChannelUnavailable otherwise); unknown versions and mid-session version switches are rejected (ADR-0025). HTTP peer access requires v5.

Frame Direction Purpose
PeerOpenRequest Caller Agent -> Server (control) requestId and mappingId (no business bytes or plaintext secrets)
PeerOpen Server -> Target Agent (control) One-time connectionId, caller clientId, target channel, encryption mode, target bind token, setupTimeoutMilliseconds
PeerOpenGranted Server -> Caller Agent (control) connectionId, encryption mode, caller bind token, setupTimeoutMilliseconds
PeerOpenRejected Server -> Caller Agent (control) Rejection reason code
PeerBindData Both Agents -> Server (data) Session ID, connectionId, role, and one-time random token (consumed at most once)
PeerBindAccepted Server -> Both Agents (data) Confirms both data tunnels are paired and enters frame relay mode
PeerRelayAuthenticated / PeerRelayPrepare Both -> Server / Server -> Target (control TLS) Confirms matching raw peer auth receipts before instructing the target to dial
PeerRelayTargetReady / PeerRelayAborted Target -> Server -> Caller / Either -> Server (control TLS) Confirms target readiness or aborts the attempt; caller holds TCP bytes or UDP first packets until ready
PeerMappingStatus Caller Agent -> Server (control) Current session, confirmed config version, bound mapping IDs, and loopback ports (no secrets)
Data / Fin / Reset Agents <-> Server (data) Forwards encrypted TLS records or plaintext payloads and stream termination signals

Authentication and Access Proofs

  1. Server-side authorization: The caller Agent authenticates via its per-client secret. The Server resolves the caller from the session and maps mappingId exclusively against Server-confirmed config, ignoring any caller-supplied target ID, port, or secret. Duplicate requestId submissions within a 2-minute window on the same session are rejected as protocol errors without consuming quotas; identifiers may be reused once the window expires. The Server never puts accessSecret inside PeerOpen; the target Agent validates against its confirmed channel snapshot and rejects mode mismatches.
  2. Encrypted mode: Completes inner TLS 1.3 handshake and target SHA-256 fingerprint pinning first, then exchanges the access proof inside the TLS stream.
  3. Plaintext mode: Exchanges the access proof directly over the framed duplex stream. In both modes, the target issues a per-connection 32-byte random challenge and verifies the caller's HMAC-SHA256 proof using the channel accessSecret. Legacy combinations without relayControlReady continue using the single-byte stream readiness marker (1 for raw, 2 for HTTP).
  4. Control-ready binding (v5 relayControlReady): When both Agents negotiate relayControlReady=true, raw TCP and unicast UDP use the hardened control handshake. The Server embeds identical relayBinding metadata (logical connectionId, attemptId, client/session IDs, mapping, channel, transport protocol, and encryption mode) in PeerOpen and PeerOpenGranted. After data tunnels pair and the SQLite start audit commits, the caller sends its 32-byte nonce and 32-byte HMAC proof covering a domain prefix, UTF-8 binding JSON, and both nonces; both ends report the uppercase SHA-256 hex digest of that proof as handshakeId on their control sessions.
  5. Target dial gating: The Server validates both sessions and matching handshakeId, then sends PeerRelayPrepare with a fresh random preparationId to the target. Only after dialing the TCP target or preparing the UDP socket does the target echo preparationId over control TLS, allowing the Server to signal PeerRelayTargetReady to the caller and promote the connection from pending to active. Global and per-client pending quotas remain held throughout setup; raw data bytes cannot advance handshake state, and revocation, bad proofs, identity changes, or timeouts abort the attempt without falling back to the legacy handshake.

Frame Forwarding and Half-Close

The Server validates only frame type, length, pairing, and quotas, forwarding Data/Fin/Reset verbatim. Each direction permits a single reader and single writer, enforcing the 32 KiB Data limit, write timeouts, and cancellation.

  • Encrypted TCP half-close: Encapsulated inside inner TLS application data as 4-byte big-endian length + up to 32 KiB payload, where length 0 represents unidirectional EOF. Sending TLS close_notify early for business EOF is forbidden because Windows Schannel terminates return traffic prematurely.
  • Plaintext TCP half-close: Writes local socket reads directly as Data and sends Fin on local EOF; receiving peer Fin shuts down only the local socket's send direction while allowing return data to finish.
  • Peer UDP: Uses the same access proof and optional inner TLS, carrying 4-byte length-framed datagrams once verified (see UDP Forwarding Technical Design). TCP half-close framing does not apply to UDP.

4. Sequencing, Local Endpoints, and Revocation

Local App -> Caller Agent loopback Accept -> Server validates session & mappingId
          -> (Optional preferDirect: DES-011 P2P probe or fallback)
          -> Target Agent confirms channel & quota -> Both Agents dial BindData
          -> Server signals tls/plain mode and pairs framed pipes
          -> tls: Inner TLS + pinned cert | plain: Skip TLS
          -> Mode-bound HMAC access proof -> Target dials business service
          -> Bidirectional TLS records or plaintext payload relay
  • Atomic validation and status reporting: Agents validate the entire OutboundMappings snapshot (addresses, Base64 secret length, protocol pairing, unique mapping IDs) before stopping old listeners or starting new ones; invalid snapshots log a permanent config error while preserving existing listeners. Valid snapshots bind loopback ports, persist <clientId>.ports.json, and report PeerMappingStatus. The Server validates session, config version, ownership, port range, and uniqueness before displaying reported addresses while the session remains online.
  • Local dashboard and read-only API: The Agent dashboard binds IPv4 loopback at http://127.0.0.1:18081/ by default (dashboardPort = 0 disables both UI and local API). Stable read-only endpoints are GET /api/v1/status, GET /api/v1/channels, and GET /api/v1/mappings (plus legacy GET /api/status), returning 405 on write verbs, no-store cache headers, and no CORS. Models read from an immutable AgentStatusSnapshot (returning empty lists when offline) and never expose secrets, private keys, fingerprints, or tokens. v5 sessions declaring mappingEncryptionStatus receive target channel encryption status on outbound mappings (showing encryption status unknown against older Servers for raw TCP/UDP, while HTTP always uses inner TLS). Multi-server UI management is covered in Multi-Server Agent Design.
  • Timeouts and revocation: Server Bind setup uses openTimeoutSeconds; PeerOpen / PeerOpenGranted carry setupTimeoutMilliseconds = openTimeoutSeconds + targetConnectTimeoutSeconds (older peers omitting the field fall back to 20s, or max(20s, targetConnectTimeoutSeconds) on the target side). Disabling either session, mapping, or target channel rejects new requests; changes to encryption mode or active channel config, or mapping edits/deletions, actively revoke affected pending and active connections (no-op saves do not revoke, and unaffected channels keep running; see ADR-0009). Metrics accumulate forwarded peer payload bytes (legacy APIs preserve peerCiphertext* field names while UI labels display forwarded peer bytes).

5. Acceptance Matrix

Governed by A18–A22 and A51–A53 (see DES-011 for the preferDirect P2P verification matrix):

  • Isolation and stream integrity: Multi-Agent, multi-mapping, and multi-channel isolation; lossless bidirectional large-stream TCP, half-close, and unicast UDP datagram boundaries across encrypted and plaintext modes.
  • Pre-dial rejection: Invalid or missing access keys, unauthorized mappings, replayed requests, and cross-mode attempts must fail before any target dial (zero target Connect).
  • Encryption vs. plaintext boundaries: Encrypted mode enforces pinned certificates and exposes only ciphertext to the Server; plaintext mode emits zero TLS handshake records and copies raw bytes after proof verification.
  • Dynamic updates and quotas: Config and encryption-mode switches revoke stale sessions and apply atomically under confirmed versions; quotas, cancellation, disconnects, and reconnect cleanup stay leak-free without regressing standard cloud-proxy ports. Localhost harness tests never substitute for real cross-host NAT and sustained capacity runs.

Repository source