@ledgerhq/agent-intent-sdk 0.0.0-stage → 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.
Files changed (59) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +333 -2
  3. package/dist/auth.d.ts +35 -0
  4. package/dist/auth.d.ts.map +1 -0
  5. package/dist/auth.js +366 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/bytes.d.ts +7 -0
  8. package/dist/bytes.d.ts.map +1 -0
  9. package/dist/bytes.js +26 -0
  10. package/dist/bytes.js.map +1 -0
  11. package/dist/client.d.ts +34 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +149 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.d.ts.map +1 -0
  17. package/dist/completion.js +78 -0
  18. package/dist/completion.js.map +1 -0
  19. package/dist/enrollment.d.ts +54 -0
  20. package/dist/enrollment.d.ts.map +1 -0
  21. package/dist/enrollment.js +143 -0
  22. package/dist/enrollment.js.map +1 -0
  23. package/dist/enrollmentChannel.d.ts +85 -0
  24. package/dist/enrollmentChannel.d.ts.map +1 -0
  25. package/dist/enrollmentChannel.js +671 -0
  26. package/dist/enrollmentChannel.js.map +1 -0
  27. package/dist/fingerprint.d.ts +2 -0
  28. package/dist/fingerprint.d.ts.map +1 -0
  29. package/dist/fingerprint.js +36 -0
  30. package/dist/fingerprint.js.map +1 -0
  31. package/dist/identity.d.ts +13 -0
  32. package/dist/identity.d.ts.map +1 -0
  33. package/dist/identity.js +28 -0
  34. package/dist/identity.js.map +1 -0
  35. package/dist/index.d.ts +13 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +13 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/intentPage.d.ts +71 -0
  40. package/dist/intentPage.d.ts.map +1 -0
  41. package/dist/intentPage.js +103 -0
  42. package/dist/intentPage.js.map +1 -0
  43. package/dist/intents.d.ts +93 -0
  44. package/dist/intents.d.ts.map +1 -0
  45. package/dist/intents.js +294 -0
  46. package/dist/intents.js.map +1 -0
  47. package/dist/recovery.d.ts +67 -0
  48. package/dist/recovery.d.ts.map +1 -0
  49. package/dist/recovery.js +188 -0
  50. package/dist/recovery.js.map +1 -0
  51. package/dist/requestFields.d.ts +64 -0
  52. package/dist/requestFields.d.ts.map +1 -0
  53. package/dist/requestFields.js +230 -0
  54. package/dist/requestFields.js.map +1 -0
  55. package/dist/userAgent.d.ts +16 -0
  56. package/dist/userAgent.d.ts.map +1 -0
  57. package/dist/userAgent.js +53 -0
  58. package/dist/userAgent.js.map +1 -0
  59. package/package.json +66 -3
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 2026-present Ledger
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 CHANGED
@@ -1,3 +1,334 @@
1
- # Temporary Holding Version
1
+ # `@ledgerhq/agent-intent-sdk`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > [!CAUTION]
4
+ > **Status: UNSTABLE**
5
+ > This package is under active development. Breaking changes may be released
6
+ > while the Agent Intent protocol and service contract stabilize.
7
+
8
+ Headless TypeScript SDK for agents that enroll with Ledger Agent Intent,
9
+ authenticate through LKRP/Keycloak, and submit signed intents for human approval.
10
+
11
+ The package has no React, Vite, browser-storage, Ledger device, or application
12
+ state dependency. Secret-key persistence is deliberately left to consumers.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ pnpm add @ledgerhq/agent-intent-sdk
18
+ ```
19
+
20
+ ## Requirements
21
+
22
+ - Node.js 24 or newer
23
+ - An enrolled Agent Intent identity and Trustchain ID
24
+ - Network access to the selected Agent Intent and Keycloak environments
25
+
26
+ ## Submit an intent
27
+
28
+ ```ts
29
+ import { createAgentIntentClient, createSoftwareAgentIdentity } from "@ledgerhq/agent-intent-sdk";
30
+
31
+ const identity = createSoftwareAgentIdentity(savedSecretKey);
32
+ const client = createAgentIntentClient({
33
+ bffBaseUrl: "https://global.api.stg.ledger-test.com/agent-intent",
34
+ identity,
35
+ trustchainId,
36
+ environment: "staging",
37
+ });
38
+
39
+ const deeplink = await client.createSendIntent({
40
+ type: "send",
41
+ network: "ethereum",
42
+ sender,
43
+ recipient,
44
+ amount: "1000000000000000000",
45
+ asset: { type: "native" },
46
+ feeStrategy: "medium",
47
+ description: "Pay supplier",
48
+ });
49
+ ```
50
+
51
+ Amounts accept decimal strings or `bigint` and are serialized as exact JSON
52
+ integers to avoid JavaScript precision loss.
53
+
54
+ A Solana send uses `network: "solana"` (or `"solana_devnet"`) and canonical
55
+ base58 addresses. It has no fee strategy, because the service sets the priority
56
+ fee, and it may carry an on-chain `memo`. A native SOL send gives its amount in
57
+ lamports:
58
+
59
+ ```ts
60
+ const deeplink = await client.createSendIntent({
61
+ type: "send",
62
+ network: "solana",
63
+ sender,
64
+ recipient,
65
+ amount: "10000000", // 0.01 SOL
66
+ asset: { type: "native" },
67
+ memo: "Invoice 42",
68
+ });
69
+ ```
70
+
71
+ An SPL token send names the token by its mint, with the amount in the token's
72
+ base units:
73
+
74
+ ```ts
75
+ asset: { type: "spl-token", assetReference: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" }, // USDC
76
+ amount: "1000000", // 1 USDC
77
+ ```
78
+
79
+ Token-2022 tokens and an `assetOwner` are refused for now: no client can send
80
+ the former yet, and the service doesn't use the latter on Solana.
81
+
82
+ ### Swap intents
83
+
84
+ ```ts
85
+ const deeplink = await client.createSwapIntent({
86
+ type: "swap",
87
+ network: "ethereum",
88
+ sender,
89
+ fromAsset: "ethereum",
90
+ toAsset: "ethereum/erc20/usd__coin",
91
+ fromAmount: "0.5",
92
+ toAmount: "1250",
93
+ provider: "oneinch",
94
+ description: "Rebalance to USDC",
95
+ });
96
+ ```
97
+
98
+ `network` is one of `SWAP_INTENT_NETWORKS` (`ethereum`, `ethereum_sepolia`,
99
+ `arc_testnet`). `fromAmount` and `toAmount` are human-unit decimal strings
100
+ (`"0.5"` ETH, not wei), signed as given: `"1.5"` and `"1.50"` sign differently.
101
+
102
+ ## List the agent's intents
103
+
104
+ ```ts
105
+ import { isSendOperation, isSwapOperation } from "@ledgerhq/agent-intent-sdk";
106
+
107
+ let page = await client.listIntents({ status: ["signed", "broadcast"], pageSize: 10 });
108
+ while (true) {
109
+ for (const { id, status, intent } of page.intents) {
110
+ if (isSendOperation(intent)) console.log(id, status, intent.amount);
111
+ else if (isSwapOperation(intent)) console.log(id, status, intent.fromAmount, intent.toAmount);
112
+ }
113
+ if (!page.nextCursor) break;
114
+ page = await client.listIntents({ cursor: page.nextCursor });
115
+ }
116
+ ```
117
+
118
+ The BFF scopes the listing to the authenticated agent: it only returns intents
119
+ that agent issued, most recent first. `status` takes any of
120
+ `AGENT_INTENT_STATUSES` and `pageSize` one of `AGENT_INTENT_PAGE_SIZES` (1, 5,
121
+ 10, 50, 100; the BFF defaults to 10). `nextCursor` is opaque; when you pass it
122
+ back, the first page's filters and page size apply and the other options are
123
+ ignored. Amounts are exact strings: a send's `amount` is an integer in the
124
+ asset's smallest unit (wei, lamports, token base units), a swap's `fromAmount`
125
+ and `toAmount` are decimals in human units. One record that lacks a required
126
+ field, or has a known field of the wrong type (`null` included, even on an
127
+ optional field such as `failureReason` or `memo`), fails the whole page with an
128
+ `AgentIntentSdkError`. An intent type the SDK doesn't know yet is passed
129
+ through, so narrow with `isSendOperation` or `isSwapOperation`. HTTP failures
130
+ throw `AgentIntentHttpError` with the BFF's `status` and `type`.
131
+
132
+ ## Read one intent
133
+
134
+ ```ts
135
+ const intent = await client.getIntent(intentId);
136
+ console.log(intent.status, intent.updatedAt);
137
+ ```
138
+
139
+ An unknown id and another agent's intent both fail with `AgentIntentHttpError`
140
+ `status` 404. Amounts are exact decimal strings, as in the listing.
141
+
142
+ ## Cancel an intent
143
+
144
+ An agent can withdraw an intent it created, as long as the user hasn't acted on it:
145
+
146
+ ```ts
147
+ await client.cancelIntent(intentId);
148
+ ```
149
+
150
+ A `created` or `crafted` intent can be cancelled, and cancelling an already
151
+ cancelled one also succeeds. Any other state, including one the user rejected or
152
+ signed, fails with `AgentIntentHttpError` `status` 400 and no `type`; call
153
+ `getIntent` to see which. Only the user rejects, in Ledger's interface. An intent
154
+ can't be edited: to change one, cancel it and create a new one.
155
+
156
+ ## User-Agent
157
+
158
+ Outside browsers, requests send `User-Agent: ledger-agent-intent-sdk/<version> (agentic)`.
159
+ A custom `tokenProvider` sends its own authentication requests, so it must set that header itself.
160
+
161
+ ## Enrollment fingerprint
162
+
163
+ Display the same fingerprint that the Ledger device shows:
164
+
165
+ ```ts
166
+ import { formatAgentPublicKeyFingerprint } from "@ledgerhq/agent-intent-sdk";
167
+
168
+ console.log(formatAgentPublicKeyFingerprint(identity.publicKey));
169
+ ```
170
+
171
+ The helper accepts compressed or uncompressed secp256k1 public keys.
172
+
173
+ ## Validate an enrollment or recovery link
174
+
175
+ `validateAgentEnrollment` and `validateAgentRecovery` take the link's query
176
+ parameters. A malformed link comes back with `reason: "malformed"` and the
177
+ field problems in `issues`, so an application can say what went wrong:
178
+
179
+ ```ts
180
+ const validation = validateAgentEnrollment(search);
181
+ if (validation.status === "invalid" && validation.reason === "malformed") {
182
+ // { status: "invalid", reason: "malformed",
183
+ // message: 'This agent enrollment link is malformed: "signature" is cut off (expected 128 hex characters).',
184
+ // issues: [{ field: "signature", problem: "truncated", expectedLength: 128 }] }
185
+ }
186
+ ```
187
+
188
+ A field can be `missing`, `repeated` (the link was pasted twice), `empty`,
189
+ `truncated` or followed by `extra-characters` (hex fields), `too-long` (name and
190
+ description), have an `invalid-value`, carry an `unsupported-version`, or be
191
+ `unexpected`. `message` describes the first issue, and unexpected parameters
192
+ come after every other problem. `issues` only explains a rejection and never
193
+ changes which links are accepted, so two problems that do not reject a link on
194
+ their own, an unreadable `expiresAt` and a repeated channel field on a link
195
+ without a channel, are listed only when something else already rejects it. An
196
+ `unexpected` issue has a `parameter` instead of a `field`: it is the name as the
197
+ link carried it, so treat it as untrusted text and don't show it as is.
198
+ `AGENT_NAME_MAX_LENGTH` and `AGENT_DESCRIPTION_MAX_LENGTH` export the name and
199
+ description limits the validators apply.
200
+
201
+ ## Agent setup prompt
202
+
203
+ The prompt a user pastes into their agent to enroll it with the app they are on:
204
+
205
+ ```ts
206
+ const prompt = buildAgentSetupPrompt(window.location.origin);
207
+ ```
208
+
209
+ An https app is named by its host (`app.agents.ledger.com`), an http one by its full origin
210
+ (`http://localhost:5173`). The wallet-cli skill holds the enrollment steps.
211
+
212
+ ## Encrypted enrollment completion
213
+
214
+ Version-2 enrollment requests bind a one-use ephemeral relay host key into the
215
+ agent signature. A headless agent creates the host binding before creating the
216
+ URL; the socket opens lazily when it starts waiting. The host independently
217
+ authenticates the completion, persists it, and only then acknowledges:
218
+
219
+ ```ts
220
+ const host = createAgentEnrollmentChannelHost({
221
+ environment: "production",
222
+ relayBaseUrl: "https://trustchain.api.live.ledger.com",
223
+ });
224
+ const request = createAgentEnrollmentRequest(identity, {
225
+ name,
226
+ description,
227
+ source,
228
+ expiresAt,
229
+ channel: host.binding,
230
+ });
231
+ console.log(createAgentEnrollmentUrl(frontendUrl, request));
232
+
233
+ await host.waitForCompletion({
234
+ request,
235
+ authenticate: async (completion) => {
236
+ // Prove this agent key belongs to the claimed Trustchains. Throw on failure.
237
+ },
238
+ persist: async (completion) => {
239
+ // Persist completion.trustchainId and completion.accountAccess atomically.
240
+ },
241
+ });
242
+ ```
243
+
244
+ The browser validates the signed request, derives its trusted relay origin from
245
+ the signed environment, and uses `createAgentEnrollmentChannelCandidate()` to
246
+ deliver the serialized completion. The encrypted channel is the only delivery
247
+ path for version-2 and channel-bound recovery requests.
248
+
249
+ The candidate separates reaching the agent from delivering to it, so device
250
+ work only starts once the agent is known to be listening:
251
+
252
+ ```ts
253
+ const candidate = createAgentEnrollmentChannelCandidate({ request, relayBaseUrl });
254
+
255
+ await candidate.connect(); // relay socket + key-confirmation handshake
256
+ const completion = await approveOnLedgerDevice(); // may take minutes
257
+ await candidate.deliver(completion); // resolves after the host acknowledges
258
+ ```
259
+
260
+ `deliver()` connects implicitly when `connect()` was not called or the session
261
+ was lost (for example, the relay dropped the socket during device approval).
262
+ If a delivery fails, for example because `authenticate` rejected it or the
263
+ acknowledgement timed out, `deliver()` may be retried on the same candidate. Each
264
+ retry opens a fresh session with a new ephemeral key, and a newly connecting
265
+ candidate replaces one that has not delivered yet. A retry fails once the host has
266
+ finished, closed, or timed out.
267
+
268
+ ### Recovery
269
+
270
+ A recovery request re-enrolls an existing agent key into its previous App-18
271
+ Trustchain. Its `source` is an `AgentRecoverySource`, which is any supported
272
+ `AgentSource` (see `isAgentRecoverySource`): recovery never depends on the
273
+ source. Bind it to a channel host the same way:
274
+
275
+ ```ts
276
+ const request = createAgentRecoveryRequest(identity, {
277
+ name,
278
+ description,
279
+ source,
280
+ previousTrustchainId,
281
+ expiresAt,
282
+ channel: host.binding,
283
+ });
284
+ console.log(createAgentRecoveryUrl(frontendUrl, request));
285
+
286
+ const completion = await host.waitForCompletion({ request, authenticate, persist });
287
+ // completion: { version: 3, recovery: true, trustchainId, previousTrustchainId, ... }
288
+ ```
289
+
290
+ For a recovery request, the host accepts only a version-3 recovery completion
291
+ whose agent key, previous Trustchain, and request signature match the signed
292
+ request, and whose `trustchainId` equals `previousTrustchainId`. For a version-2
293
+ request it accepts only a version-2 completion. `serializeAgentRecoveryCompletion`,
294
+ `parseAgentRecoveryCompletion`, and `validateAgentRecovery` are exported for the
295
+ frontend. The channel binding is optional and signed; an unbound recovery
296
+ request keeps its earlier canonical bytes.
297
+
298
+ ### Security and timeouts
299
+
300
+ The channel key and every encrypted envelope are bound to the exact signed
301
+ request and envelope metadata. Handshake, completion, persistence, and
302
+ acknowledgement waits are bounded and capped by the signed request expiry.
303
+ The host allows 15 minutes for the frontend candidate to connect. After a
304
+ candidate connects, the cryptographic handshake, persistence, and
305
+ acknowledgement defaults are 30 seconds each. The wait between a completed
306
+ handshake and the delivered completion (device approval) is bounded only by
307
+ `completionTimeoutMs` (15 minutes) and the request expiry, on both the host and
308
+ the candidate. Applications may override these with the `timeouts` option.
309
+ While a session is open, both sides send the relay a text `ping` every 60
310
+ seconds, because the Trustchain relay drops a client after 5 minutes without a
311
+ frame sent to it. A failed `authenticate` call rejects only that delivery, so
312
+ the same or a later candidate can complete the same bounded host session. A
313
+ persistence failure closes the session without acknowledging. If enrollment was
314
+ committed before delivery failed, re-enroll the agent with a channel-bound
315
+ recovery request.
316
+
317
+ The channel sends only the agent public key, App-18 Trustchain ID, and safe
318
+ App-16 environment/root/path references. It must never carry a serialized
319
+ Trustchain, `walletSyncEncryptionKey`, private key, JWT, or access token.
320
+
321
+ ## Development
322
+
323
+ ```sh
324
+ mise install
325
+ pnpm install
326
+ pnpm verify
327
+ ```
328
+
329
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for branch, changeset, review, and
330
+ release conventions.
331
+
332
+ ## License
333
+
334
+ Apache-2.0. See [LICENSE](./LICENSE).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { type AgentIdentity } from "./identity.ts";
2
+ export type AgentIntentEnvironment = "staging" | "production";
3
+ export type AgentKeycloakConfig = {
4
+ baseUrl: string;
5
+ realm: string;
6
+ clientId: string;
7
+ brokerId: string;
8
+ disablePkce?: boolean;
9
+ };
10
+ export declare const AGENT_KEYCLOAK_ENVIRONMENTS: {
11
+ readonly staging: {
12
+ readonly baseUrl: "https://global.api.stg.ledger-test.com/keycloak";
13
+ readonly realm: "agent-intent-customers";
14
+ readonly clientId: "agentic-client";
15
+ readonly brokerId: "lkrp";
16
+ };
17
+ readonly production: {
18
+ readonly baseUrl: "https://global.api.prd.ledger.com/keycloak";
19
+ readonly realm: "agent-intent-customers";
20
+ readonly clientId: "agentic-client";
21
+ readonly brokerId: "lkrp";
22
+ };
23
+ };
24
+ export type AccessTokenProvider = {
25
+ withAccessToken<T>(query: (accessToken: string) => Promise<T>, retryWhen?: (result: T) => boolean): Promise<T>;
26
+ };
27
+ export declare function createAgentTokenProvider(input: {
28
+ identity: AgentIdentity;
29
+ trustchainId: string;
30
+ keycloak: AgentKeycloakConfig;
31
+ fetch?: typeof globalThis.fetch;
32
+ }): AccessTokenProvider;
33
+ export declare function buildUnsignedChallengeTlv(tlvHex: string): Uint8Array;
34
+ export declare function buildAttestation(trustchainId: string): string;
35
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AACA,OAAO,EAA+B,KAAK,aAAa,EAAE,MAAM,eAAe,CAAC;AAGhF,MAAM,MAAM,sBAAsB,GAAG,SAAS,GAAG,YAAY,CAAC;AAE9D,MAAM,MAAM,mBAAmB,GAAG;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,2BAA2B;;iBAEpC,OAAO,EAAE,iDAAiD;iBAC1D,KAAK,EAAE,wBAAwB;iBAC/B,QAAQ,EAAE,gBAAgB;iBAC1B,QAAQ,EAAE,MAAM;;;iBAGhB,OAAO,EAAE,4CAA4C;iBACrD,KAAK,EAAE,wBAAwB;iBAC/B,QAAQ,EAAE,gBAAgB;iBAC1B,QAAQ,EAAE,MAAM;;CAEoD,CAAC;AAEzE,MAAM,MAAM,mBAAmB,GAAG;IAChC,eAAe,CAAC,CAAC,EACf,KAAK,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,EAC1C,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,OAAO,GACjC,OAAO,CAAC,CAAC,CAAC,CAAC;CACf,CAAC;AAOF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE;IAC9C,QAAQ,EAAE,aAAa,CAAC;IACxB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC,GAAG,mBAAmB,CA4BtB;AA8HD,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAmBpE;AAED,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAI7D"}