@agentproto/pair-client 0.2.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 +202 -0
- package/README.md +137 -0
- package/dist/index.d.ts +307 -0
- package/dist/index.mjs +776 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +69 -0
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,137 @@
|
|
|
1
|
+
# @agentproto/pair-client
|
|
2
|
+
|
|
3
|
+
The browser side of agentproto E2E daemon pairing. A phone (or any browser
|
|
4
|
+
tab, worker or service worker) scans the QR from `agentproto pair offer --qr`,
|
|
5
|
+
pairs with the daemon through the rendezvous broker, and from then on reaches
|
|
6
|
+
it with a plain WHATWG `fetch`: streamed bodies and SSE included, every
|
|
7
|
+
request multiplexed over one end-to-end encrypted WebSocket. The broker only
|
|
8
|
+
ever sees ciphertext.
|
|
9
|
+
|
|
10
|
+
It speaks the same `pair/v1` handshake and `agentproto/tunnel/v1` frames as
|
|
11
|
+
the Node CLI (`agentproto pair accept` / `pair exec`), so the daemon can't
|
|
12
|
+
tell the two clients apart. It is browser-safe: no `node:` import, no
|
|
13
|
+
`Buffer`/`process`, WebCrypto only. A test bundles it for the browser and runs
|
|
14
|
+
a real pair + fetch in a realm that has only web globals.
|
|
15
|
+
|
|
16
|
+
## Pair
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { inspectOffer, pairFromOffer, createIndexedDbCredentialStore } from "@agentproto/pair-client"
|
|
20
|
+
|
|
21
|
+
const store = createIndexedDbCredentialStore()
|
|
22
|
+
|
|
23
|
+
// No network: what the QR says.
|
|
24
|
+
const info = await inspectOffer(location.href) // { fingerprint, rendezvousUrl, expiresAt }
|
|
25
|
+
|
|
26
|
+
// Handshake (spends the one-time offer), then show the daemon to the user.
|
|
27
|
+
const pending = await pairFromOffer(location.href, { store, clientName: "Jeremy's phone" })
|
|
28
|
+
showConfirm(pending.daemon.name, pending.daemon.fingerprint)
|
|
29
|
+
const credential = await pending.confirm() // stored; or pending.cancel()
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**One origin per daemon.** `pair offer --qr` points at a per-daemon page by
|
|
33
|
+
default, `https://{fp}.agentproto.cloud/pair` (`pairing.pairPage` or
|
|
34
|
+
`--pair-page` change it). A page built for that must check that it's on its
|
|
35
|
+
daemon's origin before pairing (AIP-59 §5.8):
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { expectedPairHost, inspectOffer, PAIR_WEB_URL_TEMPLATE_CLOUD } from "@agentproto/pair-client"
|
|
39
|
+
|
|
40
|
+
const info = await inspectOffer(location.href)
|
|
41
|
+
if (location.host !== expectedPairHost(PAIR_WEB_URL_TEMPLATE_CLOUD, info.fingerprint)) {
|
|
42
|
+
throw new Error("this pairing QR is for another daemon's page")
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`pairFromOffer` accepts both offer forms: the web link
|
|
47
|
+
`https://<fingerprint>.agentproto.cloud/pair#v=2&rv=…` (the offer rides in the fragment,
|
|
48
|
+
which is never sent to a server) and the plain `agentproto://pair?…` URL.
|
|
49
|
+
|
|
50
|
+
The daemon records the pairing as soon as the handshake succeeds, the same as
|
|
51
|
+
for `pair accept`. `cancel()` only drops it on this side; remove the daemon's
|
|
52
|
+
record with `agentproto pair revoke`.
|
|
53
|
+
|
|
54
|
+
## Connect and fetch
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { connect } from "@agentproto/pair-client"
|
|
58
|
+
|
|
59
|
+
const client = connect(credential, { store })
|
|
60
|
+
client.onStateChange(({ state, error }) => render(state, error?.message))
|
|
61
|
+
// state: "connecting" | "open" | "offline" | "revoked" | "outdated" | "closed"
|
|
62
|
+
|
|
63
|
+
const res = await client.fetch("/sessions") // a real Response
|
|
64
|
+
const events = await client.fetch("/events", { signal }) // res.body streams chunk by chunk
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- **Multiplexing:** any number of concurrent requests share one channel.
|
|
68
|
+
- **Streaming:** `http_response_head` resolves the `Response`. The body is a
|
|
69
|
+
`ReadableStream` fed by each `http_response_chunk` as it arrives, so SSE works.
|
|
70
|
+
- **Abort:** aborting the signal, or cancelling the body, sends `http_cancel` and
|
|
71
|
+
the daemon stops its upstream request.
|
|
72
|
+
- **Reconnect:** jittered exponential backoff, capped (500 ms → 30 s by
|
|
73
|
+
default). In-flight requests fail with `TunnelClientError{code:"disconnected"}`.
|
|
74
|
+
New requests wait for the reconnect, or fail with `offline` after
|
|
75
|
+
`requestWaitMs`. A ping/pong keepalive catches half-open sockets.
|
|
76
|
+
- **Revocation:** after `agentproto pair revoke` the daemon answers this
|
|
77
|
+
pairing with an authenticated `pairing_revoked` frame inside the E2E channel.
|
|
78
|
+
The client goes to `revoked`, stops retrying, and every call rejects with
|
|
79
|
+
`TunnelClientError{code:"revoked"}`: "this device was unpaired from
|
|
80
|
+
<daemon>; scan a new pairing QR". The broker can't forge that signal.
|
|
81
|
+
|
|
82
|
+
- **Protocol:** pair/v2. Each connection derives a *route* token and an *auth*
|
|
83
|
+
token (from the offer secret, or from the pair root and the day). Only the
|
|
84
|
+
route goes on the broker URL; the auth is sealed into the hello. A v1 offer,
|
|
85
|
+
or a credential stored before v2, gives `TunnelClientError{code:
|
|
86
|
+
"protocol_outdated"}` (state `outdated`) and is never dialed: upgrade the
|
|
87
|
+
daemon and scan a new QR.
|
|
88
|
+
|
|
89
|
+
The daemon keeps one standing channel per epoch slot for each pairing, so
|
|
90
|
+
share one `TunnelClient` per credential. Don't connect twice.
|
|
91
|
+
|
|
92
|
+
## In a service worker
|
|
93
|
+
|
|
94
|
+
The package runs in a service worker: `WebSocket`, `crypto.subtle`,
|
|
95
|
+
`indexedDB`, `fetch` types and streams are all there. Keep one client per
|
|
96
|
+
credential at module scope and use it for every `fetch` event:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { connect, createIndexedDbCredentialStore } from "@agentproto/pair-client"
|
|
100
|
+
|
|
101
|
+
const store = createIndexedDbCredentialStore()
|
|
102
|
+
const clients = new Map<string, ReturnType<typeof connect>>()
|
|
103
|
+
|
|
104
|
+
async function clientFor(id: string) {
|
|
105
|
+
let c = clients.get(id)
|
|
106
|
+
if (!c || c.state === "closed") {
|
|
107
|
+
const cred = await store.get(id)
|
|
108
|
+
if (!cred) throw new Error("not paired")
|
|
109
|
+
const prefix = `/d/${id}`
|
|
110
|
+
c = connect(cred, { store, mapPath: url => url.pathname.slice(prefix.length) + url.search })
|
|
111
|
+
clients.set(id, c)
|
|
112
|
+
}
|
|
113
|
+
return c
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
self.addEventListener("fetch", (event: FetchEvent) => {
|
|
117
|
+
const m = new URL(event.request.url).pathname.match(/^\/d\/([0-9a-f]{32})\//)
|
|
118
|
+
if (!m) return
|
|
119
|
+
event.respondWith(clientFor(m[1]!).then(c => c.fetch(event.request)))
|
|
120
|
+
})
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
The browser may stop an idle service worker. The next `fetch` event then
|
|
124
|
+
builds a new client, which reconnects in about one round trip.
|
|
125
|
+
|
|
126
|
+
## Credential storage
|
|
127
|
+
|
|
128
|
+
`CredentialStore` is `{ get, put, delete, list }`:
|
|
129
|
+
|
|
130
|
+
- `createIndexedDbCredentialStore()` works in a window or a worker, scoped to
|
|
131
|
+
the origin.
|
|
132
|
+
- `createMemoryCredentialStore()` is for tests.
|
|
133
|
+
|
|
134
|
+
Nothing is written to localStorage. The pair root is imported as a
|
|
135
|
+
**non-extractable** WebCrypto HKDF `CryptoKey`, and IndexedDB stores the key
|
|
136
|
+
object as-is. Script can derive the day's routing token with it but can't
|
|
137
|
+
read the secret back out.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { HelloFrame } from '@agentproto/acp/tunnel/browser';
|
|
2
|
+
export { DEFAULT_PAIR_PAGE, PAIR_PAGE_FP_PLACEHOLDER, PAIR_WEB_URL, PAIR_WEB_URL_TEMPLATE_CLOUD, encodeOfferWebUrl, expectedPairHost, resolvePairPageUrl } from '@agentproto/secrets/pairing/browser';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One E2E channel to the daemon through the rendezvous: dial the broker, run
|
|
6
|
+
* the `pair/v1` client handshake, and read the daemon's greeting.
|
|
7
|
+
*
|
|
8
|
+
* This is the Node client's `acceptOffer` / `openPairChannel` sequence
|
|
9
|
+
* (`packages/cli/src/util/pair-transport.ts`) — same upgrade URL, same pair/v2
|
|
10
|
+
* hello (static keys pinned, the client name, and the AUTH token sealed to the
|
|
11
|
+
* daemon's key), same verification — built only from the browser-safe
|
|
12
|
+
* entries, so the daemon can't tell the two clients apart. The ROUTE token is
|
|
13
|
+
* the only thing on the broker URL; the auth token never leaves the sealed
|
|
14
|
+
* hello.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** The tunnel `error` code the daemon answers a revoked pairing with
|
|
18
|
+
* (`PAIRING_REVOKED_CODE` in `@agentproto/runtime`'s pairing registry). */
|
|
19
|
+
declare const PAIRING_REVOKED_CODE = "pairing_revoked";
|
|
20
|
+
/** A WHATWG `WebSocket` constructor (the global one by default). */
|
|
21
|
+
type WebSocketConstructor = new (url: string) => WebSocket;
|
|
22
|
+
interface ChannelTimeouts {
|
|
23
|
+
/** Rendezvous dial ceiling. Default 15s (as the CLI). */
|
|
24
|
+
dialTimeoutMs?: number;
|
|
25
|
+
/** Handshake ceiling. Default 15s (as the CLI). */
|
|
26
|
+
handshakeTimeoutMs?: number;
|
|
27
|
+
/** How long to wait for the daemon's first tunnel frame. Default 10s. */
|
|
28
|
+
greetingTimeoutMs?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The stored pairing credential and where it lives.
|
|
33
|
+
*
|
|
34
|
+
* `PairCredential` carries what the Node CLI persists per pairing
|
|
35
|
+
* (`~/.agentproto/pair-credentials.json`, `ClientPairing` in
|
|
36
|
+
* `packages/cli/src/util/client-pairings.ts`) — the pinned daemon keys, the
|
|
37
|
+
* rendezvous URL, the pair root, timestamps — so a reconnect is byte-for-byte
|
|
38
|
+
* the one the CLI makes. Two differences, both client-local:
|
|
39
|
+
*
|
|
40
|
+
* - `pairRoot` is normally a **non-extractable** WebCrypto HKDF `CryptoKey`
|
|
41
|
+
* (`importPairRootKey`): script can derive the epoch routing tokens with
|
|
42
|
+
* it but can't read the secret back out. IndexedDB stores it as-is
|
|
43
|
+
* (structured clone). A base64 string is accepted too (e.g. a credential
|
|
44
|
+
* imported from the CLI's file).
|
|
45
|
+
* - The CLI keeps one `name` that is both the user's label and the handshake
|
|
46
|
+
* `clientName`; here `name` is the daemon's display name and `clientName`
|
|
47
|
+
* the label this device announced to the daemon (what `pair ls` shows).
|
|
48
|
+
*
|
|
49
|
+
* No localStorage anywhere: `createIndexedDbCredentialStore` for browsers and
|
|
50
|
+
* service workers, `createMemoryCredentialStore` for tests.
|
|
51
|
+
*/
|
|
52
|
+
interface PairCredential {
|
|
53
|
+
/** Pairing protocol the credential was made under (`PAIR_VERSION`, 2). A
|
|
54
|
+
* credential without it predates pair/v2: `connect` refuses it with
|
|
55
|
+
* `protocol_outdated` instead of dialing (the daemon would never serve it). */
|
|
56
|
+
protocol?: number;
|
|
57
|
+
/** Store key: the daemon fingerprint (one credential per daemon, as the CLI
|
|
58
|
+
* keys its pairings). */
|
|
59
|
+
id: string;
|
|
60
|
+
/** Daemon identity fingerprint (32 hex): the pin. */
|
|
61
|
+
fingerprint: string;
|
|
62
|
+
/** Daemon display name: its tunnel `hello` label, else its host name, else
|
|
63
|
+
* the fingerprint. */
|
|
64
|
+
name: string;
|
|
65
|
+
/** The label this device sent in the handshake (the daemon's `pair ls` name). */
|
|
66
|
+
clientName: string;
|
|
67
|
+
/** Daemon static X25519 public key (base64 SPKI DER), pinned. */
|
|
68
|
+
daemonX25519Pub: string;
|
|
69
|
+
/** Daemon static Ed25519 public key (base64 SPKI DER), pinned: verifies the
|
|
70
|
+
* daemon's transcript signature on every (re)connect. */
|
|
71
|
+
daemonEd25519Pub: string;
|
|
72
|
+
/** Rendezvous endpoint to reconnect through. */
|
|
73
|
+
rendezvousUrl: string;
|
|
74
|
+
/** Long-term shared secret the epoch routing tokens derive from: a
|
|
75
|
+
* non-extractable HKDF `CryptoKey`, or base64. */
|
|
76
|
+
pairRoot: CryptoKey | string;
|
|
77
|
+
/** ISO-8601 when this pairing was made. */
|
|
78
|
+
createdAt: string;
|
|
79
|
+
/** ISO-8601 of the most recent (re)connect. */
|
|
80
|
+
lastSeen: string;
|
|
81
|
+
}
|
|
82
|
+
interface CredentialStore {
|
|
83
|
+
get(id: string): Promise<PairCredential | undefined>;
|
|
84
|
+
/** Insert or replace (keyed by `id`). */
|
|
85
|
+
put(credential: PairCredential): Promise<void>;
|
|
86
|
+
/** Returns whether something was removed. */
|
|
87
|
+
delete(id: string): Promise<boolean>;
|
|
88
|
+
list(): Promise<PairCredential[]>;
|
|
89
|
+
}
|
|
90
|
+
/** In-memory store (tests, or a page that must not persist). */
|
|
91
|
+
declare function createMemoryCredentialStore(initial?: PairCredential[]): CredentialStore;
|
|
92
|
+
interface IndexedDbCredentialStoreOptions {
|
|
93
|
+
/** Database name. Default `agentproto-pair`. */
|
|
94
|
+
dbName?: string;
|
|
95
|
+
/** Object store name. Default `credentials`. */
|
|
96
|
+
storeName?: string;
|
|
97
|
+
/** The IndexedDB factory. Default `globalThis.indexedDB` (window or worker). */
|
|
98
|
+
indexedDB?: IDBFactory;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* IndexedDB-backed store. Works in a window and in a service worker (both
|
|
102
|
+
* expose `indexedDB`); credentials are scoped to the origin like all IndexedDB
|
|
103
|
+
* data. The `CryptoKey` pair root is stored by structured clone, so it stays
|
|
104
|
+
* non-extractable at rest and after reload.
|
|
105
|
+
*/
|
|
106
|
+
declare function createIndexedDbCredentialStore(opts?: IndexedDbCredentialStoreOptions): CredentialStore;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The one error type this package throws, with a stable machine code so a UI
|
|
110
|
+
* can branch on it (e.g. show "scan a new pairing QR" for `revoked`).
|
|
111
|
+
*/
|
|
112
|
+
type TunnelClientErrorCode =
|
|
113
|
+
/** The daemon told us (authenticated, inside the E2E channel) that this
|
|
114
|
+
* pairing was revoked. Terminal: pair again from a new offer. */
|
|
115
|
+
"revoked"
|
|
116
|
+
/** The offer or stored credential predates pairing protocol v2 (or the
|
|
117
|
+
* daemon says so). Terminal: upgrade agentproto and pair again. */
|
|
118
|
+
| "protocol_outdated"
|
|
119
|
+
/** The daemon could not be reached (rendezvous dial, handshake or greeting
|
|
120
|
+
* failed, or no connection came up within the wait). Retried with backoff. */
|
|
121
|
+
| "offline"
|
|
122
|
+
/** The live connection dropped while this request was in flight. */
|
|
123
|
+
| "disconnected"
|
|
124
|
+
/** `client.close()` was called. */
|
|
125
|
+
| "closed"
|
|
126
|
+
/** The offer URL is malformed or expired. */
|
|
127
|
+
| "invalid_offer"
|
|
128
|
+
/** The pairing handshake over the offer failed (bad daemon signature, spent
|
|
129
|
+
* offer, fingerprint mismatch, timeout…). */
|
|
130
|
+
| "pairing_failed"
|
|
131
|
+
/** `confirm()` after `cancel()` (or a second `confirm()`). */
|
|
132
|
+
| "cancelled"
|
|
133
|
+
/** The daemon's upstream failed mid-stream (surfaced on the body stream). */
|
|
134
|
+
| "stream_error";
|
|
135
|
+
declare class TunnelClientError extends Error {
|
|
136
|
+
readonly code: TunnelClientErrorCode;
|
|
137
|
+
constructor(code: TunnelClientErrorCode, message: string, options?: {
|
|
138
|
+
cause?: unknown;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* `connect(credential)` — a long-lived, self-healing tunnel to a paired
|
|
144
|
+
* daemon, with a WHATWG `fetch` on top.
|
|
145
|
+
*
|
|
146
|
+
* Connection: the CLI's `openPairChannel` sequence (epoch routing token for
|
|
147
|
+
* today, then yesterday's to bridge clock skew; a fresh handshake each time),
|
|
148
|
+
* kept up with jittered, capped exponential backoff. A live channel is watched
|
|
149
|
+
* with ping/pong so a half-open socket is noticed.
|
|
150
|
+
*
|
|
151
|
+
* State (for a UI): `connecting` → `open`; on failure or drop → `offline`
|
|
152
|
+
* (while waiting to retry) → `connecting` …; `revoked`, `outdated` and
|
|
153
|
+
* `closed` are terminal. `revoked` is only ever entered on the daemon's
|
|
154
|
+
* authenticated `pairing_revoked` frame — never on anything the broker could
|
|
155
|
+
* fake — and stops all retries. `outdated` means the credential predates
|
|
156
|
+
* pair/v2 (it is never dialed) or the daemon said so, authenticated, the same
|
|
157
|
+
* way.
|
|
158
|
+
*
|
|
159
|
+
* Tokens (pair/v2): each attempt derives the epoch ROUTE — the only value on
|
|
160
|
+
* the broker URL — and the epoch AUTH, which is sealed into the hello and
|
|
161
|
+
* never leaves it.
|
|
162
|
+
*
|
|
163
|
+
* Requests: `http_request` frames multiplexed over the one channel by `reqId`.
|
|
164
|
+
* The response resolves at the daemon's `http_response` (buffered) or
|
|
165
|
+
* `http_response_head` (streamed: SSE / NDJSON), whose body is then a
|
|
166
|
+
* `ReadableStream` fed chunk by chunk as `http_response_chunk` frames arrive.
|
|
167
|
+
* Aborting (the request's signal, or cancelling the body) sends
|
|
168
|
+
* `http_cancel`. In-flight requests fail with `disconnected` when the channel
|
|
169
|
+
* drops; new ones wait for the (re)connection, up to `requestWaitMs`.
|
|
170
|
+
*/
|
|
171
|
+
|
|
172
|
+
type ConnectionState = "connecting" | "open" | "offline" | "revoked" | "outdated" | "closed";
|
|
173
|
+
interface ConnectOptions extends ChannelTimeouts {
|
|
174
|
+
/** WebSocket constructor. Default: the global `WebSocket`. */
|
|
175
|
+
WebSocket?: WebSocketConstructor;
|
|
176
|
+
/** When set, `lastSeen` is refreshed there after each (re)connect
|
|
177
|
+
* (best-effort, as the CLI does). */
|
|
178
|
+
store?: CredentialStore;
|
|
179
|
+
/** First retry delay. Default 500ms. */
|
|
180
|
+
reconnectMinMs?: number;
|
|
181
|
+
/** Retry delay ceiling. Default 30s. */
|
|
182
|
+
reconnectMaxMs?: number;
|
|
183
|
+
/** How long a request waits for a connection before failing `offline`.
|
|
184
|
+
* Default 20s. */
|
|
185
|
+
requestWaitMs?: number;
|
|
186
|
+
/** Ping interval on a live channel. Default 25s; `0` disables. */
|
|
187
|
+
keepAliveMs?: number;
|
|
188
|
+
/** A ping unanswered this long drops the channel (and reconnects).
|
|
189
|
+
* Default 10s. */
|
|
190
|
+
pongTimeoutMs?: number;
|
|
191
|
+
/** Map a request URL to the daemon path (path + query, must start with `/`).
|
|
192
|
+
* Default: `url.pathname + url.search`. A service worker uses this to strip
|
|
193
|
+
* its scope prefix. */
|
|
194
|
+
mapPath?: (url: URL) => string;
|
|
195
|
+
/** Clock (ms). Default `Date.now`. */
|
|
196
|
+
now?: () => number;
|
|
197
|
+
/** Random source for backoff jitter, in [0, 1). Default `Math.random`. */
|
|
198
|
+
random?: () => number;
|
|
199
|
+
}
|
|
200
|
+
interface StateChange {
|
|
201
|
+
state: ConnectionState;
|
|
202
|
+
/** Why we're `offline` / `revoked` / `outdated` / `closed` (the last failure). */
|
|
203
|
+
error?: TunnelClientError;
|
|
204
|
+
}
|
|
205
|
+
interface TunnelClient {
|
|
206
|
+
/** The pairing this client serves. */
|
|
207
|
+
readonly credential: PairCredential;
|
|
208
|
+
readonly state: ConnectionState;
|
|
209
|
+
/** The daemon's hello on the current (or last) channel. */
|
|
210
|
+
readonly hello: HelloFrame | null;
|
|
211
|
+
/** The most recent connection failure, if any. */
|
|
212
|
+
readonly lastError: TunnelClientError | null;
|
|
213
|
+
/** Subscribe to state changes. Returns an unsubscribe function. */
|
|
214
|
+
onStateChange(listener: (change: StateChange) => void): () => void;
|
|
215
|
+
/** Resolves once connected; rejects with `revoked` / `protocol_outdated` /
|
|
216
|
+
* `closed`, or `offline`
|
|
217
|
+
* when no connection came up within `requestWaitMs`. */
|
|
218
|
+
ready(): Promise<void>;
|
|
219
|
+
/** A WHATWG `fetch` through the daemon. Relative URLs are fine: only the
|
|
220
|
+
* path + query (see `mapPath`) is sent. Rejects with `TunnelClientError`
|
|
221
|
+
* (`offline` / `disconnected` / `revoked` / `protocol_outdated` / `closed`)
|
|
222
|
+
* where `fetch` would
|
|
223
|
+
* reject with a network error, or with the signal's reason on abort. */
|
|
224
|
+
fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
|
|
225
|
+
/** Skip the current backoff wait and retry now (e.g. on `online`). */
|
|
226
|
+
reconnect(): void;
|
|
227
|
+
/** Close the channel and stop reconnecting. Pending requests fail `closed`.
|
|
228
|
+
* The state becomes `closed`, except that a terminal `revoked` / `outdated`
|
|
229
|
+
* is kept (with its `lastError`). */
|
|
230
|
+
close(): void;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Connect to a paired daemon. Returns immediately; the client connects in the
|
|
234
|
+
* background (watch `state` / `onStateChange`, or `await client.ready()`).
|
|
235
|
+
* One client per credential: the daemon keeps one standing channel per epoch
|
|
236
|
+
* slot, so share this instance rather than connecting twice.
|
|
237
|
+
*/
|
|
238
|
+
declare function connect(credential: PairCredential, opts?: ConnectOptions): TunnelClient;
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* First contact: turn an offer (the `pair offer --qr` link, or the plain
|
|
242
|
+
* `agentproto://pair?…` URL) into a stored credential.
|
|
243
|
+
*
|
|
244
|
+
* Two steps so a UI can ask the human before persisting anything:
|
|
245
|
+
*
|
|
246
|
+
* 1. `inspectOffer(url)` — no network: parse + validate the offer and return
|
|
247
|
+
* the daemon fingerprint it pins and when it expires.
|
|
248
|
+
* 2. `pairFromOffer(url)` — run the handshake through the offer's rendezvous
|
|
249
|
+
* (this spends the one-time offer; the daemon records the pairing now,
|
|
250
|
+
* exactly as for `agentproto pair accept`), read the daemon's hello for its
|
|
251
|
+
* name, close the channel, and hand back `{ daemon, confirm, cancel }`.
|
|
252
|
+
* `confirm()` builds the credential (pair root as a non-extractable
|
|
253
|
+
* `CryptoKey`) and stores it; `cancel()` drops it. Cancelling does not undo
|
|
254
|
+
* the daemon's record — remove that with `agentproto pair revoke`.
|
|
255
|
+
*/
|
|
256
|
+
|
|
257
|
+
interface OfferInfo {
|
|
258
|
+
/** Daemon identity fingerprint (32 hex) the offer pins — show it to the user. */
|
|
259
|
+
fingerprint: string;
|
|
260
|
+
/** The rendezvous the handshake will go through. */
|
|
261
|
+
rendezvousUrl: string;
|
|
262
|
+
/** Offer expiry. */
|
|
263
|
+
expiresAt: Date;
|
|
264
|
+
}
|
|
265
|
+
/** Parse and validate an offer without touching the network. Accepts the web
|
|
266
|
+
* form (`https://…/pair#…`) and the `agentproto://pair?…` form. */
|
|
267
|
+
declare function inspectOffer(offerUrl: string, opts?: {
|
|
268
|
+
now?: number;
|
|
269
|
+
}): Promise<OfferInfo>;
|
|
270
|
+
interface PairFromOfferOptions extends ChannelTimeouts {
|
|
271
|
+
/** How this device is listed on the daemon (`agentproto pair ls`).
|
|
272
|
+
* Default `browser@<location.host>` (or `browser`). */
|
|
273
|
+
clientName?: string;
|
|
274
|
+
/** Where `confirm()` stores the credential. Omit to only get it back. */
|
|
275
|
+
store?: CredentialStore;
|
|
276
|
+
/** WebSocket constructor. Default: the global `WebSocket`. */
|
|
277
|
+
WebSocket?: WebSocketConstructor;
|
|
278
|
+
/** Clock (ms). Default `Date.now`. */
|
|
279
|
+
now?: () => number;
|
|
280
|
+
}
|
|
281
|
+
interface PairedDaemon {
|
|
282
|
+
/** Daemon identity fingerprint — verified by the handshake. */
|
|
283
|
+
fingerprint: string;
|
|
284
|
+
/** Display name (hello label, else host name, else the fingerprint). */
|
|
285
|
+
name: string;
|
|
286
|
+
/** The daemon's `serve --label`, if any. */
|
|
287
|
+
label?: string;
|
|
288
|
+
/** `<os>/<hostname>` from the daemon's hello (diagnostic). */
|
|
289
|
+
platform?: string;
|
|
290
|
+
rendezvousUrl: string;
|
|
291
|
+
}
|
|
292
|
+
interface PendingPairing {
|
|
293
|
+
daemon: PairedDaemon;
|
|
294
|
+
/** Build the credential and (with `opts.store`) persist it. */
|
|
295
|
+
confirm(): Promise<PairCredential>;
|
|
296
|
+
/** Discard the pairing on this side. */
|
|
297
|
+
cancel(): void;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Run the `pair/v1` handshake for an offer. See the module doc for the
|
|
301
|
+
* two-step flow. Throws `TunnelClientError` — `invalid_offer` for a
|
|
302
|
+
* malformed/expired offer, `pairing_failed` for everything the handshake can
|
|
303
|
+
* hit (unreachable daemon, spent offer, bad signature, fingerprint mismatch).
|
|
304
|
+
*/
|
|
305
|
+
declare function pairFromOffer(offerUrl: string, opts?: PairFromOfferOptions): Promise<PendingPairing>;
|
|
306
|
+
|
|
307
|
+
export { type ChannelTimeouts, type ConnectOptions, type ConnectionState, type CredentialStore, type IndexedDbCredentialStoreOptions, type OfferInfo, PAIRING_REVOKED_CODE, type PairCredential, type PairFromOfferOptions, type PairedDaemon, type PendingPairing, type StateChange, type TunnelClient, TunnelClientError, type TunnelClientErrorCode, type WebSocketConstructor, connect, createIndexedDbCredentialStore, createMemoryCredentialStore, inspectOffer, pairFromOffer };
|