@private.me/xbind 1.3.5 → 3.0.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 (306) hide show
  1. package/LICENSES.md +212 -0
  2. package/README.md +388 -6
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -639
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -496
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -317
  7. package/dist-standalone/_deps/shared/errors.js +1 -255
  8. package/dist-standalone/_deps/shared/index.js +1 -74
  9. package/dist-standalone/_deps/shared/types.js +1 -90
  10. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  20. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  21. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  28. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  29. package/dist-standalone/_deps/xchange/errors.js +1 -1
  30. package/dist-standalone/_deps/xchange/index.js +1 -1
  31. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  32. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  33. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  34. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  40. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  41. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  42. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  43. package/dist-standalone/_deps/xregistry/index.js +1 -1
  44. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  45. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  46. package/dist-standalone/_deps/xregistry/types.js +1 -1
  47. package/dist-standalone/agent-call.js +1 -642
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +95 -5
  50. package/dist-standalone/agent.js +1 -1545
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +275 -0
  53. package/dist-standalone/async-iterators.js +1 -0
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.d.ts +114 -0
  58. package/dist-standalone/backup.js +1 -0
  59. package/dist-standalone/batch-operations.d.ts +297 -0
  60. package/dist-standalone/batch-operations.js +1 -0
  61. package/dist-standalone/cancellation.d.ts +301 -0
  62. package/dist-standalone/cancellation.js +1 -0
  63. package/dist-standalone/checkpoint.js +1 -186
  64. package/dist-standalone/circuit-breaker.d.ts +351 -0
  65. package/dist-standalone/circuit-breaker.js +1 -0
  66. package/dist-standalone/cjs/agent-call.js +1 -651
  67. package/dist-standalone/cjs/agent-sdk.js +1 -332
  68. package/dist-standalone/cjs/agent.js +1 -1582
  69. package/dist-standalone/cjs/approval.js +1 -199
  70. package/dist-standalone/cjs/async-iterators.js +1 -0
  71. package/dist-standalone/cjs/auth.js +1 -225
  72. package/dist-standalone/cjs/auto-accept.js +1 -233
  73. package/dist-standalone/cjs/backup-config.js +1 -207
  74. package/dist-standalone/cjs/backup.js +1 -0
  75. package/dist-standalone/cjs/batch-operations.js +1 -0
  76. package/dist-standalone/cjs/cancellation.js +1 -0
  77. package/dist-standalone/cjs/checkpoint.js +1 -193
  78. package/dist-standalone/cjs/circuit-breaker.js +1 -0
  79. package/dist-standalone/cjs/cli/init.js +1 -486
  80. package/dist-standalone/cjs/config-validation.js +1 -0
  81. package/dist-standalone/cjs/connect.js +1 -312
  82. package/dist-standalone/cjs/connection-pool.js +1 -0
  83. package/dist-standalone/cjs/correlation-id.js +1 -339
  84. package/dist-standalone/cjs/crypto-utils.js +1 -0
  85. package/dist-standalone/cjs/debug-mode.js +1 -0
  86. package/dist-standalone/cjs/did-document.js +1 -101
  87. package/dist-standalone/cjs/did-privateme.js +1 -130
  88. package/dist-standalone/cjs/did-web.js +1 -201
  89. package/dist-standalone/cjs/discovery.js +1 -462
  90. package/dist-standalone/cjs/dual-mode.js +1 -251
  91. package/dist-standalone/cjs/email-templates.js +1 -313
  92. package/dist-standalone/cjs/email-transport.js +1 -239
  93. package/dist-standalone/cjs/envelope.js +1 -510
  94. package/dist-standalone/cjs/errors.js +1 -826
  95. package/dist-standalone/cjs/event-emitter.js +1 -0
  96. package/dist-standalone/cjs/gateway-state.js +1 -55
  97. package/dist-standalone/cjs/gateway-transport.js +1 -120
  98. package/dist-standalone/cjs/graceful-degradation.js +1 -0
  99. package/dist-standalone/cjs/guardrails.js +1 -223
  100. package/dist-standalone/cjs/health-check.js +1 -0
  101. package/dist-standalone/cjs/http-compat.js +1 -272
  102. package/dist-standalone/cjs/http-status-map.js +1 -571
  103. package/dist-standalone/cjs/identity.js +1 -540
  104. package/dist-standalone/cjs/index.js +1 -237
  105. package/dist-standalone/cjs/invitation.js +1 -421
  106. package/dist-standalone/cjs/invite.js +1 -328
  107. package/dist-standalone/cjs/key-agreement.js +1 -246
  108. package/dist-standalone/cjs/lazy-init.js +1 -300
  109. package/dist-standalone/cjs/logger.js +1 -0
  110. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  111. package/dist-standalone/cjs/nonce-store.js +1 -66
  112. package/dist-standalone/cjs/pairing-manager.js +1 -223
  113. package/dist-standalone/cjs/plugin-system.js +1 -0
  114. package/dist-standalone/cjs/plugins/logging.js +1 -0
  115. package/dist-standalone/cjs/plugins/metrics.js +1 -0
  116. package/dist-standalone/cjs/plugins/validation.js +1 -0
  117. package/dist-standalone/cjs/policy.js +1 -320
  118. package/dist-standalone/cjs/progress-callbacks.js +1 -0
  119. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  120. package/dist-standalone/cjs/registry-middleware.js +1 -50
  121. package/dist-standalone/cjs/retry-strategies.js +1 -0
  122. package/dist-standalone/cjs/retry-transport.js +1 -102
  123. package/dist-standalone/cjs/runtime/browser.js +1 -0
  124. package/dist-standalone/cjs/runtime/edge.js +1 -0
  125. package/dist-standalone/cjs/runtime/react-native.js +1 -0
  126. package/dist-standalone/cjs/security-policy.js +1 -245
  127. package/dist-standalone/cjs/serialization.js +1 -0
  128. package/dist-standalone/cjs/split-channel.js +1 -177
  129. package/dist-standalone/cjs/subscription-proof.js +1 -230
  130. package/dist-standalone/cjs/succession.js +1 -148
  131. package/dist-standalone/cjs/timeouts.js +1 -0
  132. package/dist-standalone/cjs/trace-context.js +1 -0
  133. package/dist-standalone/cjs/trace-spans.js +1 -0
  134. package/dist-standalone/cjs/transport.js +1 -63
  135. package/dist-standalone/cjs/trust-registry.js +1 -742
  136. package/dist-standalone/cjs/types/error-response.js +1 -56
  137. package/dist-standalone/cjs/vault-auth.js +1 -0
  138. package/dist-standalone/cjs/vault-store-loader.js +1 -0
  139. package/dist-standalone/cjs/verify.js +1 -25
  140. package/dist-standalone/cjs/version-info.js +1 -0
  141. package/dist-standalone/cjs/xfetch.js +1 -252
  142. package/dist-standalone/cli/init.js +1 -449
  143. package/dist-standalone/cli/setup.js +1 -514
  144. package/dist-standalone/cli/types.js +1 -27
  145. package/dist-standalone/cli/xbind.js +1 -148
  146. package/dist-standalone/config-validation.d.ts +185 -0
  147. package/dist-standalone/config-validation.js +1 -0
  148. package/dist-standalone/connect.js +1 -274
  149. package/dist-standalone/connection-pool.d.ts +251 -0
  150. package/dist-standalone/connection-pool.js +1 -0
  151. package/dist-standalone/correlation-id.js +1 -326
  152. package/dist-standalone/crypto-utils.d.ts +60 -0
  153. package/dist-standalone/crypto-utils.js +1 -0
  154. package/dist-standalone/debug-mode.d.ts +286 -0
  155. package/dist-standalone/debug-mode.js +1 -0
  156. package/dist-standalone/did-document.js +1 -96
  157. package/dist-standalone/did-privateme.js +1 -121
  158. package/dist-standalone/did-web.js +1 -196
  159. package/dist-standalone/discovery.js +1 -458
  160. package/dist-standalone/dual-mode.js +1 -247
  161. package/dist-standalone/email-templates.js +1 -309
  162. package/dist-standalone/email-transport.js +1 -232
  163. package/dist-standalone/envelope.d.ts +29 -1
  164. package/dist-standalone/envelope.js +1 -497
  165. package/dist-standalone/errors.d.ts +10 -0
  166. package/dist-standalone/errors.js +1 -811
  167. package/dist-standalone/event-emitter.d.ts +395 -0
  168. package/dist-standalone/event-emitter.js +1 -0
  169. package/dist-standalone/gateway-state.js +1 -51
  170. package/dist-standalone/gateway-transport.js +1 -116
  171. package/dist-standalone/graceful-degradation.d.ts +246 -0
  172. package/dist-standalone/graceful-degradation.js +1 -0
  173. package/dist-standalone/guardrails.js +1 -216
  174. package/dist-standalone/health-check.d.ts +150 -0
  175. package/dist-standalone/health-check.js +1 -0
  176. package/dist-standalone/http-compat.js +1 -267
  177. package/dist-standalone/http-status-map.js +1 -561
  178. package/dist-standalone/identity.d.ts +64 -1
  179. package/dist-standalone/identity.js +1 -515
  180. package/dist-standalone/index.d.ts +45 -3
  181. package/dist-standalone/index.js +1 -52
  182. package/dist-standalone/invitation.js +1 -415
  183. package/dist-standalone/invite.js +1 -324
  184. package/dist-standalone/key-agreement.d.ts +61 -13
  185. package/dist-standalone/key-agreement.js +1 -236
  186. package/dist-standalone/lazy-init.js +1 -295
  187. package/dist-standalone/logger.d.ts +77 -0
  188. package/dist-standalone/logger.js +1 -0
  189. package/dist-standalone/mdns-discovery.js +1 -195
  190. package/dist-standalone/nonce-store.d.ts +16 -3
  191. package/dist-standalone/nonce-store.js +1 -62
  192. package/dist-standalone/package.json +0 -1
  193. package/dist-standalone/pairing-manager.js +1 -219
  194. package/dist-standalone/plugin-system.d.ts +145 -0
  195. package/dist-standalone/plugin-system.js +1 -0
  196. package/dist-standalone/policy.js +1 -315
  197. package/dist-standalone/progress-callbacks.d.ts +394 -0
  198. package/dist-standalone/progress-callbacks.js +1 -0
  199. package/dist-standalone/redis-nonce-store.js +1 -72
  200. package/dist-standalone/registry-middleware.js +1 -47
  201. package/dist-standalone/retry-strategies.d.ts +382 -0
  202. package/dist-standalone/retry-strategies.js +1 -0
  203. package/dist-standalone/retry-transport.js +1 -98
  204. package/dist-standalone/security-policy.js +1 -239
  205. package/dist-standalone/serialization.d.ts +244 -0
  206. package/dist-standalone/serialization.js +1 -0
  207. package/dist-standalone/split-channel.d.ts +49 -1
  208. package/dist-standalone/split-channel.js +1 -171
  209. package/dist-standalone/subscription-proof.js +1 -224
  210. package/dist-standalone/succession.js +1 -142
  211. package/dist-standalone/timeouts.d.ts +275 -0
  212. package/dist-standalone/timeouts.js +1 -0
  213. package/dist-standalone/trace-context.d.ts +252 -0
  214. package/dist-standalone/trace-context.js +1 -0
  215. package/dist-standalone/trace-spans.d.ts +360 -0
  216. package/dist-standalone/trace-spans.js +1 -0
  217. package/dist-standalone/transport.js +1 -59
  218. package/dist-standalone/trust-registry.d.ts +106 -5
  219. package/dist-standalone/trust-registry.js +1 -702
  220. package/dist-standalone/vault-auth.d.ts +91 -0
  221. package/dist-standalone/vault-auth.js +1 -0
  222. package/dist-standalone/vault-store-loader.d.ts +110 -0
  223. package/dist-standalone/vault-store-loader.js +1 -0
  224. package/dist-standalone/verify.js +1 -16
  225. package/dist-standalone/version-info.d.ts +259 -0
  226. package/dist-standalone/version-info.js +1 -0
  227. package/dist-standalone/xfetch.js +1 -247
  228. package/llms.txt +1 -0
  229. package/package.json +65 -5
  230. package/share1.dat +0 -0
  231. package/dist-standalone/_deps/crypto/base64.d.ts +0 -29
  232. package/dist-standalone/_deps/crypto/base64.js +0 -222
  233. package/dist-standalone/_deps/crypto/cjs/base64.js +0 -665
  234. package/dist-standalone/_deps/crypto/cjs/errors.js +0 -675
  235. package/dist-standalone/_deps/crypto/cjs/hmac.js +0 -473
  236. package/dist-standalone/_deps/crypto/cjs/index.js +0 -852
  237. package/dist-standalone/_deps/crypto/cjs/package.json +0 -1
  238. package/dist-standalone/_deps/crypto/cjs/padding.js +0 -511
  239. package/dist-standalone/_deps/crypto/cjs/share-header.js +0 -372
  240. package/dist-standalone/_deps/crypto/cjs/shares.js +0 -874
  241. package/dist-standalone/_deps/crypto/cjs/tlv.js +0 -1021
  242. package/dist-standalone/_deps/crypto/cjs/uuid.js +0 -443
  243. package/dist-standalone/_deps/crypto/cjs/verify.js +0 -414
  244. package/dist-standalone/_deps/crypto/cjs/xorida.js +0 -923
  245. package/dist-standalone/_deps/crypto/errors.d.ts +0 -51
  246. package/dist-standalone/_deps/crypto/errors.js +0 -199
  247. package/dist-standalone/_deps/crypto/hmac.d.ts +0 -39
  248. package/dist-standalone/_deps/crypto/hmac.js +0 -134
  249. package/dist-standalone/_deps/crypto/index.d.ts +0 -20
  250. package/dist-standalone/_deps/crypto/index.js +0 -145
  251. package/dist-standalone/_deps/crypto/padding.d.ts +0 -19
  252. package/dist-standalone/_deps/crypto/padding.js +0 -159
  253. package/dist-standalone/_deps/crypto/share-header.d.ts +0 -44
  254. package/dist-standalone/_deps/crypto/share-header.js +0 -92
  255. package/dist-standalone/_deps/crypto/shares.d.ts +0 -27
  256. package/dist-standalone/_deps/crypto/shares.js +0 -295
  257. package/dist-standalone/_deps/crypto/tlv.d.ts +0 -26
  258. package/dist-standalone/_deps/crypto/tlv.js +0 -364
  259. package/dist-standalone/_deps/crypto/uuid.d.ts +0 -22
  260. package/dist-standalone/_deps/crypto/uuid.js +0 -136
  261. package/dist-standalone/_deps/crypto/verify.d.ts +0 -15
  262. package/dist-standalone/_deps/crypto/verify.js +0 -71
  263. package/dist-standalone/_deps/crypto/xorida.d.ts +0 -44
  264. package/dist-standalone/_deps/crypto/xorida.js +0 -366
  265. package/dist-standalone/_deps/shared/errors.d.ts.map +0 -1
  266. package/dist-standalone/_deps/shared/errors.js.map +0 -1
  267. package/dist-standalone/_deps/shared/index.d.ts.map +0 -1
  268. package/dist-standalone/_deps/shared/index.js.map +0 -1
  269. package/dist-standalone/_deps/shared/types.d.ts.map +0 -1
  270. package/dist-standalone/_deps/shared/types.js.map +0 -1
  271. package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts.map +0 -1
  272. package/dist-standalone/_deps/ux-helpers/cjs/errors.js.map +0 -1
  273. package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts.map +0 -1
  274. package/dist-standalone/_deps/ux-helpers/cjs/index.js.map +0 -1
  275. package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts.map +0 -1
  276. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js.map +0 -1
  277. package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts.map +0 -1
  278. package/dist-standalone/_deps/ux-helpers/cjs/progress.js.map +0 -1
  279. package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts.map +0 -1
  280. package/dist-standalone/_deps/ux-helpers/cjs/search.js.map +0 -1
  281. package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts.map +0 -1
  282. package/dist-standalone/_deps/ux-helpers/cjs/types.js.map +0 -1
  283. package/dist-standalone/_deps/ux-helpers/errors.d.ts.map +0 -1
  284. package/dist-standalone/_deps/ux-helpers/errors.js.map +0 -1
  285. package/dist-standalone/_deps/ux-helpers/index.d.ts.map +0 -1
  286. package/dist-standalone/_deps/ux-helpers/index.js.map +0 -1
  287. package/dist-standalone/_deps/ux-helpers/pagination.d.ts.map +0 -1
  288. package/dist-standalone/_deps/ux-helpers/pagination.js.map +0 -1
  289. package/dist-standalone/_deps/ux-helpers/progress.d.ts.map +0 -1
  290. package/dist-standalone/_deps/ux-helpers/progress.js.map +0 -1
  291. package/dist-standalone/_deps/ux-helpers/search.d.ts.map +0 -1
  292. package/dist-standalone/_deps/ux-helpers/search.js.map +0 -1
  293. package/dist-standalone/_deps/ux-helpers/types.d.ts.map +0 -1
  294. package/dist-standalone/_deps/ux-helpers/types.js.map +0 -1
  295. package/dist-standalone/_deps/xregistry/discovery.d.ts.map +0 -1
  296. package/dist-standalone/_deps/xregistry/discovery.js.map +0 -1
  297. package/dist-standalone/_deps/xregistry/errors.d.ts.map +0 -1
  298. package/dist-standalone/_deps/xregistry/errors.js.map +0 -1
  299. package/dist-standalone/_deps/xregistry/index.d.ts.map +0 -1
  300. package/dist-standalone/_deps/xregistry/index.js.map +0 -1
  301. package/dist-standalone/_deps/xregistry/registry.d.ts.map +0 -1
  302. package/dist-standalone/_deps/xregistry/registry.js.map +0 -1
  303. package/dist-standalone/_deps/xregistry/schema.d.ts.map +0 -1
  304. package/dist-standalone/_deps/xregistry/schema.js.map +0 -1
  305. package/dist-standalone/_deps/xregistry/types.d.ts.map +0 -1
  306. package/dist-standalone/_deps/xregistry/types.js.map +0 -1
