@agentproto/pairing-host 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # @agentproto/pairing-host
2
+
3
+ Host-side AIP-59 pairing for anything that wants to be a pairing host, not only
4
+ the agentproto daemon. Depends on `@agentproto/acp`, `@agentproto/secrets` and
5
+ `ws` only.
6
+
7
+ - `createPairingRegistry(deps)`: offers, accept handshake over an untrusted
8
+ rendezvous, `pairings.json` persistence, epoch reconnect, revocation.
9
+ Dependency-injected (`loadIdentity`, `dial`, `serve`, `pairingsPath`).
10
+ - `dialRendezvous(url, signal, { agent? })`: default WebSocket dial.
11
+ - `serveLoopbackHttp({ target, injectHeaders?, allowPaths? })`: a `serve`
12
+ that forwards the paired, E2E-wrapped channel to a loopback HTTP app.
13
+ - `registry.mintLocalDevice({ name })` / `registry.verifyDeviceBearer(bearer)`:
14
+ optional local-device credential for loopback clients. The bearer is derived
15
+ from a per-device secret kept in `pairings.json` (`localDevices`, optional,
16
+ mode 0600); it is shown once at mint time, never logged, and `revoke()` makes
17
+ the very next verify fail.
18
+
19
+ ```ts
20
+ import { createPairingRegistry, dialRendezvous, serveLoopbackHttp } from "@agentproto/pairing-host"
21
+
22
+ const registry = createPairingRegistry({
23
+ loadIdentity,
24
+ pairingsPath,
25
+ dial: (url, signal) => dialRendezvous(url, signal),
26
+ serve: serveLoopbackHttp({
27
+ target: new URL("http://127.0.0.1:8123"),
28
+ injectHeaders: { authorization: `Bearer ${localToken}` },
29
+ allowPaths: ["/mcp"],
30
+ }),
31
+ })
32
+ ```
@@ -0,0 +1,350 @@
1
+ import { FrameSink, E2eFrameSink } from '@agentproto/acp/tunnel';
2
+ import { RouteAuthTokens } from '@agentproto/secrets/pairing';
3
+ import { DaemonIdentity } from '@agentproto/secrets/identity';
4
+ import { Agent } from 'node:http';
5
+
6
+ /**
7
+ * Host-side pairing registry (design: DESIGN §3/§4, PLAN deliverable 2). Lives
8
+ * in `@agentproto/pairing-host` so any AIP-59 host — the agentproto daemon is
9
+ * one, a standalone app is another — can embed it; `@agentproto/runtime`
10
+ * re-exports it unchanged.
11
+ *
12
+ * Owns everything a host needs to be *paired with* over an untrusted
13
+ * rendezvous:
14
+ *
15
+ * - **Offer store** — in-memory, single-use, expiry-checked one-time offer
16
+ * secrets minted by `pair offer`. A daemon restart voids outstanding offers
17
+ * (acceptable + documented). The daemon parks on the offer's ROUTE token and
18
+ * the handshake's `verifyAuthToken` predicate checks the sealed AUTH token,
19
+ * SPENDING the offer on the first successful handshake (a wrong token spends
20
+ * nothing).
21
+ * - **Pairings store** — `~/.agentproto/pairings.json` (0600, atomic write),
22
+ * one record per paired client: `{clientPub, name, fingerprint, createdAt,
23
+ * lastSeen, pairRoot, rendezvousUrl}`. `pairRoot` is the long-term shared
24
+ * secret (`derivePairRoot`) from which reconnect routing tokens derive.
25
+ * - **Rendezvous connections** — for a fresh offer, and for every persisted
26
+ * pairing on boot (autoconnect), the daemon dials the rendezvous *outbound*
27
+ * (`side=daemon&t=<route>`), runs `daemonHandshakeOverSink` with the P1
28
+ * crypto, and — on success — serves the spliced, E2E-wrapped channel exactly
29
+ * like `serve --connect` serves a tunnel host. The serving path itself is
30
+ * injected (`serve`) so this module stays free of pty/adapter concerns and
31
+ * the CLI can reuse its `createTunnelServer` config verbatim.
32
+ * - **Reconnect epochs** — a persisted pairing's standing connection parks on
33
+ * the pairing-derived route `HKDF(pairRoot, "rv-route"‖epoch)`, rotated per
34
+ * UTC day. The daemon parks on BOTH the current and previous
35
+ * epoch tokens so a client whose clock straddles midnight still finds it;
36
+ * reconnect-with-backoff keeps the standing connection alive.
37
+ * - **Revocation** — removing a pairing drops its rendezvous connections, so
38
+ * it can no longer be served. For a grace period (`revokedGraceMs`, default
39
+ * 14 days) the daemon keeps a *tombstone*: it still parks on the pairing's
40
+ * epoch ROUTES, completes the (daemon-signed) handshake only for a hello
41
+ * carrying that epoch's AUTH token, and answers with a single E2E-encrypted
42
+ * `error{code:"pairing_revoked"}` frame before closing — never serving the
43
+ * channel. That is what lets a client tell "unpaired" from "daemon
44
+ * offline" (which both otherwise look like a park timeout at the broker)
45
+ * and stop retrying. The signal is authenticated like every tunnel frame:
46
+ * it arrives inside the AEAD channel of a handshake whose transcript the
47
+ * client verified against the pinned daemon key, so the broker can't forge
48
+ * it; and the broker, which knows the routes, can't elicit it either (no
49
+ * auth token). A tombstone keeps only the per-epoch route + auth tokens for
50
+ * its window — the pair root is dropped at revoke.
51
+ *
52
+ * ## Reconnect authentication (why no stable client key)
53
+ *
54
+ * The handshake carries only a client *ephemeral* key (regenerated per
55
+ * handshake) — there is no persistent client identity key. So a reconnect
56
+ * authenticates the client by **possession of the epoch AUTH token**
57
+ * `HKDF(pairRoot, "rv-auth"‖epoch)`, which derives from `pairRoot` — a secret
58
+ * only the paired client and daemon share (it fell out of the original ECDH).
59
+ * The daemon parks on the pairing's epoch ROUTE, and on that connection the
60
+ * `verifyAuthToken` predicate accepts a hello whose sealed auth equals the same
61
+ * epoch's auth token (constant-time). The route and auth are separate one-way
62
+ * HKDF outputs: the broker sees every route and can't compute an auth from it.
63
+ * (pair/v1 used ONE value for both, so a broker could replay a logged route as
64
+ * the proof and be served.) The stored `fingerprint` (of the first handshake's
65
+ * ephemeral key) is a stable display/revocation handle, not an auth input.
66
+ *
67
+ * ## Legacy (pair/v1) pairings
68
+ *
69
+ * A v1 `pairings.json` is loaded with every record flagged `legacy`: listed and
70
+ * revocable, never served. The daemon still parks on a legacy pairing's routes
71
+ * (the epoch route is unchanged from v1) so that pairing's not-yet-upgraded
72
+ * client reaches it and is told to re-pair — see `respondToLegacyHandshake` —
73
+ * rather than timing out. v1 records are not upgraded in place: v1 let the
74
+ * broker pair as a client, so any v1 record may be the broker's own.
75
+ */
76
+
77
+ /** `pairings.json` format. v2 = pairings made under pair/v2 (route/auth
78
+ * split). A v1 file still loads, every record flagged `legacy`. */
79
+ declare const PAIRINGS_VERSION: 2;
80
+ /** One persisted pairing. Written verbatim to `pairings.json`. */
81
+ interface PairingRecord {
82
+ /** The client ephemeral public key from the FIRST handshake (a snapshot —
83
+ * reconnects use fresh ephemerals; this is not an auth input). */
84
+ clientPub: string;
85
+ /** Human-facing label the client chose on `pair accept`. */
86
+ name: string;
87
+ /** `identityFingerprint(clientPub)` from the first handshake — the stable
88
+ * display + revocation handle. */
89
+ fingerprint: string;
90
+ /** ISO-8601 first-pair timestamp. */
91
+ createdAt: string;
92
+ /** ISO-8601 of the most recent successful (re)connect. */
93
+ lastSeen: string;
94
+ /** Long-term shared secret (base64), from which epoch routing tokens derive. */
95
+ pairRoot: string;
96
+ /** Rendezvous endpoint to reconnect through. */
97
+ rendezvousUrl: string;
98
+ /** Set on a pairing made under the retired pair/v1 protocol: listed and
99
+ * revocable, never served — its client is told to re-pair. */
100
+ legacy?: true;
101
+ /** Set when this pairing was made under an offer minted with
102
+ * `agentproto pair offer --host` (PR-C) — i.e. the offering daemon's own
103
+ * intent, recorded server-side at handshake time from the OfferEntry it
104
+ * itself created, never from the (unauthenticated) `scope` param a client
105
+ * presented in the offer URL. Absent for an ordinary remote-control
106
+ * pairing. Purely informational here — it does not change how this
107
+ * pairing is served. */
108
+ scope?: "host";
109
+ /** Set on a record returned by `list()` for a local device (see "Local
110
+ * devices"): it has no rendezvous, `clientPub`/`pairRoot`/`rendezvousUrl`
111
+ * are empty strings. Never written to the `pairings` array of the file. */
112
+ local?: true;
113
+ }
114
+ /** A revoked pairing still answered with `pairing_revoked` until `expiresAt`
115
+ * (see "Revocation" above). Persisted in `pairings.json` under `revoked`. */
116
+ interface RevokedPairingRecord {
117
+ /** The revoked pairing's fingerprint. */
118
+ fingerprint: string;
119
+ /** Its client label. */
120
+ name: string;
121
+ /** Rendezvous endpoint its client reconnects through. */
122
+ rendezvousUrl: string;
123
+ /** ISO-8601 revocation time. */
124
+ revokedAt: string;
125
+ /** ISO-8601 end of the grace window; the tombstone is dropped after it. */
126
+ expiresAt: string;
127
+ /** The epoch route (parked on) + auth (verified) tokens covering the window
128
+ * (previous epoch at revoke time through the epoch of `expiresAt`) —
129
+ * derived from the pair root at revoke time so the root itself need not be
130
+ * kept. */
131
+ routes: ({
132
+ epoch: number;
133
+ } & RouteAuthTokens)[];
134
+ }
135
+ /** The tunnel `error` code a revoked pairing's client receives. */
136
+ declare const PAIRING_REVOKED_CODE: "pairing_revoked";
137
+ /** Mode of a served channel — first-contact offer vs. an established reconnect. */
138
+ type PairingChannelMode = "offer" | "reconnect";
139
+ /** Context handed to the injected `serve` when a channel comes up. */
140
+ interface PairingChannelContext {
141
+ mode: PairingChannelMode;
142
+ /** Stable pairing fingerprint (present for reconnect; for an offer it's the
143
+ * freshly-derived one). */
144
+ fingerprint: string;
145
+ /** Client label. */
146
+ name: string;
147
+ /** This pairing's OWN recorded scope (mirrors `PairingRecord.scope`) —
148
+ * `"host"` when the offer that produced it was minted with
149
+ * `agentproto pair offer --host`, absent for an ordinary remote-control
150
+ * pairing. Present on BOTH the offer and every reconnect context, so
151
+ * `serve` can gate scope-restricted routes (e.g. device-inference
152
+ * proxying) the same way on first contact and on every later reconnect. */
153
+ scope?: "host";
154
+ }
155
+ /** Handle to a live served channel — the registry closes it on teardown. */
156
+ interface PairingChannelHandle {
157
+ close(): Promise<void>;
158
+ }
159
+ interface CreatedOffer {
160
+ /** The one-time offer secret (base64url) — the URL's `s`. Never on the wire:
161
+ * the broker only ever sees its derived route. */
162
+ secret: string;
163
+ /** Offer expiry, unix seconds. */
164
+ exp: number;
165
+ /** The full `agentproto://pair?…` offer URL. */
166
+ url: string;
167
+ /** The daemon's identity fingerprint (shown to the human at accept time). */
168
+ fingerprint: string;
169
+ /** The rendezvous the offer routes through. */
170
+ rendezvousUrl: string;
171
+ /** True when `rendezvousUrl` is the hosted default — i.e. neither an explicit
172
+ * `--rendezvous` nor a configured `pairing.rendezvous` applied, so the offer
173
+ * falls back to `HOSTED_RENDEZVOUS_URL`. Surfaced so `pair offer` can flag,
174
+ * never silently, that the daemon is relaying through our infrastructure. */
175
+ rendezvousIsHostedDefault: boolean;
176
+ /** Echoes `CreateOfferInput.scope`. `"host"` when minted with `--host`;
177
+ * absent for a plain offer. */
178
+ scope?: "host";
179
+ }
180
+ interface CreateOfferInput {
181
+ /** Time-to-live in ms. Default 10 minutes. */
182
+ ttlMs?: number;
183
+ /** Rendezvous URL override; falls back to the configured default. */
184
+ rendezvousUrl?: string;
185
+ /** Mint a HOST-scoped offer (PR-C): the accepting side may register this
186
+ * daemon as a driveable host (`devices add`), not just remote-control it.
187
+ * Recorded on the resulting `OfferEntry`/`PairingRecord` server-side — this
188
+ * is the authoritative record of what was granted, independent of the
189
+ * `scope` param an accepting client's offer URL happens to carry. */
190
+ scope?: "host";
191
+ }
192
+ interface PairingRegistryDeps {
193
+ /** Lazily load (create on first use) the daemon identity. Kept lazy so a
194
+ * daemon that never pairs never writes an identity file. */
195
+ loadIdentity: () => Promise<DaemonIdentity>;
196
+ /** Path to `pairings.json`. Defaults to `~/.agentproto/pairings.json`. */
197
+ pairingsPath?: string;
198
+ /** Configured rendezvous URL (from `config.pairing.rendezvous`). Three states:
199
+ * - `undefined` (key absent) → `createOffer` falls back to the hosted default
200
+ * (`HOSTED_RENDEZVOUS_URL`).
201
+ * - a non-empty URL → that endpoint is the default for offers.
202
+ * - `""` (explicitly empty) → an explicit opt-out: no default applies, so an
203
+ * offer without `--rendezvous` fails closed. Wire it through verbatim (do
204
+ * not coerce `""` to `undefined`) or the opt-out silently reverts to the
205
+ * hosted default. */
206
+ defaultRendezvousUrl?: string;
207
+ /** Dial a rendezvous WS and adapt it to a FrameSink. Injected by the CLI
208
+ * (uses `ws` + `wrapWebSocket`). Rejects if the dial fails. The `signal`
209
+ * aborts on registry shutdown. */
210
+ dial: (wsUrl: string, signal: AbortSignal) => Promise<FrameSink>;
211
+ /** Serve the E2E-wrapped channel (the CLI builds `createTunnelServer` over
212
+ * it with the same config `serve --connect` uses). */
213
+ serve: (sink: E2eFrameSink, ctx: PairingChannelContext) => PairingChannelHandle;
214
+ /** Injectable clock (ms). Defaults to Date.now. */
215
+ now?: () => number;
216
+ /** Diagnostic log sink. */
217
+ log?: (line: string) => void;
218
+ /** Reconnect backoff floor / ceiling (ms). Defaults 1s / 30s. */
219
+ reconnectMinMs?: number;
220
+ reconnectMaxMs?: number;
221
+ /** How long a parked daemon socket waits for a client hello before recycling
222
+ * the connection. Kept just under the broker's park timeout. Default 110s. */
223
+ handshakeTimeoutMs?: number;
224
+ /** How long a revoked pairing is still answered with `pairing_revoked` (see
225
+ * "Revocation" above). Default 14 days; `0` disables tombstones, so a
226
+ * revoked client just stops finding the daemon. */
227
+ revokedGraceMs?: number;
228
+ }
229
+ interface PairingRegistry {
230
+ /** Mint a one-time offer + start dialing the rendezvous for it. */
231
+ createOffer(input?: CreateOfferInput): Promise<CreatedOffer>;
232
+ /** All persisted pairings (copies). Loads `pairings.json` on first call. */
233
+ list(): Promise<PairingRecord[]>;
234
+ /** Rename a pairing by fingerprint or name (cosmetic only — no effect on
235
+ * auth or routing). Returns false when nothing matched; throws on an
236
+ * empty `newName`. */
237
+ rename(idOrName: string, newName: string): Promise<boolean>;
238
+ /** Drop a pairing by fingerprint or name; stops its rendezvous connections.
239
+ * Returns false when nothing matched. */
240
+ revoke(idOrName: string): Promise<boolean>;
241
+ /** Is a channel (offer or reconnect) currently served for this fingerprint? */
242
+ isOnline(fingerprint: string): boolean;
243
+ /** Start standing reconnect connections for every persisted pairing. Call
244
+ * after the gateway is up (so the injected `serve` can reach it). */
245
+ startAutoconnect(): Promise<void>;
246
+ /** Tear down every offer + reconnect connection and served channel. */
247
+ shutdown(): Promise<void>;
248
+ }
249
+ /** What `mintLocalDevice` hands back. `bearer` is shown ONCE to the caller
250
+ * (write it to the client's config); the host never logs or stores it. */
251
+ interface LocalDeviceCredential {
252
+ bearer: string;
253
+ fingerprint: string;
254
+ name: string;
255
+ createdAt: string;
256
+ }
257
+ /** The registry `createPairingRegistry` returns: the daemon-facing
258
+ * `PairingRegistry` plus the optional local-device credential. */
259
+ interface PairingHostRegistry extends PairingRegistry {
260
+ /** Mint a paired-device record for a loopback client and return its bearer.
261
+ * Visible in `list()`, revocable with `revoke()`. Throws on an empty name. */
262
+ mintLocalDevice(input: {
263
+ name: string;
264
+ }): Promise<LocalDeviceCredential>;
265
+ /** Constant-time check of a device bearer. `null` for anything unknown,
266
+ * malformed or revoked; a revoke is honoured on the very next call. */
267
+ verifyDeviceBearer(bearer: string): Promise<{
268
+ fingerprint: string;
269
+ name: string;
270
+ } | null>;
271
+ }
272
+ /**
273
+ * Read-only snapshot of `pairings.json` for callers that just want the
274
+ * persisted records — no `dial`/`serve`/`loadIdentity` deps, no rendezvous
275
+ * connections started (e.g. `agentproto doctor`'s devices check). Mirrors
276
+ * `ensureLoaded`'s parse + v1-legacy flagging; never throws — a missing or
277
+ * malformed file just yields `[]`.
278
+ */
279
+ declare function readPairingsSnapshot(path?: string): Promise<PairingRecord[]>;
280
+ declare function createPairingRegistry(deps: PairingRegistryDeps): PairingHostRegistry;
281
+
282
+ /**
283
+ * Rate-limited failure logging for reconnect loops.
284
+ *
285
+ * A standing reconnect loop (the outbound tunnel, a pairing rendezvous) whose
286
+ * peer is permanently gone re-dials on backoff forever. Logging every single
287
+ * failure buries the daemon log — a single dead pairing produced ~85% of one
288
+ * 2.9MB never-rotated `~/.agentproto/daemon.log`, and the tunnel reconnect
289
+ * spam another chunk. This gate logs the FIRST failure per key immediately,
290
+ * then at most one line per `windowMs`, and when it does emit again it carries
291
+ * the count of failures it swallowed in between. A successful connect resets
292
+ * the key so the next outage logs promptly again.
293
+ *
294
+ * Deliberately dependency-free: a per-key `{ lastLoggedAt, suppressed }` map.
295
+ * `now` is injectable so tests can advance the clock without real timers. This
296
+ * only changes logging cadence — reconnect timing/backoff is untouched.
297
+ */
298
+ interface ReconnectLogGate {
299
+ /**
300
+ * Record a failure for `key`. Returns the line to log now — the given
301
+ * `message`, with a `(N failures suppressed)` suffix when repeats were
302
+ * swallowed since the last emit — or `null` to stay quiet this time.
303
+ */
304
+ onFailure(key: string, message: string): string | null;
305
+ /** Reset suppression for `key` after a successful connect. */
306
+ onSuccess(key: string): void;
307
+ }
308
+ declare function createReconnectLogGate(opts?: {
309
+ windowMs?: number;
310
+ now?: () => number;
311
+ }): ReconnectLogGate;
312
+
313
+ interface DialRendezvousOptions {
314
+ /** A `ws`-compatible agent (e.g. an HTTPS proxy agent). `ws` ignores
315
+ * `HTTPS_PROXY` on its own, so a host behind a proxy passes one here. */
316
+ agent?: Agent;
317
+ }
318
+ /**
319
+ * Dial a rendezvous broker outbound and adapt the socket to a `FrameSink`.
320
+ * The default `PairingRegistryDeps.dial`. Rejects if the dial fails; honours
321
+ * `signal` so a registry shutdown tears down an in-flight dial promptly.
322
+ */
323
+ declare function dialRendezvous(url: string, signal: AbortSignal, opts?: DialRendezvousOptions): Promise<FrameSink>;
324
+
325
+ interface ServeLoopbackHttpOptions {
326
+ /** The local HTTP app the paired channel is forwarded to. Must be a
327
+ * loopback http(s) URL (127.0.0.0/8, ::1 or localhost): a paired peer must
328
+ * never be able to steer the host at another machine. */
329
+ target: URL | string;
330
+ /** Headers set on EVERY forwarded request, overriding any same-named header
331
+ * the peer sent (e.g. the host app's own bearer). */
332
+ injectHeaders?: Readonly<Record<string, string>>;
333
+ /** Pathnames a peer may request. `"/mcp"` matches exactly, `"/api/*"`
334
+ * matches `/api` and everything below it, a RegExp is tested against the
335
+ * pathname. Omitted: any path. `[]`: nothing. A denied request gets a 403
336
+ * `path_not_allowed` response and never reaches the target. */
337
+ allowPaths?: readonly (string | RegExp)[];
338
+ /** Label in the tunnel hello. Default "loopback-http". */
339
+ label?: string;
340
+ httpForwardTimeoutMs?: number;
341
+ }
342
+ /**
343
+ * Build a `PairingRegistryDeps.serve` that forwards the paired, E2E-wrapped
344
+ * channel to a local HTTP app: `http_request` frames become fetches against
345
+ * `target` (with `injectHeaders` applied), responses stream back. Spawn, PTY
346
+ * and WebSocket frames are not served.
347
+ */
348
+ declare function serveLoopbackHttp(opts: ServeLoopbackHttpOptions): (sink: E2eFrameSink, ctx: PairingChannelContext) => PairingChannelHandle;
349
+
350
+ export { type CreateOfferInput, type CreatedOffer, type DialRendezvousOptions, type LocalDeviceCredential, PAIRINGS_VERSION, PAIRING_REVOKED_CODE, type PairingChannelContext, type PairingChannelHandle, type PairingChannelMode, type PairingHostRegistry, type PairingRecord, type PairingRegistry, type PairingRegistryDeps, type ReconnectLogGate, type RevokedPairingRecord, type ServeLoopbackHttpOptions, createPairingRegistry, createReconnectLogGate, dialRendezvous, readPairingsSnapshot, serveLoopbackHttp };