RELAYLINK

AI automation & SDK design

Document ID: DES-010
Status: Draft
Version: v0.2.2
Updated: 2026-11-23
Research Date: 2026-11-05
Related: REQ-001P, ADR-0035, ADR-0036

Implementation & acceptance status: Originally authored as a proposed design, Phase 1 has now landed in the codebase. Actual progress, test evidence, and open gaps are recorded in the AI Automation Verification Record. Endpoints, fields, error codes, and exit codes below remain binding constraints, while formal acceptance follows REQ-001P A108–A119—implemented does not automatically mean accepted.

Three scope refinements were folded back into this specification during implementation:

  1. Class C channel.security toggles E2E encryption only: Audit mode and authorizedClientsOnly cannot be edited on existing channels; changing channel shape requires deleting and recreating the channel unless a future ADR expands it.
  2. Phase-1 SDK management plane covers C#/.NET only: The other five languages follow a strict standard-library/JDK/built-in-module policy that prevents reading OS credential stores and requires per-language ES256 proof signing. Note that RelayLink.Sdk currently implements the data plane, while RelayLink.AutomationClient implements the .NET automation client.
  3. Proofs must include instanceId: Sourced from the persistent automationInstanceId returned by /info. Both pairing proofs and per-request token proofs carry instanceId so the Server binds proofs to a concrete Server automation instance.

Implementation note on Windows: Kestrel cannot complete TLS handshakes directly from certificates loaded via X509Certificate2.CreateFromPemFile (ephemeral key flag); certificates must be exported to PFX and re-imported.

1. Research Conclusions

The problem is not simply adding another HTTP endpoint; it ties together three concerns: caller identity, credential delivery, and keeping management traffic under the same encryption and audit posture as the browser Admin UI.