@@ -1,219 +1 @@
1
- /**
2
- * Xlock auth challenge module for Agent SDK.
3
- *
4
- * Provides requestAuth(), respondToChallenge(), and onChallenge()
5
- * functions that work with an Agent instance and the XBind gateway.
6
- *
7
- * These functions are also re-exported as thin methods on the Agent class.
8
- */
9
- import { ok, err } from"./_deps/shared/index.js";
10
- import { createSignedEnvelope } from './envelope.js';
11
- /** Default poll interval for challenge status. */
12
- const DEFAULT_POLL_INTERVAL_MS = 2_000;
13
- /** Default TTL for challenges (5 minutes). */
14
- const DEFAULT_TTL_MS = 5 * 60 * 1000;
15
- /** Max poll iterations (TTL / pollInterval + safety margin). */
16
- const MAX_POLL_ITERATIONS = 200;
17
- /**
18
- * Create an auth challenge and poll until the user responds.
19
- *
20
- * Sends a challenge via the XBind gateway, then polls the status
21
- * endpoint until the challenge is approved, denied, or expires.
22
- *
23
- * @param agent - The Agent requesting authorization.
24
- * @param request - Auth request details (recipient DID, action, metadata).
25
- * @param gateway - Gateway connection options.
26
- * @returns Auth result (approved/denied) or error.
27
- */
28
- export async function requestAuth(agent, request, gateway) {
29
- const ttlMs = request.ttlMs ?? DEFAULT_TTL_MS;
30
- const pollIntervalMs = request.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
31
- // Build the challenge payload
32
- const payload = {
33
- recipientDid: request.to,
34
- action: request.action,
35
- metadata: request.metadata ?? {},
36
- ttlMs,
37
- };
38
- // Create a signed envelope wrapping the challenge request
39
- const envelopeResult = await createSignedEnvelope({
40
- senderDid: agent.did,
41
- recipientDid: request.to,
42
- scope: 'xlock:challenge',
43
- plaintext: new TextEncoder().encode(JSON.stringify(payload)),
44
- privateKey: agent.identity.privateKey,
45
- });
46
- if (!envelopeResult.ok) {
47
- return err('INVALID_REQUEST');
48
- }
49
- // POST to gateway
50
- let challengeId;
51
- let expiresAt;
52
- try {
53
- const response = await fetch(`${gateway.gatewayUrl}/gateway/auth/challenge`, {
54
- method: 'POST',
55
- headers: { 'Content-Type': 'application/json' },
56
- body: JSON.stringify(envelopeResult.value),
57
- });
58
- if (response.status === 429)
59
- return err('RATE_LIMITED');
60
- if (!response.ok) {
61
- const body = await response.json().catch(() => null);
62
- const code = body
63
- ?.error?.code;
64
- return err(code ?? 'INVALID_REQUEST');
65
- }
66
- const data = await response.json();
67
- challengeId = data.challengeId;
68
- expiresAt = data.expiresAt;
69
- }
70
- catch {
71
- return err('INVALID_REQUEST');
72
- }
73
- // Poll for status
74
- return pollChallengeStatus(challengeId, expiresAt, pollIntervalMs, gateway);
75
- }
76
- /**
77
- * Respond to an incoming auth challenge (approve or deny).
78
- *
79
- * Sends a signed response envelope to the gateway.
80
- *
81
- * @param agent - The Agent responding to the challenge.
82
- * @param challengeId - The challenge ID to respond to.
83
- * @param approved - Whether the user approved the challenge.
84
- * @param gateway - Gateway connection options.
85
- * @returns Success or error.
86
- */
87
- export async function respondToChallenge(agent, challengeId, approved, gateway) {
88
- const payload = {
89
- challengeId,
90
- approved,
91
- timestamp: Date.now(),
92
- };
93
- // Create a signed envelope for the response
94
- const envelopeResult = await createSignedEnvelope({
95
- senderDid: agent.did,
96
- recipientDid: agent.did, // Self-addressed (gateway verifies recipient match)
97
- scope: 'xlock:respond',
98
- plaintext: new TextEncoder().encode(JSON.stringify(payload)),
99
- privateKey: agent.identity.privateKey,
100
- });
101
- if (!envelopeResult.ok) {
102
- return err('INVALID_REQUEST');
103
- }
104
- try {
105
- const response = await fetch(`${gateway.gatewayUrl}/gateway/auth/respond`, {
106
- method: 'POST',
107
- headers: { 'Content-Type': 'application/json' },
108
- body: JSON.stringify({
109
- ...envelopeResult.value,
110
- // Include response fields at top level for the server
111
- challengeId,
112
- approved,
113
- responseEnvelope: envelopeResult.value,
114
- }),
115
- });
116
- if (!response.ok) {
117
- const body = await response.json().catch(() => null);
118
- const code = body
119
- ?.error?.code;
120
- return err(code ?? 'INVALID_REQUEST');
121
- }
122
- return ok(undefined);
123
- }
124
- catch {
125
- return err('INVALID_REQUEST');
126
- }
127
- }
128
- /**
129
- * Register a callback for incoming auth challenges via WebSocket.
130
- *
131
- * The callback fires when an `auth:challenge` message arrives
132
- * over the gateway WebSocket connection.
133
- *
134
- * @param ws - The WebSocket connection to the gateway.
135
- * @param callback - Handler for incoming challenges.
136
- * @returns Cleanup function to unregister the listener.
137
- */
138
- export function onChallenge(ws, callback) {
139
- const handler = (event) => {
140
- try {
141
- const msg = JSON.parse(event.data);
142
- if (msg.type === 'auth:challenge' && msg.data) {
143
- callback(msg.data);
144
- }
145
- }
146
- catch {
147
- // Skip non-JSON messages
148
- }
149
- };
150
- ws.addEventListener('message', handler);
151
- return () => ws.removeEventListener('message', handler);
152
- }
153
- /**
154
- * Generate a registration QR code URI for TOTP migration.
155
- *
156
- * Creates a `xlock://register` URI that replaces `otpauth://` for
157
- * asymmetric DID-based registration.
158
- *
159
- * @param options - Registration options.
160
- * @returns The registration URI string.
161
- */
162
- export function generateRegistrationQR(options) {
163
- const params = new URLSearchParams({
164
- app: options.appName,
165
- did: options.appDid,
166
- registry: options.registryUrl,
167
- callback: options.callbackUrl,
168
- });
169
- if (options.appIcon)
170
- params.set('icon', options.appIcon);
171
- return `xlock://register?${params.toString()}`;
172
- }
173
- /** Poll the gateway for challenge status until resolved or expired. */
174
- async function pollChallengeStatus(challengeId, expiresAt, pollIntervalMs, gateway) {
175
- for (let i = 0; i < MAX_POLL_ITERATIONS; i++) {
176
- if (Date.now() > expiresAt) {
177
- return err('CHALLENGE_EXPIRED');
178
- }
179
- await sleep(pollIntervalMs);
180
- try {
181
- const response = await fetch(`${gateway.gatewayUrl}/gateway/auth/status/${challengeId}`, {
182
- headers: { Authorization: `Bearer ${gateway.accessToken}` },
183
- });
184
- if (!response.ok) {
185
- if (response.status === 404)
186
- return err('CHALLENGE_NOT_FOUND');
187
- continue; // Retry on transient errors
188
- }
189
- const data = await response.json();
190
- if (data.status === 'approved') {
191
- return ok({
192
- challengeId: data.challengeId,
193
- approved: true,
194
- respondedAt: data.respondedAt,
195
- envelope: data.envelope,
196
- });
197
- }
198
- if (data.status === 'denied') {
199
- return ok({
200
- challengeId: data.challengeId,
201
- approved: false,
202
- respondedAt: data.respondedAt,
203
- });
204
- }
205
- if (data.status === 'expired') {
206
- return err('CHALLENGE_EXPIRED');
207
- }
208
- // Still pending — continue polling
209
- }
210
- catch {
211
- // Network error — continue polling
212
- }
213
- }
214
- return err('CHALLENGE_TIMEOUT');
215
- }
216
- /** Promise-based sleep. */
217
- function sleep(ms) {
218
- return new Promise((resolve) => setTimeout(resolve, ms));
219
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{createSignedEnvelope}from"./envelope.js";const DEFAULT_POLL_INTERVAL_MS=2e3,DEFAULT_TTL_MS=3e5,MAX_POLL_ITERATIONS=200;export async function requestAuth(e,t,r){const n=t.ttlMs??3e5,a=t.pollIntervalMs??2e3,o={recipientDid:t.to,action:t.action,metadata:t.metadata??{},ttlMs:n},i=await createSignedEnvelope({senderDid:e.did,recipientDid:t.to,scope:"xlock:challenge",plaintext:(new TextEncoder).encode(JSON.stringify(o)),privateKey:e.identity.privateKey});if(!i.ok)return err("INVALID_REQUEST");let s,c;try{const e=await fetch(`${r.gatewayUrl}/gateway/auth/challenge`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i.value)});if(429===e.status)return err("RATE_LIMITED");if(!e.ok){const t=await e.json().catch(()=>null),r=t?.error?.code;return err(r??"INVALID_REQUEST")}const t=await e.json();s=t.challengeId,c=t.expiresAt}catch{return err("INVALID_REQUEST")}return pollChallengeStatus(s,c,a,r)}export async function respondToChallenge(e,t,r,n){const a={challengeId:t,approved:r,timestamp:Date.now()},o=await createSignedEnvelope({senderDid:e.did,recipientDid:e.did,scope:"xlock:respond",plaintext:(new TextEncoder).encode(JSON.stringify(a)),privateKey:e.identity.privateKey});if(!o.ok)return err("INVALID_REQUEST");try{const e=await fetch(`${n.gatewayUrl}/gateway/auth/respond`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...o.value,challengeId:t,approved:r,responseEnvelope:o.value})});if(!e.ok){const t=await e.json().catch(()=>null),r=t?.error?.code;return err(r??"INVALID_REQUEST")}return ok(void 0)}catch{return err("INVALID_REQUEST")}}export function onChallenge(e,t){const r=e=>{try{const r=JSON.parse(e.data);"auth:challenge"===r.type&&r.data&&t(r.data)}catch{}};return e.addEventListener("message",r),()=>e.removeEventListener("message",r)}export function generateRegistrationQR(e){const t=new URLSearchParams({app:e.appName,did:e.appDid,registry:e.registryUrl,callback:e.callbackUrl});return e.appIcon&&t.set("icon",e.appIcon),`xlock://register?${t.toString()}`}async function pollChallengeStatus(e,t,r,n){for(let a=0;a<200;a++){if(Date.now()>t)return err("CHALLENGE_EXPIRED");await sleep(r);try{const t=await fetch(`${n.gatewayUrl}/gateway/auth/status/${e}`,{headers:{Authorization:`Bearer ${n.accessToken}`}});if(!t.ok){if(404===t.status)return err("CHALLENGE_NOT_FOUND");continue}const r=await t.json();if("approved"===r.status)return ok({challengeId:r.challengeId,approved:!0,respondedAt:r.respondedAt,envelope:r.envelope});if("denied"===r.status)return ok({challengeId:r.challengeId,approved:!1,respondedAt:r.respondedAt});if("expired"===r.status)return err("CHALLENGE_EXPIRED")}catch{}}return err("CHALLENGE_TIMEOUT")}function sleep(e){return new Promise(t=>setTimeout(t,e))}
@@ -1,229 +1 @@
1
- /**
2
- * @module auto-accept
3
- * Auto-accept invite on first SDK call for zero-click onboarding.
4
- *
5
- * Enables services to accept invites automatically without explicit
6
- * accept commands. Invite code comes from environment variable.
7
- *
8
- * @example
9
- * ```ts
10
- * // Environment: XBIND_INVITE_CODE=XBD-abc123, XBIND_AUTO_ACCEPT=true
11
- *
12
- * // Auto-accept happens on first Agent method call:
13
- * const agent = Agent.lazy({ name: 'my-service' });
14
- * await agent.send({ to: partnerDid, payload: data, scope: 'test' });
15
- * // ↑ Invite auto-accepted before send()
16
- * ```
17
- */
18
- import { ok, err } from"./_deps/shared/index.js";
19
- import { InviteService } from './invite.js';
20
- import { HttpTrustRegistry, MemoryTrustRegistry } from './trust-registry.js';
21
- import { fromBase64 } from"./_deps/crypto/index.js";
22
- import { importPublicKey } from './identity.js';
23
- /**
24
- * Auto-accept error codes.
25
- */
26
- export var AutoAcceptErrorCode;
27
- (function (AutoAcceptErrorCode) {
28
- AutoAcceptErrorCode["NO_INVITE_CODE"] = "AUTO_ACCEPT_NO_INVITE_CODE";
29
- AutoAcceptErrorCode["DISABLED"] = "AUTO_ACCEPT_DISABLED";
30
- AutoAcceptErrorCode["INVITE_FAILED"] = "AUTO_ACCEPT_INVITE_FAILED";
31
- AutoAcceptErrorCode["REGISTRY_SETUP_FAILED"] = "AUTO_ACCEPT_REGISTRY_SETUP_FAILED";
32
- })(AutoAcceptErrorCode || (AutoAcceptErrorCode = {}));
33
- /**
34
- * Auto-accept an invite on first SDK call.
35
- *
36
- * Reads invite code from config or environment variable `XBIND_INVITE_CODE`.
37
- * If `XBIND_AUTO_ACCEPT` is false, returns error with code DISABLED.
38
- *
39
- * When successful:
40
- * 1. Fetches invite details from invite server
41
- * 2. Adds inviter to trust registry
42
- * 3. Auto-detects registry endpoint from invite metadata (if present)
43
- * 4. Marks invite as accepted
44
- *
45
- * This is called internally by `Agent.lazy()` before the first send/receive.
46
- *
47
- * @param config - Auto-accept configuration
48
- * @param acceptorInfo - Acceptor service info (DID, endpoint, publicKey)
49
- * @returns Accept details or error
50
- *
51
- * @example
52
- * ```ts
53
- * // Manual usage (typically called internally by Agent.lazy):
54
- * const result = await autoAcceptInvite(
55
- * { inviteCode: 'XBD-abc123' },
56
- * {
57
- * name: 'my-service',
58
- * did: 'did:key:z6Mk...',
59
- * endpoint: 'https://my-service.com',
60
- * publicKey: '...',
61
- * }
62
- * );
63
- *
64
- * if (result.ok) {
65
- * console.log('Auto-accepted invite from:', result.value.from.name);
66
- * }
67
- * ```
68
- */
69
- export async function autoAcceptInvite(config, acceptorInfo) {
70
- // Step 1: Check if auto-accept is enabled
71
- const autoAcceptEnabled = config.enabled ?? getEnvFlag('XBIND_AUTO_ACCEPT', true);
72
- if (!autoAcceptEnabled) {
73
- return err({
74
- code: AutoAcceptErrorCode.DISABLED,
75
- message: 'Auto-accept is disabled',
76
- hint: 'Set XBIND_AUTO_ACCEPT=true or pass { enabled: true } in config',
77
- });
78
- }
79
- // Step 2: Get invite code
80
- const inviteCode = config.inviteCode ?? getEnv('XBIND_INVITE_CODE');
81
- if (!inviteCode) {
82
- return err({
83
- code: AutoAcceptErrorCode.NO_INVITE_CODE,
84
- message: 'No invite code provided',
85
- hint: 'Set XBIND_INVITE_CODE environment variable or pass inviteCode in config',
86
- });
87
- }
88
- // Step 3: Fetch invite details
89
- const inviteService = new InviteService({
90
- inviteApiUrl: config.inviteApiUrl ?? getEnv('XBIND_INVITE_API_URL') ?? 'https://xbind.to',
91
- });
92
- const inviteUrl = normalizeInviteCode(inviteCode);
93
- const inviteResult = await inviteService.get(inviteUrl);
94
- if (!inviteResult.ok) {
95
- return err({
96
- code: AutoAcceptErrorCode.INVITE_FAILED,
97
- message: `Failed to fetch invite: ${inviteResult.error.message}`,
98
- hint: inviteResult.error.hint,
99
- cause: inviteResult.error,
100
- });
101
- }
102
- const invite = inviteResult.value;
103
- // Step 4: Add inviter to trust registry
104
- const registry = config.registry ?? await autoConfigureRegistry(invite);
105
- try {
106
- // Import public key from base64
107
- const publicKeyBytes = fromBase64(invite.from.publicKey);
108
- const publicKeyResult = await importPublicKey(publicKeyBytes);
109
- if (!publicKeyResult.ok) {
110
- return err({
111
- code: AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,
112
- message: 'Invalid inviter public key',
113
- hint: 'The invite may be corrupted',
114
- cause: publicKeyResult.error,
115
- });
116
- }
117
- // Add to registry
118
- const addResult = await registry.register(invite.from.did, publicKeyBytes, invite.from.name, invite.permissions, invite.from.x25519PublicKey ? fromBase64(invite.from.x25519PublicKey) : undefined, invite.from.mlKemPublicKey ? fromBase64(invite.from.mlKemPublicKey) : undefined, undefined, // mlDsaPublicKey (not in invite yet)
119
- false);
120
- if (!addResult.ok) {
121
- // If already registered, that's OK (idempotent)
122
- if (addResult.error !== 'ALREADY_REGISTERED') {
123
- return err({
124
- code: AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,
125
- message: `Failed to add inviter to registry: ${addResult.error}`,
126
- cause: addResult.error,
127
- });
128
- }
129
- }
130
- }
131
- catch (error) {
132
- return err({
133
- code: AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,
134
- message: 'Failed to configure trust registry',
135
- cause: error,
136
- });
137
- }
138
- // Step 5: Accept the invite (marks as accepted on server)
139
- const acceptResult = await inviteService.accept({ inviteUrl, acceptor: acceptorInfo });
140
- if (!acceptResult.ok) {
141
- // Non-fatal: invite acceptance is for tracking/notification only
142
- // The connection is still established locally via registry add
143
- }
144
- return ok({
145
- invite,
146
- from: invite.from,
147
- registryUrl: extractRegistryUrl(invite),
148
- registryAutoconfigured: config.registry === undefined,
149
- });
150
- }
151
- /**
152
- * Auto-configure trust registry from invite metadata.
153
- *
154
- * Attempts to extract registry URL from invite. If found, creates HttpTrustRegistry.
155
- * Otherwise falls back to MemoryTrustRegistry.
156
- *
157
- * @param invite - Invite details
158
- * @returns Trust registry instance
159
- */
160
- async function autoConfigureRegistry(invite) {
161
- const registryUrl = extractRegistryUrl(invite);
162
- if (registryUrl) {
163
- return new HttpTrustRegistry({ baseUrl: registryUrl });
164
- }
165
- return new MemoryTrustRegistry();
166
- }
167
- /**
168
- * Extract registry URL from invite metadata.
169
- *
170
- * Checks for registry URL in invite.from.endpoint or custom metadata fields.
171
- *
172
- * @param invite - Invite details
173
- * @returns Registry URL or undefined
174
- */
175
- function extractRegistryUrl(invite) {
176
- // Check if endpoint is a registry URL (heuristic: contains /registry or /trust)
177
- if (invite.from.endpoint.includes('/registry') || invite.from.endpoint.includes('/trust')) {
178
- return invite.from.endpoint;
179
- }
180
- // Future: check invite.metadata.registryUrl when invite system adds it
181
- return undefined;
182
- }
183
- /**
184
- * Normalize invite code to full URL.
185
- *
186
- * If code is already a URL, returns as-is.
187
- * If code is short form (e.g., 'XBD-abc123'), converts to https://xbind.to/invite/{code}.
188
- *
189
- * @param code - Invite code or URL
190
- * @returns Full invite URL
191
- */
192
- function normalizeInviteCode(code) {
193
- if (code.startsWith('http://') || code.startsWith('https://')) {
194
- return code;
195
- }
196
- // Short form: XBD-abc123 or just abc123
197
- const cleanCode = code.replace(/^XBD-/i, '');
198
- return `https://xbind.to/invite/${cleanCode}`;
199
- }
200
- /**
201
- * Get environment variable value.
202
- *
203
- * @param key - Environment variable name
204
- * @param defaultValue - Default value if not set
205
- * @returns Environment variable value or default
206
- */
207
- function getEnv(key, defaultValue) {
208
- // SAFETY: Check for Node.js environment before accessing process
209
- if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {
210
- return process.env[key] ?? defaultValue;
211
- }
212
- return defaultValue;
213
- }
214
- /**
215
- * Get environment variable as boolean flag.
216
- *
217
- * Treats 'true', '1', 'yes' as true. Everything else as false.
218
- *
219
- * @param key - Environment variable name
220
- * @param defaultValue - Default value if not set
221
- * @returns Boolean flag
222
- */
223
- function getEnvFlag(key, defaultValue) {
224
- const value = getEnv(key);
225
- if (value === undefined)
226
- return defaultValue;
227
- const normalized = value.toLowerCase().trim();
228
- return normalized === 'true' || normalized === '1' || normalized === 'yes';
229
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{InviteService}from"./invite.js";import{HttpTrustRegistry,MemoryTrustRegistry}from"./trust-registry.js";import{fromBase64}from"./crypto-utils.js";import{importPublicKey}from"./identity.js";export var AutoAcceptErrorCode;!function(e){e.NO_INVITE_CODE="AUTO_ACCEPT_NO_INVITE_CODE",e.DISABLED="AUTO_ACCEPT_DISABLED",e.INVITE_FAILED="AUTO_ACCEPT_INVITE_FAILED",e.REGISTRY_SETUP_FAILED="AUTO_ACCEPT_REGISTRY_SETUP_FAILED"}(AutoAcceptErrorCode||(AutoAcceptErrorCode={}));export async function autoAcceptInvite(e,r){if(!(e.enabled??getEnvFlag("XBIND_AUTO_ACCEPT",!0)))return err({code:AutoAcceptErrorCode.DISABLED,message:"Auto-accept is disabled",hint:"Set XBIND_AUTO_ACCEPT=true or pass { enabled: true } in config"});const t=e.inviteCode??getEnv("XBIND_INVITE_CODE");if(!t)return err({code:AutoAcceptErrorCode.NO_INVITE_CODE,message:"No invite code provided",hint:"Set XBIND_INVITE_CODE environment variable or pass inviteCode in config"});const o=new InviteService({inviteApiUrl:e.inviteApiUrl??getEnv("XBIND_INVITE_API_URL")??"https://xbind.to"}),i=normalizeInviteCode(t),n=await o.get(i);if(!n.ok)return err({code:AutoAcceptErrorCode.INVITE_FAILED,message:`Failed to fetch invite: ${n.error.message}`,hint:n.error.hint,cause:n.error});const s=n.value,c=e.registry??await autoConfigureRegistry(s);try{const e=fromBase64(s.from.publicKey),r=await importPublicKey(e);if(!r.ok)return err({code:AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,message:"Invalid inviter public key",hint:"The invite may be corrupted",cause:r.error});const t=await c.register(s.from.did,e,s.from.name,s.permissions,s.from.x25519PublicKey?fromBase64(s.from.x25519PublicKey):void 0,s.from.mlKemPublicKey?fromBase64(s.from.mlKemPublicKey):void 0,void 0,!1);if(!t.ok&&"ALREADY_REGISTERED"!==t.error)return err({code:AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,message:`Failed to add inviter to registry: ${t.error}`,cause:t.error})}catch(e){return err({code:AutoAcceptErrorCode.REGISTRY_SETUP_FAILED,message:"Failed to configure trust registry",cause:e})}return(await o.accept({inviteUrl:i,acceptor:r})).ok,ok({invite:s,from:s.from,registryUrl:extractRegistryUrl(s),registryAutoconfigured:void 0===e.registry})}async function autoConfigureRegistry(e){const r=extractRegistryUrl(e);return r?new HttpTrustRegistry({baseUrl:r}):new MemoryTrustRegistry}function extractRegistryUrl(e){if(e.from.endpoint.includes("/registry")||e.from.endpoint.includes("/trust"))return e.from.endpoint}function normalizeInviteCode(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;return`https://xbind.to/invite/${e.replace(/^XBD-/i,"")}`}function getEnv(e,r){return"undefined"!=typeof process&&void 0!==process.env?process.env[e]??r:r}function getEnvFlag(e,r){const t=getEnv(e);if(void 0===t)return r;const o=t.toLowerCase().trim();return"true"===o||"1"===o||"yes"===o}
@@ -1,201 +1 @@
1
- /**
2
- * XorIDA Backup Configuration for Key Splitting
3
- *
4
- * Provides default backup configuration (k=2, n=3) and utilities for
5
- * splitting cryptographic keys across multiple shares using information-
6
- * theoretic threshold secret sharing.
7
- *
8
- * @module backup-config
9
- */
10
- import { ok, err } from"./_deps/shared/index.js";
11
- import { splitXorIDA, reconstructXorIDA, nextOddPrime, pkcs7Pad, pkcs7Unpad, generateHMAC, verifyHMAC, toBase64, fromBase64, } from"./_deps/crypto/index.js";
12
- /* ── Constants ── */
13
- /**
14
- * Default backup configuration: 2-of-3 threshold sharing.
15
- *
16
- * - 3 shares generated
17
- * - Any 2 shares can reconstruct the key
18
- * - Lose 1 share and still recover (fault tolerance)
19
- * - Information-theoretic security (each share reveals zero information)
20
- */
21
- export const DEFAULT_BACKUP_CONFIG = {
22
- threshold: 2,
23
- totalShares: 3,
24
- };
25
- /* ── Validation ── */
26
- /**
27
- * Validate backup configuration parameters.
28
- *
29
- * Rules:
30
- * - threshold must be >= 2 (single share = no threshold)
31
- * - totalShares must be >= threshold
32
- * - totalShares must be <= 255 (XorIDA limit)
33
- *
34
- * @param config - Backup configuration to validate.
35
- * @returns Ok if valid, error otherwise.
36
- */
37
- export function validateBackupConfig(config) {
38
- if (config.threshold < 2) {
39
- return err('INVALID_CONFIG');
40
- }
41
- if (config.totalShares < config.threshold) {
42
- return err('INVALID_CONFIG');
43
- }
44
- if (config.totalShares > 255) {
45
- return err('INVALID_CONFIG');
46
- }
47
- return ok(undefined);
48
- }
49
- /* ── Key Splitting ── */
50
- /**
51
- * Split a cryptographic key into backup shares using XorIDA.
52
- *
53
- * The key is padded, split via information-theoretic threshold sharing,
54
- * and returned as BackupShare objects with HMAC integrity protection.
55
- *
56
- * Any `threshold` shares can reconstruct the original key. Each share
57
- * reveals zero information about the key (information-theoretic security).
58
- *
59
- * @param key - The key to split (32 or 64 bytes typical).
60
- * @param config - Backup configuration (defaults to 2-of-3).
61
- * @returns Array of backup shares or error.
62
- *
63
- * @example
64
- * ```typescript
65
- * import { splitKeyWithBackup, DEFAULT_BACKUP_CONFIG } from '@private.me/xbind';
66
- *
67
- * const key = crypto.getRandomValues(new Uint8Array(32));
68
- *
69
- * // Use defaults (2-of-3)
70
- * const shares = await splitKeyWithBackup(key);
71
- *
72
- * // Custom config (3-of-5)
73
- * const shares2 = await splitKeyWithBackup(key, {
74
- * threshold: 3,
75
- * totalShares: 5
76
- * });
77
- *
78
- * if (shares.ok) {
79
- * // Store shares in separate locations
80
- * shares.value.forEach((share, i) => {
81
- * storeShare(`backup-${i}.json`, JSON.stringify(share));
82
- * });
83
- * }
84
- * ```
85
- */
86
- export async function splitKeyWithBackup(key, config = DEFAULT_BACKUP_CONFIG) {
87
- const validation = validateBackupConfig(config);
88
- if (!validation.ok)
89
- return validation;
90
- if (key.length === 0) {
91
- return err('INVALID_KEY_LENGTH');
92
- }
93
- const n = config.totalShares;
94
- const k = config.threshold;
95
- const p = nextOddPrime(n);
96
- const blockSize = p - 1;
97
- // Pad to block size
98
- const padded = pkcs7Pad(key, blockSize);
99
- // Generate HMAC for integrity verification
100
- const { key: hmacKey, signature: hmacSig } = await generateHMAC(padded);
101
- const hmacKeyB64 = toBase64(hmacKey);
102
- const hmacSigB64 = toBase64(hmacSig);
103
- // Split via XorIDA
104
- let shareArrays;
105
- try {
106
- shareArrays = splitXorIDA(padded, n, k);
107
- }
108
- catch {
109
- return err('SPLIT_FAILED');
110
- }
111
- // Package as BackupShare objects
112
- const shares = shareArrays.map((data, index) => ({
113
- index,
114
- data: toBase64(data),
115
- total: n,
116
- threshold: k,
117
- hmacKey: hmacKeyB64,
118
- hmacSig: hmacSigB64,
119
- }));
120
- return ok(shares);
121
- }
122
- /* ── Key Reconstruction ── */
123
- /**
124
- * Reconstruct a cryptographic key from backup shares.
125
- *
126
- * Requires at least `threshold` shares. Verifies HMAC before returning
127
- * the reconstructed key to prevent tampering.
128
- *
129
- * @param shares - Backup shares (must be >= threshold).
130
- * @returns Reconstructed key or error.
131
- *
132
- * @example
133
- * ```typescript
134
- * import { reconstructKeyFromBackup } from '@private.me/xbind';
135
- *
136
- * // Load shares from storage
137
- * const share0 = JSON.parse(loadShare('backup-0.json'));
138
- * const share1 = JSON.parse(loadShare('backup-1.json'));
139
- *
140
- * // Reconstruct from any 2 shares (threshold=2)
141
- * const key = await reconstructKeyFromBackup([share0, share1]);
142
- *
143
- * if (key.ok) {
144
- * // Use reconstructed key
145
- * const agent = await Agent.fromSeed(key.value, opts);
146
- * } else {
147
- * console.error('Reconstruction failed:', key.error);
148
- * }
149
- * ```
150
- */
151
- export async function reconstructKeyFromBackup(shares) {
152
- if (shares.length === 0) {
153
- return err('INSUFFICIENT_SHARES');
154
- }
155
- const threshold = shares[0].threshold;
156
- const total = shares[0].total;
157
- if (shares.length < threshold) {
158
- return err('INSUFFICIENT_SHARES');
159
- }
160
- // Use first `threshold` shares
161
- const usedShares = shares.slice(0, threshold);
162
- // Decode share data
163
- let shareData;
164
- try {
165
- shareData = usedShares.map((s) => fromBase64(s.data));
166
- }
167
- catch {
168
- return err('INVALID_SHARE_DATA');
169
- }
170
- const indices = usedShares.map((s) => s.index);
171
- // Reconstruct padded key
172
- let padded;
173
- try {
174
- padded = reconstructXorIDA(shareData, indices, total, threshold);
175
- }
176
- catch {
177
- return err('RECONSTRUCT_FAILED');
178
- }
179
- // Verify HMAC
180
- let hmacKey;
181
- let hmacSig;
182
- try {
183
- hmacKey = fromBase64(usedShares[0].hmacKey);
184
- hmacSig = fromBase64(usedShares[0].hmacSig);
185
- }
186
- catch {
187
- return err('INVALID_SHARE_DATA');
188
- }
189
- const hmacValid = await verifyHMAC(hmacKey, padded, hmacSig);
190
- if (!hmacValid) {
191
- return err('HMAC_VERIFICATION_FAILED');
192
- }
193
- // Unpad to recover original key
194
- const p = nextOddPrime(total);
195
- const blockSize = p - 1;
196
- const unpadResult = pkcs7Unpad(padded, blockSize);
197
- if (!unpadResult.ok) {
198
- return err('RECONSTRUCT_FAILED');
199
- }
200
- return ok(unpadResult.value);
201
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{splitXorIDA,reconstructXorIDA,nextOddPrime,pkcs7Pad,pkcs7Unpad,generateHMAC,verifyHMAC,toBase64,fromBase64}from"./crypto-utils.js";export const DEFAULT_BACKUP_CONFIG={threshold:2,totalShares:3};export function validateBackupConfig(r){return r.threshold<2||r.totalShares<r.threshold||r.totalShares>255?err("INVALID_CONFIG"):ok(void 0)}export async function splitKeyWithBackup(r,t=DEFAULT_BACKUP_CONFIG){const e=validateBackupConfig(t);if(!e.ok)return e;if(0===r.length)return err("INVALID_KEY_LENGTH");const o=t.totalShares,a=t.threshold,n=nextOddPrime(o),s=pkcs7Pad(r,n-1),{key:c,signature:i}=await generateHMAC(s),A=toBase64(c),h=toBase64(i);let I;try{I=splitXorIDA(s,o,a)}catch{return err("SPLIT_FAILED")}const d=I.map((r,t)=>({index:t,data:toBase64(r),total:o,threshold:a,hmacKey:A,hmacSig:h}));return ok(d)}export async function reconstructKeyFromBackup(r){if(0===r.length)return err("INSUFFICIENT_SHARES");const t=r[0].threshold,e=r[0].total;if(r.length<t)return err("INSUFFICIENT_SHARES");const o=r.slice(0,t);let a;try{a=o.map(r=>fromBase64(r.data))}catch{return err("INVALID_SHARE_DATA")}const n=o.map(r=>r.index);let s,c,i;try{s=reconstructXorIDA(a,n,e,t)}catch{return err("RECONSTRUCT_FAILED")}try{c=fromBase64(o[0].hmacKey),i=fromBase64(o[0].hmacSig)}catch{return err("INVALID_SHARE_DATA")}if(!await verifyHMAC(c,s,i))return err("HMAC_VERIFICATION_FAILED");const A=nextOddPrime(e),h=pkcs7Unpad(s,A-1);return h.ok?ok(h.value):err("RECONSTRUCT_FAILED")}