docs/internal/agenthub-direct-handshake.md
AgentHub direct-handshake review
This is the owning ceremony and protocol transcript for direct client admission, endpoint
authorization, and application open: required ordering, not shipped screen copy. The ez-agent --hub flow is client-only preparation, trust prompts, durable recovery, fresh exact reconnects,
endpoint access, ordinary typed EzAgent JSONL, then the existing TUI over the owned remote
connection — there is no pre-TUI root or leaf chooser. Pairing creates bilateral eligibility; the normal-peer link implements and manages the
required fresh connection. Peer synchronization, routing, circuits, and routed pairing
transport are separate owners. Pairing sessions never enter this client ceremony.
The byte owners remain invitation, gateway,
TLS, and application; this document owns their
ordering and human trust checkpoints, while client transport,
storage, and service own implementation details.
Message kinds, bounds, and derivation formulas live in invitationwire, the owning pages, and
checked literal fixtures; this transcript does not restate them.
Never infer a second listener or compatibility format from the phases below.
Actors and independent inputs
| Actor | Identity and responsibility |
|---|---|
| Client operator | Controls the device key and protected client store; deliberately chooses the public Hub address and supplies independently received subject checks and JOIN WORDS. |
| Hub owner | Controls the Hub's local administration channel; obtains the claimant's check independently, records the immutable lock, shares the card, and approves separately. |
| Client transport | Loads the device credential, checks the subject before certificate disclosure, owns TLS/carrier sessions and client recovery, returns an owned JSONL handle. |
| Hub service | Owns the one public accept loop, role budgets, operational credential, authority lineage, invitation transitions, admission registry, and local control. |
| Endpoint owner and engine | The owner selects a locally configured AF_UNIX EzAgent socket and stable endpoint identity; the engine proves that identity and checks its ACL. |
| EzAgent service | Accepts ordinary JSONL on that configured socket only after endpoint authorization; receives no invitation secrets, makes no Hub trust decisions. |
Each identity card displays its role, four public KEY CHECK words, mandatory check byte, and full
lowercase SHA-256 SPKI fingerprint. Roles — Hub authority, client device, endpoint — cannot
substitute for one another, the five secret JOIN WORDS are a different value labelled separately,
and a candidate's own fingerprint is diagnostic, not independent input. The claimant supplies its
device check to the owner over an independent channel before invitation creation, and the owner
supplies the subject check to the client operator independently of candidate TLS or directory
data. A complete short tuple or an independently verified full fingerprint suffices; both together
must agree, four words without the check byte are insufficient, and a fingerprint never silently
overrides a contradictory tuple. Verified-subject cards label independently entered values matched
and candidate-derived values diagnostic-only; confirm acknowledges validation already completed by
the transport. The address is deliberate local input including its port; expiry, lineage, nonces,
and exporter bytes are server/protocol values, not voice inputs. Aliases are local labels, not
trust values, and neither a received record nor a claimed or approved response may create a
replacement dial address. The bare-Hub chooser displays each saved authority's fingerprint with a
local name action; name and last are reserved from aliases, and explicit aliases, addresses,
and last remain deliberate targets that bypass the chooser.
Displays and pauses before claiming
- Prepare or load the client-only device credential with
PrepareClientandOpenPreparedClientOnly; never create a Hub authority on the client just to join a remote Hub. For admission, display the claimant card and pause before any dial while the owner independently receives its check; forAdd agent, close the directory session, display the same card, and pause before endpoint invitation input. Saved reconnects and authorized rows skip this frontend-owned checkpoint — not callbacks provided byAdmit. - the closed
CreateAdmissionorCreateEndpointhook commits the private claimant lock before returning JOIN WORDS; an unbound invitation is not permitted. The card shows purpose, subject card, expiry, and the claimant-lock summary alongside the one-time JOIN WORDS, redacted in formatters and logs. The operator then enters the selected public address, independently supplied subject check, and JOIN WORDS; candidate TLS checks the authority check before disclosing the device certificate, while a saved Hub or unanswered request uses its exact pin instead. Admitcloses the verification connection beforeConfirmshows the verified authority card. The pause precedes hello, request persistence, selector disclosure, and proof; refusal creates no pending request. Confirmation opens a fresh connection to the same address with the request's exact authority ID and SPKI pin, never repeating candidate trust — a second checkpoint, not a replacement for step 1. Endpoint authorization callsConfirmafter exact endpoint TLS, before its claim.- A claim shows pending owner approval, not access granted; the owner approves only after the durable client ACK, and no confirmation callback may become an approval action or hide this wait. After JSONL startup the typed client enters the existing TUI, which owns the ready remote client until shutdown.
Admission over the one public address
Use H:P for the deliberately selected public Hub address, A for its stable authority, and D
for the claimant device. The service may bind a local address different from H:P; all client
dials still target H:P.
| Step | Network or local action | Durable effect and authorization |
|---|---|---|
| A1 | Client dials H:P. TLS 1.3 uses client-entry ALPN, an operational leaf signed by A, and a device certificate for D. Candidate verification precedes device-certificate disclosure. | Generic pre-TLS capacity is reserved before handshake allocation. ALPN alone grants no privileged capacity. TLS authentication is not admission. |
| A2 | After the confirmation checkpoint, derive root and selector from JOIN WORD indices and static context J. Prepare canonical request Q. | Client commits an unanswered pending row with Q, root, selector, prepared time, eight-day cutoff, and the locally selected address before sending hello or claim. A retry reuses this row and request ID. |
| A3 | Client reconnects to H:P with the exact unanswered authority pin, then sends gateway hello with operation: admission; server sends hello_ok and invitation_challenge. | Authenticated identity and valid operation permit transfer into invitation capacity, not ordinary admitted capacity. Challenge creation itself grants nothing. |
| A4 | Client sends invitation_request carrying claim exchange 1. | Server verifies role, SPKIs, request, nonces, exporter, and root proof before checking the private claimant lock. The first satisfying claim atomically commits immutable context C, recovery material, claimed response, and continuation manifest before any claimed response leaves. |
| A5 | Server returns invitation_response carrying claimed content's manifest and first chunk. Client requests subsequent chunks if needed. | No approval yet. Each chunk and assembled content must verify. Admission content includes complete signed authority lineage, not a dial address. |
| A6 | Client validates C, manifest, lineage, credential revision, and deadlines; commits the recovery credential and exact trusted entry. Then it sends ACK authenticated with the derived status key. | Credential installation and pending-row conversion are one client transaction. The unanswered root is removed. Failed persistence sends no ACK. Server ACK commit erases its recovery secret, claimed-response bytes, request copy, and continuation manifest; the acknowledged row becomes owner-approvable. |
| A7 | Server returns the current result, pending unless approval has already raced its response. Client polls with the status key while the owner separately reviews and approves the exact acknowledged request through local control. | Approval rechecks store revision, invitation revision, context, claimant lock, time, and authorization policy under the writer lock. Receipt and admission authorization commit together. Regrant of a revoked identity requires the explicit regrant operation. |
| A8 | Poll returns the approved result and receipt. | Client verifies receipt identity, context, profile, authorization revision, and optional access expiry before installing the result. The admission carrier ends. The client must establish a fresh ordinary exact-pinned connection; a claim carrier never turns into a gateway session. |
Q contains static purpose/profile and subject identity, selector, mode, subject SPKI, request
ID, claimant ID and SPKI — never expiry, connection nonces, or exporter material; C adds
server-owned expiry to that immutable identity. Admission binds authority subject to device
claimant; endpoint access binds endpoint subject to device claimant and ez-agent-jsonl/v1;
pairing is rejected by this client request codec. Client-entry ALPN is ez-agent-hub-client/1,
endpoint ALPN is ez-agent-hub-endpoint/1, and each connection exports 32 bytes under
EXPORTER-AgentHub-invitation-v1. Proof domains are role-distinct; a proof from another TLS
session, direction, role, request, or exchange fails. invitationwire owns the exporter context,
message kinds, exchange numbering, manifest bounds, replay, and the single six-byte invitation
failure (see invitation). No metadata preflight spends the invitation
before a root-authenticated claim, and no remote response distinguishes a lock mismatch from a
usable approval prospect.
Exact reconnect, endpoint approval, and application open
ConnectSavedHubreconnects to the same savedH:Pwith exact authority trust and current device credentials and sendshellowithoperation: gateway; admission authorization must pass beforehello_okreports admitted. Only successful ordinary exact-pinned connection advances local success order, and this path skips the claimant-card pause.- Send
list; the chooser presents the returned entries — only endpoint ID and canonical SPKI — as ordinary rows plusAdd agent. A row must match ID, SPKI, and the JSONL profile with no recognized revocation; an alias is display-only and cannot authorize.Add agentrequires the independently supplied endpoint check, with an agreeing full fingerprint when a short check is ambiguous — an advertised key alone does not authorize it — and never becomes row selection becauseEhas a cached descriptor: it resumes an exact durable pending request or starts a fresh invitation locked toD, permitting reauthorization of a stale grant; a failed row open starts no invitation. The client closes the chooser connection before human input, then reconnects and requires the same endpoint ID and SPKI in the fresh directory; row selection skips the claimant-card pause and ceremony but still validates live descriptors. - The client selects
Ewith purposeendpoint_access, receivesreadyaftertunnel/tunnel_ok, and runs exact endpoint TLS inside opaque gateway DATA frames — no second public dial or port. The endpoint certificate is the stable self-signed endpoint server leaf, independent of the Hub authority, and the inner connection's invitation exporter — not the outer client-entry exporter — binds the ceremony. The client closes this verification tunnel before confirmation, then repeats exact gateway and endpoint selection on a fresh tunnel with the local device unchanged, prepares a separate durableQ, and performs claim, continuation, credential installation, ACK, approval, and result as in A4 through A8; endpoint claimed content has the endpoint connection kind, not admission lineage or a replacement host/port. Approved result installation stores the private descriptor and receipt for the exact endpoint/profile/authorization epoch — admission does not grant this ACL. - Close the invitation path and start a fresh ordinary gateway session at
H:P; selectEwith purposeapplicationand repeatready,tunnel,tunnel_ok, then exact endpoint TLS. Inside it send applicationopenwithendpoint_id: Eandapplication: ez-agent-jsonl/v1; the engine checks identity, publication, and the live ACL epoch, dials the configured AF_UNIX socket once, and only then sendsopen_ok— denial, retirement, unpublication, or a failed dial produces no handoff. The returnedjsonlproxy.ClientHandleprovides ordinary JSONL bytes for the existing typed client throughpkg/ezagentapi.ConnectClientRW— no second RPC map or remote-only allowlist. Control readers read exact frame lengths without buffered read-ahead, so coalescedopen_okand first application data are not lost; JSONL hello and later messages occur here, not on an invitation carrier.
The authorization registry's replacement barrier serializes registration, BeginWork, and first
use against revocation, regrant, withdrawal, and endpoint retirement; store operations recheck
exact epochs and revisions at commit. Definite failure or idempotent replay invalidates no newer
lease; revocation and retirement close matching established work, withdrawal preserves it, and
uncertain persistence is fail-stop, never success. After authorization the flow enters the
existing TUI with no terminal root or leaf prompt. Startup CWD and endpoint-fingerprint-plus-CWD
recency are TUI-owned convenience state (canonical boundary in pkg/tui);
--cwd is exact TUI input to CWD-scoped RPCs, never hello input; startup stops before hello
without an explicit or endpoint-remembered CWD; recency is never trust input; and remote CWD is
never normalized or inspected locally.
Secret ownership
Erasure means the next committed snapshot omits the secret, not forensic erasure of filesystem
blocks or memory outside these owners. JOIN WORDS and indices are displayed once, never persisted
or logged, and cleared after durable request preparation or recovery selection and on every exit;
the store persists a derived root, never words. The shared session core owns nonces, exporters,
requests, proofs, and replay bytes with idempotent success/error/cancellation close. Root and
selector live in the client unanswered pending row before transmission and in hub private
unclaimed/claim state; credential installation removes its root; hub ACK erases the secret,
claimed response, request copy, and continuation manifest while retaining the status key for
bounded recovery; approval/rejection/cancellation/expiry erase claim material, and
compromise/conflict also erase selector and recovery lookup immediately. Receipt revocation
material is generated at approval and held in private authorization/result and approved-descriptor
state, never in public records; private keys are protected credential files that outlive the
ceremony. Unanswered rows expire at the eight-day cutoff; approval and result recovery use the
seven-day RecoveryLifetime; equality at a deadline is expired, not a replay opportunity;
security-time floors never move backward.
Interruptions and recovery
- A lost card reply is not a failed creation: JOIN WORDS are returned once,
never persisted for replay; cancel-by-row for a lost unclaimed card is deferred (see
contracts). Cancellation never rolls back committed state; a request lost
before hub commit retries the stored byte-identical
Q, never a fresh request ID. A lost-reply claim or crash before receipt retains the immutable claimed content and manifest while unacknowledged; the client retries the saved request on fresh TLS with fresh authentication. A failed credential write sends no ACK; uncertain persistence is reopened and revalidated, never success. - A committed ACK with a lost reply retries idempotently and returns the permitted current result; a root retry may receive only the empty acknowledged hint while pending. A lost durable credential is not reconstructible from the hint: fail closed, use a new owner-created invitation, never a secret-replay exception. A lost approval request/reply re-reads state and rejects a retry once approved; a lost approval result is recovered by status-key poll or credential recovery within retention, never replaced by a newer or revoked grant.
- Restart reuses only the durable request or credential phase; no session
nonce, exporter, active socket, or proof survives as an authenticated connection. Revocation, a
terminal transition, or an elapsed deadline racing a reply invalidates cached chunks, hints, and
results no longer permitted; retries never extend terminal retention. Losing ordinary
ready,tunnel_ok, oropen_okcloses the connection and requires a fresh exact-pinned ordinary path — no application-session replay across this boundary, and losingopen_okafter the AF_UNIX dial also tears down that local edge.
Lineage recovery opens a separate connection to the same H:P and sends the bounded AHLQ v1
request with the saved head ID before TLS; the accept owner returns AHLM v1 plus ordered AHLC
v1 chunks or a bounded failure. The client verifies the complete consecutive signed lineage
extension from the exact saved head and stages the strictly newer candidate outside accepted
Trust. Signed continuity is evidence, not approval. Before installation the client displays both
old/new KEY CHECK words, check bytes and full fingerprints and requires explicit local approval
or denial. Approval is bound to the exact candidate and current store revision; only its durable
commit advances the pin and permits fresh exact TLS. Denial is durable and retains the old pin.
Missing, failed, cancelled or stale decisions do not advance trust; a signed fork quarantines
without an ordinary approval override. An uncertain commit publishes no live trust or success
and poisons the store. Restart strictly loads whichever complete valid snapshot is on disk,
which may include a post-rename approval. The unauthenticated transfer itself grants no
privilege, is not a metadata preflight, and supplies no address. Gateway cancellation uses cancel/cancelled where state permits it; closing a consumed
GatewaySession does not close a transferred tunnel — its new owner does — and application
cancellation joins both tunnel pumps and the JSONL adapter, releasing reservations once.
Compromise and conflict rules, including leaked JOIN WORDS used before the intended claimant, are
owned by the invitation contract.
Bilateral pairing boundary
The pairing connection uses ez-agent-hub-pairing/1 and the dedicated
EXPORTER-AgentHub-pairing-v1, never the client invitation, hop, or circuit exporter. The pairing engine
uses InitialPairingConn to obtain both authority IDs and SPKIs without trusting a TLS generation,
then verifies signed Claim/Context lineages against durable pairing transactions.
It does not enter client gateway framing. The reviewed
pairing-handshake contract and pairingwire own bilateral
payloads, framing, approvals, and durable activation eligibility. The normal-peer link owns every fresh
normal-peer connection.
All source paths live under internal/agenthub/; literals and checker commands are indexed in
the fixture README. invitationwire is the one client
invitation codec owner; pairingwire is the separate reviewed authority-pairing codec. Neither
adds an EzAgent JSONL message.
Common evidence and presentation boundary
The identity package owns role-specific matching and canonical public presentation. Admission TLS, claimant locks, endpoint resolution, confirmation screens and local identity projections use it rather than independent word/byte/fingerprint checks. The frontend's common renderer labels matched independent values separately from candidate diagnostics and rejects altered or wrong-role presentation records before output. There is no accept-anyway action. Endpoint authorization carries the independent evidence into the transport's pre-certificate check, not merely into a later confirmation callback. Client persist-before-ACK, approve-after-ACK, status-key recovery and exact deadline equality remain unchanged.
The composed entry lifecycle retires its raw callback before typed gateway, pairing or peer handling. Endpoint preparation similarly retires before its application/invitation handler. Phase callbacks are joined before the next phase adopts I/O; capacities stay owned until the relevant worker joins. This preserves pairing graceful close instead of racing it with entry Abort. Complete key presentations validate canonical SPKI and all provenance fields before any confirmation output. Caller-owned structured JOIN material has explicit consume/close operations on success, cancellation and error paths.
Private administration migration
The owner's local commands now use concrete pkg/ezhubapi JSONL requests/results
through authenticated AF_UNIX control.sock, with a shared online Client and
typed locked offline administration only when the socket is absent. The removed
localcontrol protocol has no aliases or fallback. Committed effects/audits,
claimant locks, exact revisions, client ACK ordering and joined cancellation
remain domain responsibilities. This does not change any network handshake,
public EzAgent JSONL or durable format described above.
Add Hub returns the exact durable checkpoint with its IDs and commit revision.
A definitely committed Prepared followed by carrier loss returns prepared;
durable Context returns accepted. Either result opens or wakes one pairing
view and prioritizes an immediate exact check. Pre-Prepared failures remain
ordinary errors, and persistence uncertainty never fabricates a checkpoint.
See private administration.