Skip to content

feat: add opt-in paired-device direct and E2EE relay transport #69

Closed

Description

@abruption

Motivation

session-peer is local-first and uses SSH for remote execution. SSH is valuable
because the destination needs no resident session-peer service, but it also
requires a reachable SSH endpoint, the correct destination account, keys, and
host configuration. That makes pairing devices across NAT, firewalls, mobile
networks, and separately managed servers harder than the actual agent-message
operation.

Explore an opt-in paired-device transport similar to Paseo's connectivity model:
keep local operation as the default, permit direct TCP/Tailscale/other-VPN
connections to an explicitly enabled receiver, and offer an end-to-end encrypted
relay when direct connectivity is unavailable. Existing local and SSH transports
must remain supported.

References:

Product principles

  • Local-only remains the zero-configuration default. Ordinary commands, JSON
    consumers, and automation must never receive an unsolicited setup prompt.
  • Relay and direct peer listening are enabled only through an explicit setup,
    pairing, or service command.
  • Treat WireGuard/Tailscale as an optional direct-network underlay. Do not make
    session-peer a VPN control plane or implement key distribution for WireGuard.
  • The application relay forwards opaque encrypted frames. Endpoint private keys
    never leave their devices, and relay compromise must not reveal message bodies.
  • Keep SSH as an independent transport. A paired-device route must not silently
    guess SSH accounts or change existing --host behavior.
  • The receiver exposes a narrow session-peer protocol for discovery and message
    submission, not arbitrary remote command execution.

Findings from Orca's relay implementation

Orca provides a useful production reference for the boundary between endpoint
security and relay infrastructure:

  • Both endpoints open outbound WebSockets to a relay cell. A director assigns
    hosts to cells and returns a versioned assignment epoch and lease, while cells
    own the live user connections and splice frames. This keeps placement and
    migration decisions out of the data-forwarding path.
  • A shared relay-contract package is consumed by the relay and both endpoints.
    It defines strict versioned schemas, typed close codes, protocol limits,
    admission budgets, and a forward-only splice state machine. The state machine
    permits client acknowledgement only after both forwarding handlers exist,
    avoiding a false-positive connection result.
  • Relay admission credentials and assignment leases are distinct from the
    endpoint E2EE session. The relay authenticates and pairs the outer connection,
    then forwards an opaque encrypted stream. Orca's host proof also binds the
    relay origin, host identity and public key, assignment epoch, issue/expiry
    times, and resume intent into an encrypted challenge transcript.
  • During initial pairing, Orca probes direct and relay candidates concurrently.
    The first verified path wins, with direct selected deterministically on an
    exact tie. Relay resume credentials are installed with a stable request ID and
    reconciled as committed before the client publishes the relay endpoint.
  • Frame size, first-frame and attach deadlines, idle time, per-host connections,
    queued bytes, high/low watermarks, and wedged-link time are bounded. Failures
    use typed close reasons rather than being reported as generic delivery success.

For session-peer, the reusable parts are the shared versioned contract, the
separation of control and opaque data paths, deterministic route selection,
transactional credential reconciliation, and bounded forwarding. Orca's
multi-region director/cell fleet, Cloud SQL/Terraform operations, and separate
mobile push gateway are later scale concerns and should not be required for the
first self-hostable relay.

Possible interface

Names are provisional and should be settled during design:

session-peer serve
session-peer relay enable
session-peer relay disable
session-peer device pair
session-peer device list
session-peer device remove <device>
session-peer send --device <device> --to <session> "message"

A paired device can record one logical identity with several routes. If direct
and relay routes are both available, probe them concurrently and accept the
first authenticated endpoint response, choosing direct deterministically on an
exact tie. Report the route actually used. Keep explicit SSH
destinations separate unless a future design safely unifies them through the
structured reply-address work in #45.

The receiver service should run as the OS user that owns the Claude/Codex state
and bind only to explicitly configured interfaces. Installing the ordinary CLI
must not automatically enable or start it.