Four baseline constraints define the design space:

  1. Browser sessions are unsuitable for automation: Admin APIs rely on AdminSessionService in-memory dictionaries, HttpOnly + SameSite=Strict cookies, and X-RelayLink-CSRF. Giving cookies to scripts persists admin credentials on disk and prevents per-device revocation.
  2. The dashboard listener intentionally serves plaintext HTTP: Remote administrators run an Agent locally on the Server host and access the dashboard through authorized peer inner TLS. Opening a dedicated public HTTPS port for automation would contradict that security posture.
  3. Authorized peer access is the existing encrypted path: Caller Agents expose a 127.0.0.1 loopback port, relay ciphertext through the Server, and have the target Agent dial the target (which can be the Server's own loopback). It already enforces client identities, per-channel access secrets, inner TLS, and access proofs.
  4. Local Agent API boundaries remain fixed: Read-only Agent routes (/api/v1/*, /api/v2/status|channels|mappings) are GET-only with zero Server configuration; /api/v2/admin/servers* writes only the local Agent's servers[] profiles (ADR-0022, ADR-0023, ADR-0034).

Accordingly, RelayLink introduces a loopback-only TLS Automation listener paired with device-bound identities and short-lived tokens—cleanly separating reachability (existing authorized peer channel) from caller identity and authorization (device key + token).

Option Assessment
Let CLI sign in with admin username/password Rejected. Persists human admin credentials on workstations; cannot revoke per device; bypasses explicit console pairing
Static API key header on Admin UI Rejected. Bearer key not bound to a device; copyable across hosts; bypasses one-time human approval
Extend local Agent API into Server write API Rejected. Local API assumes single-user localhost without passwords (ADR-0034) and must not govern Server state
Expose automation directly on public port with TLS Rejected. Expands public attack surface and violates the peer-encrypted transport requirement
One-time pairing + device-bound tokens Adopted. Human-verifiable user code, non-transferable tokens, per-device revocation
SDK builds its own tunnel / exposes NTP1 wire frames Rejected. See ADR-0036; wire protocol stays internal and SDKs target entries only

2. Overall Architecture

flowchart LR
    subgraph ws["Workstation or App Host"]
        hostapp["AI Agent Host"]
        skill["Skill"]
        cli["relaylink CLI"]
        app["Third-Party App + SDK"]
        hostapp --> skill --> cli
    end
    subgraph serverhost["Server Host"]
        caller["Caller Agent"]
        srv["RelayLink.Server"]
        auto["Automation Listener<br/>127.0.0.1:18082 TLS"]
        dash["Dashboard Listener<br/>127.0.0.1:18080"]
        target["Target Agent"]
        target -->|"Dial 127.0.0.1:18082"| auto
        srv --- auto
        srv --- dash
    end
    cli -->|"1 Caller Loopback Entry"| caller
    caller -->|"2 Ciphertext Relay"| srv
    srv -->|"3 Inner TLS"| target
    app -->|"Data Plane: Direct Entry Socket"| entry(("Service Entry"))
    app -->|"Limited Management Plane: Automation API"| auto

Three independent guarantees:

  • Reachability: The Automation listener binds solely to 127.0.0.1. External callers must traverse an authorized peer channel with authorizedClientsOnly=true, endToEndEncryptionEnabled=true, and enforced peerRoutingPolicy=relayOnly (per DES-011), keeping cross-host traffic inside Agent-to-Agent inner TLS while the Server relays ciphertext only.
  • Identity: The CLI proves possession of a local EC P-256 key pair; tokens are bound to that public key thumbprint and fail if copied to another machine.
  • Authorization: Before receiving a token, the device must be explicitly approved by an administrator in the Admin UI, who may narrow requested scopes and lifetime.

The Automation listener adds its own TLS layer—not for cross-host link encryption, which inner TLS already provides, but so the CLI can pin the Server certificate's SPKI thumbprint and prevent local processes on the Server host from spoofing 127.0.0.1:18082. Trust roots remain strictly separated from Agent inner TLS.

Zero wire-protocol changes: No new FrameType, snapshot field, or protocol version is introduced. Automation traffic travels as raw TCP bytes inside an authorized peer channel (compatibility criterion A119). SDK data-plane callers connect straight to service entries without touching the Automation listener or CLI; only the limited management plane uses pairing and approvals.

2.1 Exact Meaning of Over E2E-Encrypted Channels Only

Requirements specify "over E2E-encrypted channels only." Breaking down all four hops prevents overclaiming what loopback hops actually protect:

Hop Segment Encryption Protected By
1 CLI -> Caller Agent local entry (127.0.0.1) Plaintext TCP Loopback isolation + channel access secret only; no extra transport encryption
2 Caller Agent -> Server Inner TLS E2E encryption between both Agents; Server relays ciphertext only
3 Server -> Target Agent Inner TLS Same as above
4 Target Agent -> Automation listener (127.0.0.1:18082) Plaintext TCP Wrapped in the Automation listener's own TLS, pinned by the CLI

Exact posture:

  • Cross-host hops (Hops 2 & 3) carry zero plaintext: They reuse verified Agent inner TLS.
  • Neither loopback hop is E2E-encrypted: Hop 4 has intra-host TLS termination with SPKI pinning; Hop 1 has loopback isolation and the channel access secret only.
  • Accurate statement: Management traffic never crosses the network in plaintext; on loopback hops, the Server side is protected by pinned Automation TLS while the workstation side relies on loopback isolation and the channel secret. Documentation and CLI messages must never describe loopback hops as E2E-encrypted.

This defines the threat boundary: local processes on the Server host can dial 127.0.0.1:18082, requiring SPKI pinning, device tokens, and human approval; local processes on the CLI host can observe or interfere on Hop 1 (residual risk mitigated by running operator workstations as single-user hosts).

3. Configuration Model

server.json adds an optional automation section, disabled by default:

{
  "automation": {
    "enabled": false,
    "listenAddress": "127.0.0.1",
    "port": 18082,
    "certificatePemPath": "/etc/relaylink/tls/automation-fullchain.pem",
    "privateKeyPemPath": "/etc/relaylink/tls/automation-privkey.pem",
    "sessionLifetimeMinutes": 120,
    "maxPendingPairings": 8,
    "maxAuthorizations": 16
  }
}

Configuration and certificate lifecycle rules:

  • Strict deserialization: Follows ConfigurationLoader UnmappedMemberHandling.Disallow; unknown keys fail immediately.
  • Loopback enforcement: listenAddress accepts 127.0.0.1 only. 0.0.0.0, ::, NIC addresses, and localhost are rejected in startup preflight with a SECURITY diagnostic and --check-config failure exit.
  • Dedicated port conflict check: Checks tunnel.port, tunnel.dataPort, dashboard.port, and all configured non-authorized channel ports (including disabled channels). Because ChannelPortSuggestion separates protocols and clears reservations for UDP, automation port conflict detection runs independently.
  • Certificate fault isolation & lifecycle: Missing, expired, or mismatched PEM files disable only the Automation listener while keeping the rest of the Server running. Operations cover three requirements: (a) issue via internal CA or self-signed cert with out-of-band SPKI verification; (b) recommend >= 12-month validity, log SECURITY warnings 30 days before expiry, and display days remaining in the Admin UI; (c) rotating the cert invalidates CLI SPKI pins, requiring relaylink auth trust --reset per workstation (tokens remain valid because they bind device keys, not the Server cert).
  • Restart activation & disable semantics: Changes to enabled or port require a Server restart. Setting automation.enabled=false stops the listener without revoking grants/tokens stored in state.db; real revocation requires explicit Admin UI revocation.
  • State directory: Stored under <server-config-dir>/automation/ with 0600/0700 permissions (or Windows ACL equivalents) via SecretFilePermissions. config/examples/server.example.json stays synchronized with strict schema validation.

4. Channel & Onboarding Wizard

The Admin UI offers an "Create Automation Carrier Channel" action on the client/channel tabs so admins cannot accidentally misconfigure security flags:

  1. Select the target client hosting automation (typically the Agent on the Server host).
  2. The Server generates a channel draft with targetHost=127.0.0.1, targetPort=automation.port, transportProtocol=tcp, applicationProtocol=raw, authorizedClientsOnly=true, endToEndEncryptionEnabled=true, securityGroupId=null, and no public listener (enforcing relayOnly).
  3. On the caller client (operator workstation Agent), the admin adds an outboundMappings entry whose mappingId is fixed to <targetClientId>-<targetChannelId>. Creation requires the target channel to be enabled as authorized peer access and the target client to have registered its E2eCertificateSha256 thumbprint.

Three validation gates prevent exposing automation.port via non-authorized public channels:

  1. Channel save: Any channel targeting a loopback targetHost and targetPort == automation.port must satisfy authorizedClientsOnly=true, endToEndEncryptionEnabled=true, applicationProtocol=raw, and transportProtocol=tcp.
  2. Startup config load: Executed alongside ConfigurationLoader validation to block hand-edited configs.
  3. Full scan on automation.port change: Revalidates all existing channels when automation.port changes so a previously legal loopback channel cannot become an exposed carrier.

The Admin UI also displays the active automation port, certificate SPKI fingerprint, and active grants for out-of-band verification.

5. Pairing & Tokens

5.1 Device Key & Identity

On first run, the CLI generates an EC P-256 key pair and writes the private key exclusively to local protected storage. Device identity is the SHA-256 JWK thumbprint (RFC 7638); the Server stores only the thumbprint and public key. Separate OS user profiles on the same machine act as distinct devices.

5.2 Pairing Flow

sequenceDiagram
    participant U as Operator / AI Agent
    participant C as relaylink CLI
    participant A as Automation Listener
    participant M as Admin UI
    U->>C: relaylink pair
    C->>A: POST /pairing/requests (subject, platform, scope, device JWK)
    A-->>C: requestId + USER_CODE + expiry + cert thumbprint
    C-->>U: Print USER_CODE & next steps (exit code 5)
    M->>M: Admin verifies USER_CODE & scope
    M->>A: Approve (optionally narrows scope & lifetime)
    U->>C: relaylink pair --wait
    C->>A: POST /pairing/requests/{id}/status (device proof)
    A-->>C: approved
    C->>A: POST /pairing/requests/{id}/token (device proof)
    A-->>C: token + scope + expiry
    C->>C: Pin cert thumbprint & store token

Key mechanics:

  • One-time USER_CODE: 8 unambiguous characters (XXXX-XXXX), single-use, 10-minute default TTL. Does not act as a credential on its own. Five wrong attempts lock and void the request (pairing_locked).
  • Device proof (X-RelayLink-Proof): JWT-shaped signed payload with alg=ES256 and jwk header, carrying requestId, instanceId, userCodeDigest (SHA-256), iat, exp, and jti. Inspired by RFC 9449 (DPoP) without using the DPoP header name or claiming RFC compliance. Including userCodeDigest prevents someone who merely sees USER_CODE from exchanging it without the device private key.
  • Single-transaction token exchange: Status polling and token exchange require device proofs and insert jti into a bounded replay cache. Token exchange runs check state -> invalidate request -> issue token in a single state.db write transaction so concurrent requests with distinct jti values cannot mint two tokens. Duplicate exchanges return pairing_already_completed.
  • Quotas & expiry: Pairing requests expire 10 minutes after creation (approval does not extend the window; expired requests fail with pairing_expired). approved requests awaiting exchange count toward maxPendingPairings and move to maxAuthorizations only once the token is issued. Denied requests are terminal (pairing_denied).
  • Device-key rate limiting: Because peer traffic always arrives from 127.0.0.1 ephemeral ports opened by the target Agent, rate limiting by source IP is forbidden. Pairing requests are throttled by (deviceThumbprint, subject) plus a process-wide bucket on /info and pairing creation, returning rate_limited with Retry-After.
  • No refresh tokens: Expired tokens require fresh pairing and human approval (ADR-0035).

5.3 Tokens & Per-Request Proofs

  • Token format: 32 random bytes returned in plaintext once; the Server stores only its SHA-256 digest and looks up scopes dynamically by token ID for instant revocation or narrowing.
  • Per-request headers: Every API call sends Authorization: Bearer <token> and X-RelayLink-Proof containing htm, htu (path + query without scheme/host), ath (base64url SHA-256 of the token digest), iat, exp (<= 60s), jti, instanceId, and Server cert thumbprint.
  • Verification order: TLS established -> token exists, unexpired, unrevoked -> device thumbprint matches token -> valid signature -> htm/htu/ath match -> iat within ±60s -> jti unseen -> scope covers permission -> audit gate. Any failure rejects immediately without fallback.
  • Bounded replay cache: Per-token buckets (default 2048 entries, 90s TTL), rejecting new requests rather than evicting unexpired entries when full. Because it lives in memory, a Server restart clears the cache (documented caveat: within the ±60s window across a restart, a single proof could theoretically replay once).
  • Persistent revocation: Revocation commits to state.db before reporting success to the Admin UI, takes effect on the next API call, and leaves existing data-plane connections undisturbed.

5.4 State Persistence

Pairing requests, grants, change requests, and revocations reside in automation/state.db (SQLite WAL, 0600), separate from append-only audit logs.

  • Retention cleanup: Terminal pairings (expired/denied/completed) kept 7 days; terminal change requests (applied/rejected/cancelled/expired) kept 90 days; revoked grants kept 180 days. Cleanup runs at startup and daily; failures log warnings without blocking service.
  • Coordinated backup & single-instance constraint: server.json, clients/, credentials/, automation/, and both automation PEM files must be backed up and restored together. Restoring an older snapshot can reactivate revoked grants, so operators must review grants in the Admin UI after restore. state.db, the in-memory jti cache, and write locks are strictly single-process (no multi-instance HA).

Persistent Automation Instance ID

ServerRuntime.InstanceId generates a fresh Guid.NewGuid() on every process start without persistence. Using it for automation pinning or proofs would break all tokens and CLI pins on every Server restart. Therefore:

  • Automation introduces a dedicated persistent automationInstanceId, generated on first enable and stored in automation/state.db permanently (moving with the database across backups/migrations).
  • Device proofs, token proofs, CLI profile pinning, and /info all use automationInstanceId; ServerRuntime.InstanceId remains dedicated to audit rows and /overview.
  • Losing and reinitializing state.db generates a new automationInstanceId, intentionally invalidating CLI pins and prompting re-pairing since all grants were lost with the database.

6. Automation API

6.1 Versioning & Common Contract

  • Prefix & version header: /api/v1/automation (separate from UI-oriented /api/v1), with X-RelayLink-Api-Version: 1 (default 1; unsupported versions return unsupported_api_version, CLI exit code 9).
  • Pre-pairing TLS verification: Anonymous endpoints (/info, POST /pairing/requests) run before SPKI pinning. Standard certificate-chain validation applies when issued by an internal CA pre-installed on the CLI host; for self-signed certs, the CLI prints the received SPKI digest and requires explicit out-of-band confirmation via --accept-spki. Version metadata from /info guides behavior selection only and never authorizes security decisions.
  • Response & error envelope: Successful responses carry requestId (writes also return auditStatus recorded/pending and operationId). Pagination uses page/pageSize (max 100). Failures follow:
{
  "error": {
    "code": "scope_insufficient",
    "message": "Automation token lacks clients.write permission.",
    "retryable": false,
    "requestId": "1f0f4b1c-...",
    "details": { "required": "clients.write", "granted": ["clients.read"] }
  }
}
  • Stable error codes (contract/errors.json): unauthenticated, proof_invalid, proof_replayed, token_expired, token_revoked, scope_insufficient, pairing_not_found, pairing_denied, pairing_expired, pairing_locked, pairing_already_completed, pending_capacity_exceeded, rate_limited, validation_failed, unknown_field, not_found, conflict, requires_change_request, change_request_not_approved, audit_unavailable, storage_unavailable, unsupported_api_version, automation_disabled.

6.2 Endpoint Inventory

Method Path Proof Scope Tier
GET /info None — Anonymous
POST /pairing/requests None (rate-limited) — Anonymous
POST /pairing/requests/{id}/status Device signature — Pairing
POST /pairing/requests/{id}/token Device signature — Pairing
DELETE /pairing/requests/{id} Device signature — Pairing (cancel own unexchanged request)
GET /whoami Token — A
GET /health Token server.read A
GET /version Token server.read A
GET /overview Token server.read A
GET /clients Token clients.read A
GET /clients/{clientId} Token clients.read A
PATCH /clients/{clientId} Token clients.write B
GET /clients/{clientId}/channels Token channels.read A
PATCH /clients/{clientId}/channels/{channelId} Token channels.write B
GET /clients/{clientId}/mappings Token mappings.read A
DELETE /clients/{clientId}/mappings/{mappingId} Token mappings.write B
GET /security-groups Token security.read A
POST /security-groups Token security.write B
PUT /security-groups/{id} Token security.write B
DELETE /security-groups/{id} Token security.write B (conflict if referenced)
GET /audit Token audit.read A
GET /history Token history.read A
POST /change-requests Token Per type C
GET /change-requests Token changes.read A
GET /change-requests/{id} Token changes.read A
DELETE /change-requests/{id} Token changes.write B (cancel own pending request)

Notes:

  • /version is a dedicated new endpoint (because /api/v1/overview lacks a Server product version); /overview serves the Server runtime snapshot; POST /security-groups handles creation alongside PUT; client-wide enabled is excluded from Class B (too broad for controlled channel toggling).
  • Fixed scope set (14 scopes): server.read, clients.read, clients.write, channels.read, channels.write, mappings.read, mappings.write, security.read, security.write, audit.read, history.read, changes.read, changes.write, credentials.delete (every write scope implies its matching read scope; credentials.delete has no endpoint in Phase 1 and is reserved). whoami requires no scope.

6.3 Class B Controlled Writes

  • Field allowlist: Uses PATCH and rejects unlisted fields with unknown_field (avoiding whole-object PUT overwrite hazards). Allowed fields: displayName, tags, channel enabled, maxConnections, maxPendingConnections, targetConnectTimeoutSeconds, udpIdleTimeoutSeconds, and security group name / entries.
  • Locked fields & self-protection: Encryption flags, authorizedClientsOnly, transportProtocol, applicationProtocol, targetHost, targetPort, accessSecret, and securityGroupId bindings cannot be edited via Class B. Disabling or deleting the active automation carrier channel or its mapping via automation returns conflict and directs the operator to the Admin UI.
  • Locking, idempotency & no-op skip: Executes under ConfigurationWriteLock, requiring a non-empty UUID Idempotency-Key (same key + different payload -> conflict; replay -> original result) and returning X-RelayLink-Operation-Id and X-RelayLink-Audit-Status. No-op PATCH calls skip snapshot broadcast and connection revocation.

6.4 Class C Structural Change Requests

{
  "type": "channel.create",
  "target": { "clientId": "shanghai-01", "channelId": "sql-1433" },
  "payload": {
    "displayName": "Shanghai SQL",
    "listenAddress": "0.0.0.0",
    "listenPort": 21433,
    "targetHost": "127.0.0.1",
    "targetPort": 1433,
    "maxConnections": 50,
    "targetConnectTimeoutSeconds": 20,
    "authorizedClientsOnly": false,
    "endToEndEncryptionEnabled": true
  },
  "reason": "Add SQL channel for Shanghai node"
}
  • Phase-1 types: client.create, client.delete, channel.create, channel.delete, mapping.create, channel.security (covering EndToEndEncryptionEnabled only; changing AuthorizedClientsOnly requires delete + recreate). credential.delete is excluded—credentials are managed exclusively in the Admin UI, and payloads containing secret fields are rejected with validation_failed and audited.
  • State machine: Submissions run editor validation immediately without writing disk, creating pending records. Transitions: pending -> approved, approved -> applying -> applied, pending -> rejected, approved -> rejected, pending -> cancelled, pending/approved -> expired (24h default TTL). Approvals/rejections happen exclusively in the Admin UI with full before/after diffs.
  • Two-phase execution & crash reconciliation: Because config files and state.db lack cross-store transactions, execution writes applying -> updates config under lock -> writes applied. On startup, any applying records reconcile against (type, target): if the target matches desired state, mark applied; otherwise roll back to approved with failure notes for manual retry or rejection (never auto-retried). Concurrent active requests for the same (type, target) return conflict; Idempotency-Key deduplicates submission.

6.5 Audit Integration

Automation events reuse AuditEvent and SQLite storage, adding nullable AutomationGrantId and DeviceKeyThumbprint columns via ALTER TABLE migration with Actor formatted as automation:<subject>:

Event Trigger
automation_pairing_requested Pairing request accepted
automation_pairing_approved / automation_pairing_denied Admin UI decision
automation_pairing_expired / automation_pairing_locked Expiry or 5 bad user codes
automation_token_issued Token exchanged
automation_token_revoked Revoked in Admin UI
automation_request Every token call (incl. reads) with outcome and reasonCode
automation_change_requested / _approved / _rejected / _applying / _applied / _failed Class C lifecycle
  • Write audit gate: Extends ADR-0013 to configuration writes—if audit storage is unavailable, Class B writes and Class C submissions fail closed with 503 audit_unavailable; read calls proceed while logging a file warning.
  • Read coalescing: Repeated reads by the same token for the same method + path within a 60-second window coalesce into one audit row (endpoint, count, first/last timestamp), bounded by a default 600 reads/min per-token limit (rate_limited beyond).

7.1 Command Structure

Single self-contained executable (src/RelayLink.Cli, targeting Windows/Linux/macOS × x64/arm64):

relaylink pair [--wait] [--scope <s>]... [--subject <name>]
relaylink pair status|cancel
relaylink auth whoami|logout|profiles|trust --reset
relaylink doctor
relaylink server health|overview|version
relaylink clients ls|get
relaylink clients set <clientId> --display-name <v> --tag <v>...
relaylink channels ls|get|set
relaylink mappings ls|rm
relaylink security-groups ls|create|set|rm
relaylink audit ls
relaylink history show
relaylink changes submit|ls|get|cancel
relaylink skill install --host <host> [--force]

7.2 Entry Discovery & Profiles

  1. Explicit --entry or configured profile entry.tcp=host:port takes precedence.
  2. Otherwise query local Agent http://127.0.0.1:<dashboardPort>/api/v2/mappings (default 18081) matching the automation targetClientId and targetChannelId to obtain localAddress.
  3. If neither is available, exit with code 8.

Profiles store name, optional entry, dashboardPort, persistent automationInstanceId, spkiSha256, grantId, and credential pointer. When multiple profiles exist without --profile, the CLI errors rather than guessing.

7.3 Global Flags, Exit Codes & Security

  • Global flags: --profile, --json, --dry-run, --yes, --timeout, --verbose, --api-version.
  • JSON contract: {"schemaVersion":1,"requestId":"...","data":{...}} or {"schemaVersion":1,"error":{...}}.
  • Exit codes: 0 success, 2 usage error, 3 unauthenticated/unpaired, 4 insufficient scope, 5 human approval required, 6 Server business rejection, 7 audit/storage unavailable, 8 network or certificate pin failure, 9 version incompatibility.
  • Credential store: OS keyring first (Windows DPAPI/Credential Manager, macOS Keychain, Linux libsecret), falling back to protected files (Windows ACL / Unix 0600, dir 0700) with a warning emitted in warnings under --json.
  • Pinning & retries: Pins spkiSha256 and automationInstanceId at pairing; mismatches hard-fail with exit 8 and instruct relaylink auth trust --reset (no --insecure flag). Non-TTY sessions never hang for confirmation (exit 5 unless --wait). --dry-run validates locally and outputs the plan without submitting mutations. Retries apply only to GET and idempotent writes (max 3, exponential backoff).
  • Encoding & secret hygiene: Redirected stdout/stderr use UTF-8 without BOM. Human output never logs tokens, private keys, or secrets; USER_CODE prints once on pairing initiation (data.userCode in --json and a tagged line in text output) and is never written to logs or files.

8. Skill Contract

Bundled in skills/relaylink-admin/ alongside CLI releases:

skills/relaylink-admin/
├── SKILL.md
├── reference/commands.md
├── reference/scopes.md
├── reference/change-requests.md
└── scripts/relaylink.mjs        # Argument-forwarding wrapper reading --json (requires Node.js)

SKILL.md declares name, description, supported CLI/API versions, and six prompt-level rules:

  1. Invoke relaylink only—never make direct HTTP calls or implement TLS/pinning/tokens/pairing manually.
  2. Parse --json output only; never read credential stores, device private keys, Server configs, or raw logs.
  3. On version mismatch (exit 9), stop and instruct upgrading the CLI—never downgrade or use raw HTTP.
  4. On exit 4, stop and tell the user which scope to request—never alter flags to retry.
  5. For Class C changes, run --dry-run, get user confirmation, then submit and report changeRequestId + pending status without claiming changes are live before applied.
  6. If anything resembling a secret appears in output, halt immediately, report the anomaly, and write nothing to disk.

Prompt-layer boundary: These six constraints are guidance for the host AI agent, not an OS sandbox. Acceptance covers artifact review plus controlled end-to-end demonstrations in at least two named hosts; host-agent non-compliance stays recorded in Section 12. scripts/relaylink.mjs requires Node.js on the host, and relaylink skill install --host <host> copies files only and prompts restarting the host.

9. SDK Layering & Multi-Language Baseline

9.1 Layering

flowchart TB
    app["Third-Party App"] --> dp["Data Plane"]
    app --> mp["Limited Management Plane"]
    dp --> entry["Entry Discovery"]
    entry --> api["Agent v2 Read-Only API<br/>127.0.0.1"]
    dp --> tcp["TCP / UDP Business Sockets"]
    mp --> auto["Automation API"]
    auto --> approval["Human Approval Queue<br/>Admin UI"]

Both layers are decoupled: apps using only the data plane need no pairing, tokens, or Automation API access.

9.2 Contract Sources

contract/ serves as the language-neutral source of truth:

  • contract/automation-api.openapi.json — OpenAPI 3.1 spec for the Automation API
  • contract/entry-descriptor.schema.json — Entry descriptor and Agent status schema
  • contract/errors.json — Single source of truth for error and exit codes
  • contract/conformance/ — Language-neutral behavior test cases consumed directly by every SDK test runner

The data plane is hand-written in each language (lightweight socket semantics without generated bloat), while management-plane DTOs/stubs can derive from OpenAPI with thin language wrappers.

9.3 Data-Plane Design

  • Entry discovery: Explicit config takes precedence; otherwise read http://127.0.0.1:<dashboardPort>/api/v2/mappings (default 18081) and match targetClientId/targetChannelId for authorized peer entries (requiring explicit profileId when multiple profiles match). Standard proxy entries cannot be auto-discovered and must be configured explicitly because Agent v2 views do not include channel ListenAddress/ListenPort.
  • TCP / UDP / HTTP semantics: TCP provides single connections with connectTimeout, idleTimeout, unidirectional half-close (shutdown_write), and cancellation—with no hidden connection pool or reconnect loop. UDP binds a single socket preserving datagram boundaries and errors explicitly above maxDatagramBytes (65507) without silent truncation. HTTP provides base URL, scheme, and expected Host/Origin guidance for the caller's own HTTP client.
  • Unified error codes: entry_unavailable, entry_not_found, tunnel_rejected, target_connect_failed, timeout, configuration_drift, invalid_usage (see SDK Documentation).
  • Explicit non-goals: Wire framing (NTP1), multiplexing, NAT traversal, VPN, key caching, and automatic reconnect loops.

9.4 Language & Version Baseline

Language Minimum Version / Targets Dependency Policy
C#/.NET netstandard2.0 + net8.0 (and net10.0) BCL only; must not reference RelayLink.Protocol
Java 17 (LTS) JDK only; no Netty
Python 3.9 Standard library only
TypeScript/Node Node 20 Built-in Node modules only; bundled .d.ts
Go 1.22 Standard library only
Rust 1.75 (edition 2021) No async runtime; synchronous std::net

9.5 Limited Management Plane

  • Three actions: registerClient, registerChannel, and requestAccess (all Class C change requests; updating existing channels uses CLI channels set Class B writes).
  • Phase-1 scope boundary: Because every call requires ES256 signing with the device private key and the zero-dependency baseline prevents Python/TypeScript/Go/Java/Rust from reading OS credential stores (DPAPI/Keychain/libsecret), Phase 1 commits the management plane for C#/.NET only (via RelayLink.AutomationClient). The other five languages provide the data plane only; Phase-2 cross-language options (portable encrypted credential file, relaylink subprocess wrapper, or local sidecar) require a separate ADR.
  • No secret distribution: Pairing stays in relaylink pair. Approved registrations return client ID, channel ID, and request ID only—never client secrets. Full onboarding still requires an admin to download and distribute Agent config, start the Agent, bind its E2E thumbprint, and create mappings. Request listings return only submissions from the current device.

9.6 Platform Matrix

Platform Supported Notes
Windows x64 / arm64 Yes Windows 10 1809+, Server 2019+
Linux x64 (glibc) Yes Ubuntu 22.04+, Debian 12+, RHEL 9+
Linux x64 / arm64 (musl) Yes Alpine 3.18+; Rust requires *-musl target
macOS x64 / arm64 Yes macOS 12+

10. Code Ownership

Component Location
Automation config, listener, pairing, tokens, proof verification, Class C state machine src/RelayLink.Server/Automation/ & AutomationEndpoints.cs
CLI src/RelayLink.Cli/
Shared automation client library (CLI & .NET management plane) src/RelayLink.AutomationClient/
.NET Data-Plane SDK src/RelayLink.Sdk/
Five-language Data-Plane SDKs sdk/java, sdk/python, sdk/typescript, sdk/go, sdk/rust
Contracts & conformance suite contract/
Agent skill skills/relaylink-admin/
Admin UI pairing & change-approval modals src/RelayLink.AdminWeb/src

Because Directory.Build.props sets <TargetFramework>net10.0</TargetFramework> globally and RelayLink.Protocol is not multi-targeted for netstandard2.0, RelayLink.Sdk must stay BCL-only without referencing RelayLink.Protocol.

11. Failures & Fault Handling

Scenario Behavior
Automation disabled on new Server No listener on port; CLI cannot distinguish disabled vs. stopped at TCP layer and exits 8 with both diagnostics
Legacy Server (no automation port) TCP connection refused -> exits 8 (exit 9 is reserved for reachable /info reporting an incompatible version); data-plane SDKs unaffected
Missing, expired, or mismatched cert Automation listener stays down with SECURITY log; rest of Server starts normally; CLI exits 8
Pairing request expired CLI receives terminal pairing_expired and exits 5
Pending capacity full Rejects new requests with pending_capacity_exceeded; existing grants/tunnels unaffected
Token expired or revoked Next API call returns token_expired / token_revoked (exit 3); active data tunnels unaffected
Clock skew on device Rejected when iat falls outside ±60s; error includes Server timestamp
Proof replay proof_replayed, audited, excluded from rate-limit quota
Audit storage unavailable Mutations and change requests fail closed (audit_unavailable, exit 7); reads return data with warning log
Config write lock contention Queues up to --timeout; returns retryable: true on timeout
Crash during Class C applying Reconciles on startup by (type, target): marks applied if target reflects change, else reverts to approved with failure note (no auto-retry)
Server restart Grants, token hashes, and revocations persist in state.db; in-memory jti cache and rate-limit buckets reset
Restoring old backup Rolled-back state.db may resurrect previously revoked grants; admin must review and revoke in Admin UI after restore
Automation TLS cert rotation All CLIs must run relaylink auth trust --reset and re-verify SPKI; existing tokens stay valid
Target client offline Matches existing behavior: config succeeds with pending delivery notice
CLI and local Agent unreachable Data plane raises entry_unavailable; calling application decides retry policy

Anonymous /info is an intentional trade-off so the CLI can inspect API versions and automationInstanceId before pairing without exposing secrets or device metadata.

12. Security Consequences

Threat Mitigation Residual Risk
Local process on Server host spoofing automation endpoint Dedicated TLS listener + SPKI pinning + human fingerprint verification Admin skips fingerprint verification
Local process on Server host squatting 127.0.0.1:18082 Loopback bind + exclusive socket + startup occupant logging Process squats while Server is stopped; defeated by SPKI pinning
Local DoS against pairing queue Rate limiting by (deviceThumbprint, subject) + process-wide cap + Admin UI alert Legitimate pairing blocked when queue fills until admin clears
Local process on CLI host sniffing Hop 1 loopback No extra transport encryption; relies on loopback boundary + channel secret Plaintext visible locally; mitigate via single-user operator workstation
Token stolen/copied to another machine Token bound to device public key; per-request ES256 proof required Compromised device private key compromises grants until revoked
AI agent over-privileged writes Scope allowlist + mandatory human approval for Class C + full audit Approved Class B writes execute without per-call confirmation
Host AI agent ignores SKILL.md Static artifact review + controlled host demonstrations Prompt rules are not a security sandbox; reduce misuse risk only
Automation channel exposed publicly Onboarding wizard + 3 validation gates (save, startup, port change) Offline config edit skipping startup check caught by audit/SECURITY logs
Mistaking enabled=false for revocation Explicitly documented that disabling preserves state.db grants Re-enabling restores unexpired tokens unless explicitly revoked
Secrets leaked to logs or shell history Token returned once in body; USER_CODE printed once User intentionally pipes --json to disk
Audit bloat from read polling 60s coalescing per (token, method, path) + 600 req/min cap High-cardinality polling still logs; crash inside 60s window falls back to file logs
Third-party SDK leaking tunnel secrets SDK holds zero relay keys and connects to entries only Entry reachability still governed by network & channel controls

This design preserves RelayLink's core trust model: standard proxy data tunnels remain unencrypted TCP unless protected by the workload, and peer access uses inner TLS between Agents.

13. Compatibility

  • Zero changes to NTP1 frames, ProtocolConstants.Version, snapshots, or legacy Admin APIs.
  • Legacy Servers without the automation port cause TCP connection refusal and CLI exit 8; exit 9 applies strictly when /info is reachable and reports an incompatible version. Data-plane SDKs depend only on Agent v2 APIs and remain unaffected.
  • automation config defaults to disabled; AuditEvent adds nullable columns via ALTER TABLE. Automation API guarantees backward compatibility within a major path version.
  • schemaVersion, document version, wire version, and SDK versions evolve independently.
  1. Config section, preflight checks, audit schema migration, port conflict & 3 loopback checks, Admin UI read-only display.
  2. Full pairing flow (device keys, USER_CODE, Admin UI approval modal, single-transaction exchange, rate limiting/lockout, audit events).
  3. Tokens & per-request proofs, whoami, read endpoints (incl. /version), scope enforcement, read coalescing.
  4. Class B PATCH writes, Idempotency-Key, audit gate, automation carrier self-protection.
  5. Class C state machine (applying + startup reconciliation) and approval UI.
  6. relaylink CLI (discovery, profiles, OS credential stores, SPKI pinning, all commands, exit codes, --json, --dry-run).
  7. skills/relaylink-admin/ bundle, wrapper script, and demonstrations across two named hosts.
  8. contract/ specs, conformance suite, and .NET Data-Plane SDK.
  9. Python, TypeScript, Java, Go, and Rust Data-Plane SDKs with CI runners.
  10. .NET SDK management plane (RelayLink.AutomationClient), release pipelines, and checksums.

15. Verification Points

Evidence collection for REQ-001P A108–A119 covers:

  • Transport boundaries: listenAddress strictly 127.0.0.1, plaintext HTTP rejected.
  • E2E prerequisite negatives: non-authorized channel to loopback port, manual config edit + restart, automation.port change conflict.
  • Pairing timing & concurrency: USER_CODE expiry, 5-attempt lock, expired post-approval exchange, duplicate exchange, concurrent jti race yielding at most 1 token, scope expansion rejection.
  • Token & restart behavior: cross-device token copy, clock skew, jti replay, immediate revocation, failed persistence not faking success, restart recovery.
  • Audit & redaction: database inspection plus value-by-value log scan across Server and CLI confirming zero leaks of tokens, user codes, or private keys.
  • Cross-language & cross-platform SDK conformance: all 6 languages running contract/conformance/, packet capture confirming zero NTP1 frames, and native Linux/macOS/musl runs.

16. References

Repository source