Pairing and security model to design first

  • Generate endpoint identity and encryption keys locally. Pairing transfers only
    public identity material, relay information, and a bounded one-time secret.
  • Show or verify a short fingerprint/confirmation value so a pairing link cannot
    silently substitute a peer key.
  • Store private material with OS-appropriate protection; support revocation and
    key rotation without reinstalling the CLI.
  • Use a reviewed protocol/library for authenticated encryption. Do not design
    custom cryptographic primitives. The current standard-library-only packaging
    means relay crypto may need an optional extra or a separate helper.
  • Define per-device capabilities such as list, Claude send, and Codex send. A
    paired peer does not receive filesystem or process-execution authority.
  • Bind each encrypted request to protocol version, sender, receiver, message ID,
    nonce, expiry, and operation. Reject replay, oversize payloads, expired
    requests, and unauthorized operations before touching an agent transport.
  • Keep outer relay admission and route-assignment credentials separate from the
    endpoint identity and payload-encryption session. Bind redirects or assignment
    changes to a trusted origin and a strictly newer generation.
  • Document metadata visible to the relay, including device routing identifiers,
    timing, connection state, and ciphertext sizes.
  • Apply bounded queues, backpressure, connection timeouts, and rate limits.

Delivery semantics

Do not collapse transport stages into delivered. Structured results should
distinguish at least:

  1. accepted by the relay, when a relay was used;
  2. accepted by the destination device service;
  3. posted to a Claude inbox or submitted to a Codex queue;
  4. consumed or acknowledged only when independently proven.

Use idempotent message IDs so reconnect or timeout handling never causes an
automatic duplicate submission. Coordinate the eventual response schema with
#29 and reply/wait semantics with #31 and #45.

Proposed phases

  1. Write the protocol, threat model, key lifecycle, device identity, route
    selection, and status contract before implementing a public relay.
  2. Add an opt-in receiver and direct connection over a controlled Tailscale/VPN
    test network. Preserve all local/SSH behavior and measure operational cost.
  3. Add a self-hostable, online-only blind relay and E2E pairing. Both endpoints
    connect outbound so no inbound port or SSH configuration is required.
  4. Consider hosted relay operation, regional routing, or encrypted offline
    store-and-forward only after the online design is verified.

Out of scope for the first implementation

  • Replacing SSH or removing agentless remote execution.
  • Managing WireGuard interfaces, tailnets, DNS, ACLs, or VPN peer keys.
  • Arbitrary remote shells, commands, or file access.
  • Claiming Claude/Codex consumption from a socket write or queue acceptance.
  • Offline durable relay queues, multi-relay federation, and mobile UI.
  • Automatically enabling a daemon, listener, relay account, or background
    service during ordinary CLI installation.

Acceptance criteria for an initial implementation

  • A fresh install remains local-only, starts no listener, contacts no relay,
    and preserves existing local/SSH CLI and JSON behavior.
  • Explicitly paired devices can list and submit to permitted local
    Claude/Codex targets over a direct Tailscale/VPN route.
  • When direct connection is unavailable, the same paired identity can use an
    explicitly enabled relay without exposing plaintext or endpoint private
    keys to that relay.
  • Route selection and every submission stage are exposed in structured
    results without claiming consumption.
  • Direct and relay candidates can be probed without waiting through a serial
    fallback timeout; selection is deterministic when both verify together.
  • A versioned shared wire contract validates both endpoints and the relay,
    and the destination is never acknowledged before bidirectional forwarding
    and endpoint authentication are ready.
  • Pairing replacement, replay, expiry, revocation, key rotation, timeout,
    reconnect, duplicate-message, malformed-frame, backpressure, and
    unauthorized-operation cases fail closed in tests.
  • Credential installation and rotation survive a lost response through a
    stable idempotency ID and authoritative status reconciliation.
  • A relay outage never changes local or explicit SSH behavior and never
    triggers duplicate submission.
  • macOS, Linux, and Windows lifecycle behavior is specified; supported
    platforms receive integration coverage for service startup/shutdown and
    direct/relay transport.
  • Documentation includes the threat model, relay-visible metadata, firewall
    requirements, setup/removal/recovery procedures, and the distinction
    between the CLI package, optional receiver service, and relay service.

This is a future design and implementation project rather than part of the
current v0.7 diagnostics scope in #45.

Activity

  1. added
    enhancement
    on Sep 16, 2026
  2. abruption commented on Sep 18, 2026

    @abruption
    OwnerAuthor

    Implementation resumed on isolated branch feat/69-relay-rc-hardening, based on main 0dd9592.

    User-approved RC scope now includes React + Better Auth with GitHub and Google login, user/device ownership and CLI device authorization, alongside endpoint key rotation, durable reconciliation, bounded journals, recovery and KR hosting at relay.abruption.dev. Initial hosting remains restricted to the operator's approved accounts/devices. OAuth login does not replace E2EE pairing or receiver policy.

    Work is divided between Python relay/lifecycle integration in the project session, the KR ontology session's isolated control-service implementation, and the Mac ontology session's infrastructure preparation. Existing production ingress is held until the integrated candidate is ready.

    Release gates: 24 hours on a fixed candidate; isolated real Codex/Antigravity sessions; Claude live receive/ACK after its quota recovers. Claude calls/retries are not being attempted while quota is exhausted. The RC release PR must wait for that evidence. This task does not authorize automatic merge, tags or PyPI publication.

    Automatic tests and partial implementation are not a completed deployment, OAuth-provider verification or an RC release. Remaining acceptance criteria will be tracked explicitly before closing #69.

  3. abruption commented on Sep 18, 2026

    @abruption
    OwnerAuthor

    구현 및 검증 진행 상황을 갱신합니다. 앞선 코멘트의 배포 보류·24시간 시험 계획은 아래 상태로 변경되었습니다.

    • KR 릴레이 구현·통합 테스트·운영 설정을 feat/69-relay-rc-hardening (63f6de6)에 푸시했습니다. 별도 인증 구현 이력은 feat/69-relay-control-auth (3de5604)에 보존했습니다. 최종 통합 변경은 RC 브랜치를 기준으로 검토해 주세요.
    • React + Better Auth의 실제 GitHub/Google 로그인, 명시적인 CLI 기기 승인, 사용자별 소유권 분리, 기기 등록·admission·등록 결과 조회 복구를 검증했습니다. OAuth 인증은 endpoint E2EE pairing/pin 권한을 대체하지 않습니다.
    • 실제 공개 paired WSS와 내부 E2EE TLS, 동일 메시지 ID의 중복 효과 방지, 잘못된 possession proof 거부·정상 첫 사용·소비한 ticket 재사용 거부를 검증했습니다. 격리된 실제 Codex/Antigravity 세션에서는 direct와 public relay 경로의 독립 transcript ACK를 확인했습니다. 제품의 consumptionConfirmed는 계속 false이며, 큐 수락·socket write를 소비 완료로 간주하지 않습니다.
    • KR Linux 독립 검증에서 watchdog 후보의 Node 22/24 각 63개 테스트 및 실제 Node/Python 통합 4개 테스트가 통과했습니다. 앞선 후보의 Python 전체 402개 테스트 결과는 별도 이력으로 보존했습니다. systemd watchdog의 freeze/unhealthy/crash 감지, fresh readiness 이후 자동 복구, rate limit과 상태 보존도 별도 격리 시험으로 검증했습니다.
    • 사용자 결정으로 24시간 시험 요구를 면제하고 실행 중인 시험을 종료했습니다. 중단된 관찰은 약 5시간 21분·321 cycles이며 기록상 failures/safetyFailures/sampleGaps는 0입니다. 이는 24시간 통과가 아닙니다. 로컬 시험 프로세스와 KR observer를 종료했으며 KR 서비스 운영과 구분합니다.
    • CF 인프라 전환 계획은 폐기했으며 해당 평가 브랜치는 이번 푸시에 포함하지 않았습니다. 자격증명·개인키·로그인 파일·DB·실제 사용자 허용 목록도 포함하지 않았습니다.

    남은 항목: 실제 Claude 수신/ACK(쿼터 회복 전 호출·재시도 금지), 추가 지원 플랫폼/VPN-off 및 남은 fault/recovery 검증, 패키지·운영 복구 근거와 #69 전체 AC 대응표의 최종 확인. 미충족 AC를 후속 과제로 옮겨 완료 처리하지 않습니다.

    현재는 소스 공유 및 제한된 검증 완료 상태이며 #69 전체 완료나 RC 릴리즈 승인으로 표시하지 않습니다. 병합·태그·게시·PyPI 릴리즈는 수행하지 않았습니다.

    검증 기록: https://github.com/abruption/session-peer/blob/feat/69-relay-rc-hardening/docs/validation/69-rc.md
    KR 운영 설정: https://github.com/abruption/session-peer/tree/feat/69-relay-rc-hardening/deploy/kr

  4. abruption commented on Sep 19, 2026

    @abruption
    OwnerAuthor

    최종 RC 재검증 결과를 반영합니다.

    • 통합 후보는 feat/69-relay-rc-hardening의 a09def3이며 PR #99로 제출했습니다.
    • Python 405개(컴파일된 Node control 통합 포함), control 63개/8파일, Node 22/24, 패키지 빌드·fresh wheel 설치·MCP/relay 선택 설치, Windows/macOS/Ubuntu GitHub Actions 행렬이 모두 통과했습니다. GitHub Actions run: https://github.com/abruption/session-peer/actions/runs/35418566269
    • 실제 Claude 2.1.277, Codex 0.155.0, Antigravity CLI 1.2.7에서 direct 및 public relay transcript ACK를 각각 확인했습니다. consumptionConfirmed=false는 그대로 유지하며 transcript ACK와 구분합니다.
    • Antigravity CLI 1.2.7의 agentapi send-message 인수 호환성과 macOS locale에 따른 bridge 세션 소실을 수정했고 회귀 테스트를 추가했습니다.
    • KR 운영 watchdog에 SIGSTOP을 주입해 control/fresh readiness/relay가 35.67초 안에 자동 복구됐고, 상태·replay high-water와 설정 해시 보존 및 복구 후 공개 Claude ACK를 확인했습니다.
    • 사용자가 이번 재검증에서 24시간 연속 시험을 명시적으로 제외했습니다. 앞선 중단 기록은 24시간 통과로 간주하지 않습니다.
    • CF 전환 평가 코드는 최종 RC 브랜치와 PR에 포함하지 않았습니다. 자격증명·토큰·DB·replay state·개인키도 포함하지 않았습니다.

    PR: #99
    검증 기록: https://github.com/abruption/session-peer/blob/feat/69-relay-rc-hardening/docs/validation/69-rc.md

    현재는 리뷰 가능한 RC PR 제출 및 검증 완료 상태입니다. 병합·태그·패키지 게시·릴리즈는 수행하지 않았습니다.

  5. abruption commented on Sep 19, 2026

    @abruption
    OwnerAuthor

    추가 운영 gate 검증을 완료했습니다.

    • session-peer-stack.target만 multi-user.target에 enable하고 control·relay 개별 unit은 direct boot entry로 disabled 유지했습니다. migration/replay-init one-shot도 자동 실행하지 않습니다.
    • KR 호스트를 실제 재부팅했습니다. SSH는 약 28초 후 복구됐고 control(12:37:38 KST) → readiness → relay(12:37:49) 순서로 자동 기동했습니다. 네 unit은 active/NRestarts=0, health 200, state·replay high-water와 spent ticket 2개가 보존됐습니다.
    • 기존 Caddy, Authelia, Authadmin, Ontology, portfolio, monitor, Orca, Redis, rclone 2개, Tailscale, SSH, OCI monitoring과 중앙 Vault가 모두 복구됐습니다. 공개 사이트 상태와 vault status integrity=ok도 확인했고 failed unit은 0입니다.
    • 기존 Restic 작업에 session-peer가 빠져 있어 root-only cold snapshot helper를 추가했습니다. 첫 시도는 정지 전파 경합을 fail-closed로 발견해 snapshot/원격 백업 없이 중단·복구됐고, unit을 역순 명시 정지하도록 수정했습니다.
    • 수정 후 SQLite integrity, signing key/JWKS, 기기 2개, operation receipt 2개, public revision 1214, replay revision 1213와 spent ticket 2개를 포함한 일관 snapshot을 만들었습니다.
    • encrypted R2 snapshot d286abf2 생성이 성공했습니다. 이를 root-only 격리 경로에 실제 복원해 3,742개 항목/180.638 MiB, manifest 파일 해시·mode, DB table count, 키·revision·replay·runtime symlink를 검증했습니다. production 경로는 수정하지 않았고 복원 사본은 검증 후 삭제했습니다.
    • daily 05:00 KR DR 작업은 이제 cold snapshot과 session-peer config/unit/runtime을 포함하며, helper 실패 시 전체 DR 백업을 중단합니다.

    관련 커밋: ee4db45, 386c83c
    GitHub Actions run: https://github.com/abruption/session-peer/actions/runs/35419599716 — 전체 통과

    병합·태그·게시·릴리즈는 수행하지 않았습니다.

  6. abruption commented on Sep 19, 2026

    @abruption
    OwnerAuthor

    RC scope update (7b6e8a1, included in #99):

    • Verified GitHub/Google public signup is available without invitations, an account allowlist, or a user-count cap. It remains an explicit deployment switch; closing new signup does not evict committed identities.
    • The provider account allowlist is retained only for break-glass/operator authorization. Public users cannot access operator APIs.
    • Added https://relay.abruption.dev/admin/metrics, a browser-session-only aggregate view of service health, signup status, user/device/operation counts, and state revision. It contains no emails, provider IDs, internal user IDs, principals, certificates, tokens, or secrets.
    • Added a reviewed exact /session-peer redirect block for the existing Authelia-protected admin.abruption.dev portal. It preserves that site's root and /api/*; the relay performs its own operator check after redirect.

    Validation for this delta: Node 22.14 and Node 24.16 typecheck/build/68 tests/audit 0; Node/Python integration 5 tests; full current Caddy candidate adapt/validate passed. The portal redirect and public-signup switch are not yet live, and no merge/release is implied by this update.

  7. abruption commented on Sep 19, 2026

    @abruption
    OwnerAuthor

    Release follow-up: the operator and user-facing surfaces described above are now live for v1.0.0-alpha.1.

    • The KR control runtime now runs the tagged control build with public signup enabled. The existing DB, signing key, device/operation receipts, public-state revision, and replay high-water were preserved through a verified cold snapshot.
    • https://admin.abruption.dev/session-peer is an exact Authelia-protected portal route to https://relay.abruption.dev/admin/metrics. The relay still performs its own provider-account operator check; the unauthenticated metrics API returns 401.
    • The metrics UI was verified with an allowlisted operator session and reports aggregate health/signup/device/operation counts only.
    • The multilingual hosted guide and AI setup instructions are live at https://abruption.dev/projects/session-peer/relay-server/ and https://abruption.dev/projects/session-peer/llms.txt.
    • The guide source was merged in abruption/abruption.dev-site#1; the production landing-page Worker was deployed from that merge commit.

    Post-deploy checks passed for control/readiness/relay health, loopback-only listeners, Caddy reload without PID replacement, existing admin health/root behavior, all four guide locales, and the pinned alpha install instructions. No user-count cap or manual invitation gate is active.

  8. abruption commented on Sep 20, 2026

    @abruption
    OwnerAuthor

    Post-release cross-host validation for v1.0.0-alpha.1 completed on 2026-09-20 using a disposable Windows 10 / Ubuntu 24.04 WSL2 endpoint and an Ubuntu 24.04 ARM64 endpoint. Both used session-peer[relay]==1.0.0a1, with only the public wss://relay.abruption.dev/v1/connect route configured. The 24-hour soak remained out of scope.

    Passed:

    • generation-0 enrollment and E2EE pairing;
    • forced-relay list in both directions;
    • independent real Codex transcript ACK in both directions, while product results correctly kept consumptionConfirmed=false;
    • same-ID duplicate effect suppression, changed-payload conflict rejection, and unapproved-target rejection in both directions;
    • receiver restart with durable completed-request status;
    • invalid admission proof 401 → same ticket valid proof 200/attach → consumed-ticket replay 401;
    • wrong certificate pin rejection;
    • managed key rotation to generation 1, same-operation reconciliation, new-key success, and old-key rejection;
    • durable device revocation and closure of an attached relay connection;
    • cleanup of all validation receiver/helper processes and sockets.

    The Windows native core still behaved according to its current contract: discovery worked, while paired-device initialization rejected native Windows/Python 3.10. WSL2 enabled the endpoint test. One usability gap was reproduced: a WSL receiver can read a native Windows Codex home for list, but cannot send without an ad-hoc codex.exe / CODEX_HOME translation wrapper. Follow-up: #110.

    No credentials, tokens, private keys, certificates, device/session identifiers, host addresses, or transcript contents are included in this report. This validation does not claim direct-route, 24-hour, load, or cost coverage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions