@private.me/xbind 1.3.5 → 2.3.4

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,1545 +1 @@
1
- import { ok, err } from"./_deps/shared/index.js";
2
- import { fromBase64, toBase64, splitXorIDA, reconstructXorIDA, nextOddPrime, pkcs7Pad, pkcs7Unpad, generateHMAC, verifyHMAC, generateUUID, formatShareHeader, parseShareHeader, } from"./_deps/crypto/index.js";
3
- import { generateIdentity, verify, importPublicKey, identityFromSeed, exportPKCS8, exportX25519PKCS8, extractRawEd25519, extractRawX25519, } from './identity.js';
4
- import { createEnvelope, createEnvelopeV2, createEnvelopeV3, createEnvelopeV4, decryptPayload, validateEnvelope, generateSharedKey, } from './envelope.js';
5
- import { generateXchangeKey, xchangeEncrypt, xchangeDecrypt } from"./_deps/xchange/index.js";
6
- import { verifyMlDsa65 } from './identity.js';
7
- import { senderKeyAgreement, receiverKeyAgreement, senderHybridKeyAgreement, receiverHybridKeyAgreement, importX25519PublicKey, } from './key-agreement.js';
8
- import { splitForChannel, reconstructFromChannel, DEFAULT_SPLIT_CONFIG, } from './split-channel.js';
9
- import { MemoryNonceStore } from './nonce-store.js';
10
- import { HttpsTransportAdapter } from './transport.js';
11
- import { MemoryTrustRegistry, HttpTrustRegistry } from './trust-registry.js';
12
- import { ProgressReporter } from"./_deps/ux-helpers/index.js";
13
- import { DefaultSecurityPolicy, describeSecurityMode } from './security-policy.js';
14
- import { DEFAULT_BACKUP_CONFIG } from './backup-config.js';
15
- /* ── Configuration ── */
16
- /**
17
- * Default relay URL for message transport.
18
- * Override via XBIND_RELAY_URL environment variable.
19
- */
20
- const DEFAULT_RELAY_URL = process.env.XBIND_RELAY_URL || 'https://private.me/relay';
21
- /**
22
- * Default registry URL for DID resolution.
23
- * Override via XBIND_REGISTRY_URL environment variable.
24
- */
25
- const DEFAULT_REGISTRY_URL = process.env.XBIND_REGISTRY_URL || 'https://private.me/registry';
26
- /**
27
- * Parse an AgentError string into structured detail.
28
- *
29
- * Splits colon-separated error codes into base code and sub-code.
30
- *
31
- * @param error - An AgentError string (e.g. 'DECRYPT_FAILED:KEY_AGREEMENT').
32
- * @returns Parsed error detail.
33
- */
34
- export function parseAgentError(error) {
35
- const parts = error.split(':');
36
- if (parts.length === 1)
37
- return { code: parts[0] ?? error };
38
- return { code: parts[0] ?? error, subCode: parts.slice(1).join(':') };
39
- }
40
- const TIMESTAMP_WINDOW_MS = 30_000;
41
- /* ── Key Agreement ── */
42
- /** Copy Uint8Array to fresh ArrayBuffer. */
43
- function toArrayBuffer(data) {
44
- const buf = new ArrayBuffer(data.byteLength);
45
- new Uint8Array(buf).set(data);
46
- return buf;
47
- }
48
- // SECURITY FIX (v1.1.6): deriveSharedKey() REMOVED
49
- //
50
- // Previous implementation derived AES-256-GCM keys from public-only inputs:
51
- // AES key = SHA-256(sort(pubA, pubB))
52
- //
53
- // Both public keys appear in the envelope (sender/recipient DIDs). Any passive
54
- // observer can derive the same key and decrypt all messages. Zero forward secrecy.
55
- //
56
- // Fix: All senders/receivers MUST use X25519 ECDH for proper key agreement.
57
- // Recipients without x25519 keys fail with KEY_AGREEMENT_FAILED:RECIPIENT_HAS_NO_X25519_KEY.
58
- //
59
- // Removed: deriveSharedKey() function and export (agent.ts:2305)
60
- // Removed: Sender fallback at line 959
61
- // Removed: Receiver fallbacks at lines 1036, 2209
62
- function compareBytes(a, b) {
63
- const len = Math.min(a.length, b.length);
64
- for (let i = 0; i < len; i++) {
65
- const ai = a[i] ?? 0;
66
- const bi = b[i] ?? 0;
67
- if (ai !== bi)
68
- return ai - bi;
69
- }
70
- return a.length - b.length;
71
- }
72
- function concatBytes(a, b) {
73
- const result = new Uint8Array(a.length + b.length);
74
- result.set(a);
75
- result.set(b, a.length);
76
- return result;
77
- }
78
- /* ── Agent Class ── */
79
- /**
80
- * Top-level Xail Agent SDK API.
81
- *
82
- * Matches xail.io/sdk specification:
83
- * - Agent.create({ name, registry }) — generate identity + register
84
- * - agent.send({ to, payload, scope }) — encrypt, sign, deliver
85
- * - agent.receive(envelope) — verify, decrypt, return message
86
- */
87
- export class Agent {
88
- identity;
89
- name;
90
- registry;
91
- transports;
92
- nonceStore;
93
- timestampWindowMs;
94
- securityPolicy;
95
- backupConfig;
96
- /** Accumulates split-channel shares by groupId until threshold is met. */
97
- shareAccumulator = new Map();
98
- /** Diagnostic detail from the last failed verification step. */
99
- lastDetail = '';
100
- /** Last security decision made by the policy (for debugging/logging). */
101
- lastSecurityDecision;
102
- /** Timer for ephemeral agent auto-cleanup. */
103
- cleanupTimer;
104
- /**
105
- * Human-readable diagnostic from the last failed receive/verify call.
106
- *
107
- * Populated during verification with context like age vs max window.
108
- * Empty string if no error has occurred or after a successful call.
109
- */
110
- get lastErrorDetail() {
111
- return this.lastDetail;
112
- }
113
- /**
114
- * Last security decision made by the security policy.
115
- *
116
- * Shows which security mode was selected and why. Useful for debugging
117
- * and understanding when/why Xorida split-channel was activated.
118
- *
119
- * Returns undefined if no send() has been called yet.
120
- */
121
- get lastSecurity() {
122
- return this.lastSecurityDecision;
123
- }
124
- constructor(identity, name, registry, transports, nonceStore, timestampWindowMs, securityPolicy, backupConfig) {
125
- this.identity = identity;
126
- this.name = name;
127
- this.registry = registry;
128
- this.transports = transports;
129
- this.nonceStore = nonceStore;
130
- this.timestampWindowMs = timestampWindowMs;
131
- this.securityPolicy = securityPolicy ?? new DefaultSecurityPolicy();
132
- this.backupConfig = backupConfig ?? DEFAULT_BACKUP_CONFIG;
133
- }
134
- /** The agent's DID. */
135
- get did() {
136
- return this.identity.did;
137
- }
138
- /**
139
- * Check whether the runtime supports the SDK's crypto requirements.
140
- *
141
- * Verifies that `crypto.subtle` is available and supports Ed25519 +
142
- * AES-256-GCM. Call this before lazy-loading the SDK in middleware
143
- * to avoid failing on the first `Agent.create()` call.
144
- *
145
- * @returns `true` if the runtime has the required Web Crypto APIs.
146
- */
147
- static isSupported() {
148
- try {
149
- return (typeof globalThis.crypto !== 'undefined' &&
150
- typeof globalThis.crypto.subtle !== 'undefined' &&
151
- typeof globalThis.crypto.subtle.generateKey === 'function' &&
152
- typeof globalThis.crypto.subtle.sign === 'function' &&
153
- typeof globalThis.crypto.subtle.verify === 'function' &&
154
- typeof globalThis.crypto.subtle.encrypt === 'function' &&
155
- typeof globalThis.crypto.getRandomValues === 'function');
156
- }
157
- catch {
158
- return false;
159
- }
160
- }
161
- /**
162
- * Create an Agent from a persisted identity (skips keygen + registration).
163
- *
164
- * Use this with importFromPKCS8 or importIdentity to restore a
165
- * previously created agent across process restarts.
166
- *
167
- * @param identity - A previously exported AgentIdentity.
168
- * @param opts - Agent options (registry, transport, etc.).
169
- * @returns Agent instance or error.
170
- */
171
- static async fromIdentity(identity, opts) {
172
- const nonceStore = opts.nonceStore ?? new MemoryNonceStore();
173
- const timestampWindowMs = opts.timestampWindowMs ?? TIMESTAMP_WINDOW_MS;
174
- const transports = Array.isArray(opts.transport) ? opts.transport : [opts.transport];
175
- const agent = new Agent(identity, opts.name ?? identity.did, opts.registry, transports, nonceStore, timestampWindowMs, opts.securityPolicy, opts.backupConfig);
176
- return ok(agent);
177
- }
178
- /**
179
- * Build an Agent from pre-constructed parts (synchronous).
180
- *
181
- * Unlike `create()` this does NOT generate keys or register with the
182
- * registry — the caller is responsible for both. Useful when identity
183
- * is provisioned in a factory step, registration is handled by an
184
- * external system, or transport is wired up at runtime.
185
- *
186
- * @param identity - A previously generated or imported AgentIdentity.
187
- * @param registry - Trust registry the agent will query for peers.
188
- * @param transport - Transport adapter for envelope delivery.
189
- * @param opts - Optional overrides (name, nonceStore, timestampWindowMs).
190
- * @returns A fully wired Agent instance.
191
- */
192
- static fromParts(identity, registry, transport, opts) {
193
- const transports = Array.isArray(transport) ? transport : [transport];
194
- return new Agent(identity, opts?.name ?? identity.did, registry, transports, opts?.nonceStore ?? new MemoryNonceStore(), opts?.timestampWindowMs ?? TIMESTAMP_WINDOW_MS, opts?.securityPolicy, opts?.backupConfig);
195
- }
196
- /**
197
- * Create an Agent from a deterministic 32-byte seed.
198
- *
199
- * Uses HKDF-SHA256 to derive Ed25519 + X25519 keys from the seed.
200
- * The same seed always produces the same DID and keys.
201
- *
202
- * **Just-in-Time Registration (JITR):** Automatically registers identity
203
- * with the trust registry on first use. Follows industry standards (AWS IoT
204
- * JITR, OAuth DCR, MCP 2025 spec) for zero-config onboarding. Idempotent:
205
- * safe to call multiple times (ignores ALREADY_REGISTERED errors).
206
- *
207
- * Ideal for IoT, servers, AI agents: zero-config deployment with automatic
208
- * registration on first connection.
209
- *
210
- * @param seed - Exactly 32 bytes of high-entropy key material.
211
- * @param opts - Agent options (registry, transport, scopes, etc.).
212
- * @returns Agent instance or error.
213
- */
214
- static async fromSeed(seed, opts) {
215
- const idResult = await identityFromSeed(seed, { postQuantumSig: opts.postQuantumSig });
216
- if (!idResult.ok)
217
- return err('IDENTITY_FAILED:KEYGEN');
218
- // JITR: Auto-register with trust registry (zero-config onboarding)
219
- // Includes all keys: Ed25519 (signing), X25519 (encryption), ML-KEM, ML-DSA
220
- const regResult = await opts.registry.register(idResult.value.did, idResult.value.rawPublicKey, opts.name ?? idResult.value.did, opts.scopes, idResult.value.rawX25519PublicKey, idResult.value.mlKemPublicKey, idResult.value.mlDsaPublicKey, opts.xchange ?? false);
221
- // Idempotent: Ignore ALREADY_REGISTERED (agent may have registered before)
222
- // Fail on other errors (network issues, invalid data, etc.)
223
- if (!regResult.ok && regResult.error !== 'ALREADY_REGISTERED') {
224
- const sub = regResult.error === 'NETWORK_ERROR'
225
- ? 'REGISTRATION_FAILED:NETWORK_ERROR'
226
- : 'REGISTRATION_FAILED';
227
- return err(sub);
228
- }
229
- const nonceStore = opts.nonceStore ?? new MemoryNonceStore();
230
- const timestampWindowMs = opts.timestampWindowMs ?? TIMESTAMP_WINDOW_MS;
231
- const transports = Array.isArray(opts.transport) ? opts.transport : [opts.transport];
232
- return ok(new Agent(idResult.value, opts.name ?? idResult.value.did, opts.registry, transports, nonceStore, timestampWindowMs, opts.securityPolicy, opts.backupConfig));
233
- }
234
- /**
235
- * Create a lazy agent that initializes on first use (zero-click onboarding).
236
- *
237
- * Defers invite acceptance and identity generation until first send/receive.
238
- * Reads invite code from XBIND_INVITE_CODE environment variable.
239
- * Auto-accepts invite and configures registry/transport automatically.
240
- *
241
- * @param config - Lazy agent configuration (name required).
242
- * @returns Lazy agent wrapper (synchronous).
243
- *
244
- * @example
245
- * ```ts
246
- * // Environment: XBIND_INVITE_CODE=XBD-abc123, XBIND_AUTO_ACCEPT=true
247
- *
248
- * // Synchronous construction (no await):
249
- * const agent = Agent.lazy({ name: 'my-service' });
250
- *
251
- * // Auto-accept happens on first send/receive:
252
- * await agent.send({
253
- * to: 'did:key:z6Mk...',
254
- * payload: { action: 'test' },
255
- * scope: 'test',
256
- * });
257
- * ```
258
- */
259
- static async lazy(config) {
260
- // Dynamic import avoids circular dependency
261
- const { createLazyAgent } = await import('./lazy-init.js');
262
- return createLazyAgent(config);
263
- }
264
- /**
265
- * Check whether this agent is fully initialized and ready to send/receive.
266
- *
267
- * Returns `true` if identity, registry, and transport are all present.
268
- * Construction always produces a ready agent (invalid inputs cause the
269
- * factory to return an error instead), so this is primarily useful in
270
- * middleware that lazily initializes agents and needs a guard.
271
- *
272
- * @returns `true` if the agent can send and receive messages.
273
- */
274
- isReady() {
275
- return (this.identity !== undefined &&
276
- this.registry !== undefined &&
277
- this.transports.length > 0);
278
- }
279
- /** Create a new agent, generate identity, register with trust registry. */
280
- static async create(opts) {
281
- const idResult = await generateIdentity({ postQuantumSig: opts.postQuantumSig });
282
- if (!idResult.ok)
283
- return err('IDENTITY_FAILED:KEYGEN');
284
- const regResult = await opts.registry.register(idResult.value.did, idResult.value.rawPublicKey, opts.name, opts.scopes, idResult.value.rawX25519PublicKey, idResult.value.mlKemPublicKey, idResult.value.mlDsaPublicKey, opts.xchange ?? false);
285
- if (!regResult.ok) {
286
- const sub = regResult.error === 'ALREADY_REGISTERED'
287
- ? 'REGISTRATION_FAILED:ALREADY_REGISTERED'
288
- : regResult.error === 'NETWORK_ERROR'
289
- ? 'REGISTRATION_FAILED:NETWORK_ERROR'
290
- : 'REGISTRATION_FAILED';
291
- return err(sub);
292
- }
293
- const nonceStore = opts.nonceStore ?? new MemoryNonceStore();
294
- const timestampWindowMs = opts.timestampWindowMs ?? TIMESTAMP_WINDOW_MS;
295
- const transports = Array.isArray(opts.transport) ? opts.transport : [opts.transport];
296
- const agent = new Agent(idResult.value, opts.name, opts.registry, transports, nonceStore, timestampWindowMs, opts.securityPolicy, opts.backupConfig);
297
- return ok(agent);
298
- }
299
- /**
300
- * Quickstart: create an agent with zero configuration.
301
- *
302
- * Creates an ephemeral agent with auto-cleanup after 1 hour. No policy
303
- * restrictions by default (allow all operations). Ideal for getting
304
- * started, prototyping, and simple use cases.
305
- *
306
- * Uses in-memory registry and default transport. Identity auto-expires
307
- * and is deregistered after TTL.
308
- *
309
- * @param opts - Optional configuration (name only)
310
- * @returns Agent instance (throws on error for simpler API)
311
- *
312
- * @example
313
- * ```ts
314
- * // Zero config (ephemeral identity, 1-hour TTL):
315
- * const agent = await Agent.quickstart();
316
- *
317
- * // With custom name:
318
- * const agent = await Agent.quickstart({ name: 'my-service' });
319
- *
320
- * // Agent is ready to use immediately:
321
- * await agent.send({
322
- * to: 'did:key:z6Mk...',
323
- * payload: { action: 'test' },
324
- * scope: 'test',
325
- * });
326
- * ```
327
- */
328
- static async quickstart(opts) {
329
- // Use in-memory registry for ephemeral agents
330
- const registry = new MemoryTrustRegistry();
331
- // Use default transport
332
- const transport = new HttpsTransportAdapter({
333
- baseUrl: DEFAULT_RELAY_URL,
334
- });
335
- // Generate ephemeral identity (1-hour TTL)
336
- const idResult = await generateIdentity({ postQuantumSig: false });
337
- if (!idResult.ok) {
338
- throw new Error('Failed to generate ephemeral identity');
339
- }
340
- // Auto-generate name if not provided
341
- const name = opts?.name ?? `agent-${Date.now()}`;
342
- // Register ephemeral identity
343
- const regResult = await registry.register(idResult.value.did, idResult.value.rawPublicKey, name, undefined, // scopes - no restrictions (allow all)
344
- idResult.value.rawX25519PublicKey, idResult.value.mlKemPublicKey, idResult.value.mlDsaPublicKey, false);
345
- if (!regResult.ok) {
346
- throw new Error(`Failed to register ephemeral identity: ${regResult.error}`);
347
- }
348
- // Create agent instance
349
- const agent = new Agent(idResult.value, name, registry, [transport], new MemoryNonceStore(), TIMESTAMP_WINDOW_MS, undefined, // No policy restrictions (allow all)
350
- undefined);
351
- // Auto-cleanup after 1 hour (ephemeral identity)
352
- const TTL_MS = 3600000; // 1 hour
353
- agent.cleanupTimer = setTimeout(async () => {
354
- await registry.revoke(idResult.value.did);
355
- // Ephemeral agent auto-revoked after TTL (no logging to avoid production noise)
356
- }, TTL_MS);
357
- return agent;
358
- }
359
- /**
360
- * Create agent from simplified options (async factory).
361
- *
362
- * This is the async-safe way to construct agents with AgentOptions.
363
- *
364
- * @param options - Agent configuration
365
- * @returns Agent instance
366
- *
367
- * @example
368
- * ```typescript
369
- * import { Agent } from '@private.me/xbind';
370
- *
371
- * // Ephemeral agent (auto-cleanup after 1 hour)
372
- * const agent = await Agent.from({
373
- * identity: 'ephemeral',
374
- * identityTTL: 3600, // seconds
375
- * });
376
- *
377
- * // Use the agent
378
- * await agent.send({ to, payload, scope: 'read' });
379
- * ```
380
- */
381
- static async from(options = {}) {
382
- const identity = options.identity ?? 'persistent';
383
- const identityTTL = options.identityTTL ?? 3600000; // 1 hour default (ms)
384
- const isEphemeral = identity === 'ephemeral';
385
- // Resolve registry
386
- const registry = typeof options.registry === 'string'
387
- ? new HttpTrustRegistry({ baseUrl: options.registry })
388
- : options.registry ?? (isEphemeral ? new MemoryTrustRegistry() : new HttpTrustRegistry({ baseUrl: DEFAULT_REGISTRY_URL }));
389
- // Resolve transport
390
- const transports = options.transport
391
- ? Array.isArray(options.transport)
392
- ? options.transport
393
- : [options.transport]
394
- : [new HttpsTransportAdapter({ baseUrl: DEFAULT_RELAY_URL })];
395
- // Generate identity
396
- const idResult = await generateIdentity({
397
- postQuantumSig: options.postQuantumSig ?? false,
398
- });
399
- if (!idResult.ok) {
400
- throw new Error('Failed to generate identity');
401
- }
402
- // Register identity (ephemeral agents use auto-generated names)
403
- const name = isEphemeral
404
- ? `ephemeral-agent-${Date.now()}`
405
- : `agent-${Date.now()}`;
406
- const regResult = await registry.register(idResult.value.did, idResult.value.rawPublicKey, name, undefined, // scopes
407
- idResult.value.rawX25519PublicKey, idResult.value.mlKemPublicKey, idResult.value.mlDsaPublicKey, false);
408
- if (!regResult.ok) {
409
- throw new Error(`Failed to register identity: ${regResult.error}`);
410
- }
411
- // Create agent instance
412
- const agent = new Agent(idResult.value, name, registry, transports, new MemoryNonceStore(), TIMESTAMP_WINDOW_MS, options.securityPolicy, options.backupConfig);
413
- // Setup TTL cleanup for ephemeral identities
414
- if (isEphemeral) {
415
- agent.cleanupTimer = setTimeout(async () => {
416
- // Auto-deregister after TTL expires
417
- await registry.revoke(idResult.value.did);
418
- }, identityTTL);
419
- }
420
- return agent;
421
- }
422
- /** Send a message to a recipient. */
423
- async send(opts) {
424
- const progress = new ProgressReporter(opts.onProgress);
425
- progress.start('Resolving recipient identity...');
426
- const recipientKey = await this.registry.resolve(opts.to);
427
- if (!recipientKey.ok) {
428
- return err(recipientKey.error === 'REVOKED'
429
- ? 'RECIPIENT_REVOKED'
430
- : 'RECIPIENT_NOT_FOUND');
431
- }
432
- // Bilateral authorization: check if recipient accepts this scope
433
- progress.update('Checking recipient authorization...', 10);
434
- const receiverAccepts = await this.registry.hasReceiveScope(opts.to, opts.scope);
435
- if (!receiverAccepts) {
436
- this.lastDetail = `recipient=${opts.to}, scope=${opts.scope}`;
437
- return err('RECEIVER_SCOPE_DENIED');
438
- }
439
- progress.update('Preparing message...', 15);
440
- const plaintext = new TextEncoder().encode(JSON.stringify(opts.payload));
441
- // Security policy: classify action risk and determine security mode
442
- progress.update('Determining security level...', 20);
443
- const securityDecision = this.securityPolicy.classify({
444
- action: opts.action ?? 'send',
445
- params: typeof opts.payload === 'object' && opts.payload !== null
446
- ? opts.payload
447
- : {},
448
- sender: this.did,
449
- recipient: opts.to,
450
- scope: opts.scope,
451
- securityOverride: opts.security,
452
- });
453
- this.lastSecurityDecision = securityDecision;
454
- // Log security decision for transparency
455
- progress.update(`Security: ${describeSecurityMode(securityDecision.mode)} — ${securityDecision.reason}`, 25);
456
- // Determine whether to use split-channel based on policy decision
457
- // Backward compatibility: explicit splitChannel flag overrides policy
458
- const shouldUseSplitChannel = opts.splitChannel !== undefined
459
- ? opts.splitChannel
460
- : securityDecision.mode.type === 'split';
461
- // Xchange: opt-in via xchange: true on send or policy decision. Faster (single security layer) but
462
- // trades per-share encryption and KEM for ~180x speed. Falls back to V3 if
463
- // recipient doesn't support Xchange.
464
- if (shouldUseSplitChannel && (opts.xchange || securityDecision.mode.type === 'xchange')) {
465
- progress.update('Checking Xchange support...', 20);
466
- const canXchange = await this.canUseXchange(opts.to);
467
- if (canXchange) {
468
- return this.sendXchange(opts, plaintext, progress);
469
- }
470
- // Fall back to V3 split-channel if recipient doesn't support Xchange
471
- }
472
- progress.update('Establishing key agreement...', 30);
473
- const ecdhResult = await this.trySenderECDH(opts.to);
474
- if (ecdhResult) {
475
- if (shouldUseSplitChannel) {
476
- return this.sendSplitChannel(opts, plaintext, ecdhResult.sharedKey, ecdhResult.ephemeralPublicKey, ecdhResult.kemCiphertext, ecdhResult.recipientHasMlDsa, progress);
477
- }
478
- // V3: both sides have ML-DSA + hybrid KEM
479
- if (ecdhResult.kemCiphertext && ecdhResult.recipientHasMlDsa && this.identity.mlDsaSecretKey) {
480
- return this.sendWithHybridV3(opts, plaintext, ecdhResult.sharedKey, ecdhResult.ephemeralPublicKey, ecdhResult.kemCiphertext, progress);
481
- }
482
- if (ecdhResult.kemCiphertext) {
483
- return this.sendWithHybrid(opts, plaintext, ecdhResult.sharedKey, ecdhResult.ephemeralPublicKey, ecdhResult.kemCiphertext, progress);
484
- }
485
- return this.sendWithECDH(opts, plaintext, ecdhResult.sharedKey, ecdhResult.ephemeralPublicKey, progress);
486
- }
487
- // SECURITY FIX (v1.1.6): Removed insecure fallback to deriveSharedKey()
488
- // Recipient must have x25519 public key registered for secure ECDH key agreement
489
- return err('KEY_AGREEMENT_FAILED:RECIPIENT_HAS_NO_X25519_KEY');
490
- }
491
- /**
492
- * Verify and decrypt an incoming encrypted envelope (v1 or v2).
493
- *
494
- * @param envelope - Incoming transport envelope.
495
- * @param opts - Optional receive options (e.g. allowCleartext).
496
- */
497
- async receive(envelope, opts) {
498
- this.lastDetail = '';
499
- const progress = new ProgressReporter(opts?.onProgress);
500
- progress.start('Verifying envelope signature...');
501
- const verified = await this.verifyEnvelope(envelope);
502
- if (!verified.ok)
503
- return verified;
504
- const { senderRawKey, payloadBytes } = verified.value;
505
- let sharedKey;
506
- // V4 Xchange: use receiveXchangeShare() instead
507
- if (envelope.v === 4) {
508
- return err('VERIFICATION_FAILED:UNSUPPORTED_VERSION');
509
- }
510
- progress.update('Deriving shared key...', 30);
511
- // V2/V3 hybrid path: use X25519 + ML-KEM-768
512
- if ((envelope.v === 2 || envelope.v === 3) && 'kemCiphertext' in envelope) {
513
- if (!this.identity.mlKemSecretKey) {
514
- return err('DECRYPT_FAILED:KEY_AGREEMENT');
515
- }
516
- // Type guards to prevent crashes on malformed envelopes
517
- if (typeof envelope.ephemeralPub !== 'string' || typeof envelope.kemCiphertext !== 'string') {
518
- this.lastDetail = 'ephemeralPub or kemCiphertext not string';
519
- return err('VERIFICATION_FAILED:INVALID_ENVELOPE');
520
- }
521
- const ephPubBytes = fromBase64(envelope.ephemeralPub);
522
- const kemCtBytes = fromBase64(envelope.kemCiphertext);
523
- const hybridKey = await receiverHybridKeyAgreement(this.identity.x25519PrivateKey, ephPubBytes, kemCtBytes, this.identity.mlKemSecretKey);
524
- if (!hybridKey.ok)
525
- return err('DECRYPT_FAILED:KEY_AGREEMENT');
526
- sharedKey = hybridKey.value;
527
- }
528
- else if (envelope.ephemeralPub) {
529
- // V1 with ECDH forward secrecy
530
- if (typeof envelope.ephemeralPub !== 'string') {
531
- this.lastDetail = 'ephemeralPub not string';
532
- return err('VERIFICATION_FAILED:INVALID_ENVELOPE');
533
- }
534
- const ephPubBytes = fromBase64(envelope.ephemeralPub);
535
- const ecdhKey = await receiverKeyAgreement(this.identity.x25519PrivateKey, ephPubBytes);
536
- if (!ecdhKey.ok)
537
- return err('DECRYPT_FAILED:KEY_AGREEMENT');
538
- sharedKey = ecdhKey.value;
539
- }
540
- else {
541
- // SECURITY FIX (v1.1.6): Removed insecure V1 SHA-256 fallback
542
- // Envelopes without ephemeralPub are rejected (sender must use X25519 ECDH)
543
- return err('DECRYPT_FAILED:NO_EPHEMERAL_KEY');
544
- }
545
- progress.update('Decrypting payload...', 60);
546
- const decrypted = await decryptPayload(envelope, sharedKey);
547
- if (!decrypted.ok) {
548
- if (opts?.allowCleartext) {
549
- let payload;
550
- try {
551
- payload = JSON.parse(new TextDecoder().decode(payloadBytes));
552
- }
553
- catch {
554
- return err('DECRYPT_FAILED:PARSE');
555
- }
556
- progress.complete();
557
- return ok({
558
- sender: envelope.sender,
559
- payload,
560
- scope: envelope.scope,
561
- timestamp: envelope.timestamp,
562
- });
563
- }
564
- return err('DECRYPT_FAILED:DECRYPTION');
565
- }
566
- progress.update('Parsing message...', 90);
567
- let payload;
568
- try {
569
- payload = JSON.parse(new TextDecoder().decode(decrypted.value));
570
- }
571
- catch {
572
- return err('DECRYPT_FAILED:PARSE');
573
- }
574
- progress.complete();
575
- // Mechanism 2: Protocol information available in metadata for applications to display
576
- // Applications can show this to users if needed (envelope.protocol, envelope.documentationUrl)
577
- return ok({
578
- sender: envelope.sender,
579
- payload,
580
- scope: envelope.scope,
581
- timestamp: envelope.timestamp,
582
- metadata: envelope.protocol && envelope.documentationUrl
583
- ? {
584
- protocol: envelope.protocol,
585
- documentationUrl: envelope.documentationUrl,
586
- }
587
- : undefined,
588
- });
589
- }
590
- /**
591
- * Verify only the signature on an envelope without consuming the nonce.
592
- *
593
- * Does NOT check timestamp, nonce, or scope. Use this for pre-screening
594
- * or audit logging where you need to confirm the sender but don't want
595
- * to consume replay-prevention state.
596
- *
597
- * @param envelope - The envelope to verify.
598
- * @returns `{ sender, valid }` or error if the DID cannot be resolved.
599
- */
600
- async verifySignature(envelope) {
601
- const senderKey = await this.registry.resolve(envelope.sender);
602
- if (!senderKey.ok)
603
- return err('VERIFICATION_FAILED:DID_NOT_IN_REGISTRY');
604
- const pubKey = await importPublicKey(senderKey.value);
605
- if (!pubKey.ok)
606
- return err('VERIFICATION_FAILED:KEY_IMPORT_FAILED');
607
- const sigBytes = fromBase64(envelope.signature);
608
- // SECURITY FIX (v1.1.3): Verify canonical representation (not just payload)
609
- const canonicalData = JSON.stringify({
610
- v: envelope.v,
611
- alg: envelope.alg,
612
- sender: envelope.sender,
613
- recipient: envelope.recipient,
614
- timestamp: envelope.timestamp,
615
- nonce: envelope.nonce,
616
- scope: envelope.scope,
617
- payload: envelope.payload,
618
- });
619
- const canonicalBytes = new TextEncoder().encode(canonicalData);
620
- const sigValid = await verify(pubKey.value, sigBytes, canonicalBytes);
621
- if (!sigValid.ok)
622
- return err('VERIFICATION_FAILED:SIGNATURE_MISMATCH');
623
- return ok({ sender: envelope.sender, valid: sigValid.value });
624
- }
625
- /**
626
- * Export the raw 32-byte private key seeds for both Ed25519 and X25519.
627
- *
628
- * These are the raw private key bytes extracted from PKCS8, NOT the
629
- * original HKDF seed (that derivation is one-way). Use these for
630
- * persistence or cross-device transfer.
631
- *
632
- * @returns Two 32-byte Uint8Arrays or error.
633
- */
634
- async exportSeeds() {
635
- const edPkcs8 = await exportPKCS8(this.identity.privateKey);
636
- if (!edPkcs8.ok)
637
- return err('IDENTITY_FAILED');
638
- const x25519Pkcs8 = await exportX25519PKCS8(this.identity.x25519PrivateKey);
639
- if (!x25519Pkcs8.ok)
640
- return err('IDENTITY_FAILED');
641
- const edRaw = extractRawEd25519(edPkcs8.value);
642
- if (!edRaw.ok)
643
- return err('IDENTITY_FAILED');
644
- const x25519Raw = extractRawX25519(x25519Pkcs8.value);
645
- if (!x25519Raw.ok)
646
- return err('IDENTITY_FAILED');
647
- return ok({
648
- ed25519: edRaw.value,
649
- x25519: x25519Raw.value,
650
- mlKemSecretKey: this.identity.mlKemSecretKey,
651
- mlKemPublicKey: this.identity.mlKemPublicKey,
652
- });
653
- }
654
- /**
655
- * Split a cryptographic key into backup shares using XorIDA.
656
- *
657
- * Uses the agent's backup configuration (default: k=2, n=3).
658
- * Any `threshold` shares can reconstruct the original key.
659
- * Each share reveals zero information (information-theoretic security).
660
- *
661
- * @param key - The key to split (32 or 64 bytes typical).
662
- * @returns Array of backup shares or error.
663
- *
664
- * @example
665
- * ```typescript
666
- * // Generate a key and split it
667
- * const key = crypto.getRandomValues(new Uint8Array(32));
668
- * const shares = await agent.splitKey(key);
669
- *
670
- * if (shares.ok) {
671
- * // Store shares in separate locations
672
- * shares.value.forEach((share, i) => {
673
- * storeShare(`backup-${i}.json`, JSON.stringify(share));
674
- * });
675
- * }
676
- * ```
677
- */
678
- async splitKey(key) {
679
- // Dynamic import avoids circular dependency
680
- const { splitKeyWithBackup } = await import('./backup-config.js');
681
- const result = await splitKeyWithBackup(key, this.backupConfig);
682
- if (!result.ok) {
683
- return err('ENVELOPE_FAILED:SPLIT');
684
- }
685
- return result;
686
- }
687
- /**
688
- * Reconstruct a cryptographic key from backup shares.
689
- *
690
- * Requires at least `threshold` shares. Verifies HMAC before returning
691
- * the reconstructed key to prevent tampering.
692
- *
693
- * @param shares - Backup shares (must be >= threshold).
694
- * @returns Reconstructed key or error.
695
- *
696
- * @example
697
- * ```typescript
698
- * // Load shares from storage
699
- * const share0 = JSON.parse(loadShare('backup-0.json'));
700
- * const share1 = JSON.parse(loadShare('backup-1.json'));
701
- *
702
- * // Reconstruct from any 2 shares (threshold=2)
703
- * const key = await agent.reconstructKey([share0, share1]);
704
- *
705
- * if (key.ok) {
706
- * // Use reconstructed key
707
- * console.log('Key recovered:', key.value);
708
- * }
709
- * ```
710
- */
711
- async reconstructKey(shares) {
712
- // Dynamic import avoids circular dependency
713
- const { reconstructKeyFromBackup } = await import('./backup-config.js');
714
- const result = await reconstructKeyFromBackup(shares);
715
- if (!result.ok) {
716
- return err('DECRYPT_FAILED');
717
- }
718
- return result;
719
- }
720
- /**
721
- * Verify a signed (unencrypted) envelope and return the message.
722
- *
723
- * Use for envelopes created with createSignedEnvelope().
724
- * Verifies signature, timestamp, nonce, and scope — skips decryption.
725
- *
726
- * @param envelope - A signed (unencrypted) transport envelope.
727
- * @returns Verified message or error with sub-code.
728
- */
729
- async receiveSigned(envelope) {
730
- this.lastDetail = '';
731
- const verified = await this.verifyEnvelope(envelope);
732
- if (!verified.ok)
733
- return verified;
734
- let payload;
735
- try {
736
- payload = JSON.parse(new TextDecoder().decode(verified.value.payloadBytes));
737
- }
738
- catch {
739
- return err('DECRYPT_FAILED:PARSE');
740
- }
741
- // Mechanism 2: Protocol information available in metadata for applications to display
742
- // Applications can show this to users if needed (envelope.protocol, envelope.documentationUrl)
743
- return ok({
744
- sender: envelope.sender,
745
- payload,
746
- scope: envelope.scope,
747
- timestamp: envelope.timestamp,
748
- metadata: envelope.protocol && envelope.documentationUrl
749
- ? {
750
- protocol: envelope.protocol,
751
- documentationUrl: envelope.documentationUrl,
752
- }
753
- : undefined,
754
- });
755
- }
756
- /**
757
- * Discover available tools in the registry.
758
- *
759
- * Query xRegistry for tools matching the given service prefix or capability.
760
- * Returns tool metadata including name, description, schema, and trust level.
761
- *
762
- * @param service - Optional service prefix to filter by (e.g., "payments")
763
- * @returns Array of tool metadata or empty array if none found
764
- *
765
- * @example
766
- * ```typescript
767
- * import { Agent } from '@private.me/xbind';
768
- * import { ToolRegistry } from"./_deps/xregistry/index.js";
769
- * import { setToolRegistry } from '@private.me/xbind/agent-call';
770
- *
771
- * const registry = new ToolRegistry();
772
- * registry.register({
773
- * name: 'payments:createCharge',
774
- * description: 'Create a payment charge',
775
- * schema: { type: 'object', properties: { amount: { type: 'number' } } },
776
- * trustLevel: 'verified',
777
- * endpoint: 'https://api.stripe.com/v1/charges',
778
- * capabilities: ['payment', 'charge']
779
- * });
780
- *
781
- * setToolRegistry(registry);
782
- *
783
- * const agent = await Agent.quickstart();
784
- *
785
- * // Discover all payment tools
786
- * const tools = await agent.discover('payments');
787
- * console.log(tools); // [{ name: 'payments:createCharge', ... }]
788
- *
789
- * // Discover all tools
790
- * const allTools = await agent.discover();
791
- * ```
792
- */
793
- async discover(service) {
794
- // Import dynamically to avoid circular dependency
795
- // SAFETY: Dynamic import allows agent-call.ts to import agent.ts without circular reference
796
- const { getToolRegistry } = await import('./agent-call.js');
797
- const registry = getToolRegistry();
798
- if (!registry) {
799
- // No registry configured - return empty array
800
- return [];
801
- }
802
- if (!service) {
803
- // No filter - return all tools
804
- return registry.listAll();
805
- }
806
- // Filter by service prefix using registry search
807
- // Search handles name, capability, and description matching
808
- const results = registry.search(service);
809
- return results;
810
- }
811
- /** Generate an Express-compatible middleware handler. */
812
- middleware() {
813
- return async (req, res, next) => {
814
- const validated = validateEnvelope(req.body);
815
- if (!validated.ok) {
816
- res.status(400).json({ error: validated.error });
817
- return;
818
- }
819
- // SAFETY: validateEnvelope returns AnyTransportEnvelope
820
- const result = await this.receive(validated.value);
821
- if (!result.ok) {
822
- const code = result.error === 'TIMESTAMP_EXPIRED'
823
- || result.error === 'REPLAY_DETECTED'
824
- ? 403 : 401;
825
- res.status(code).json({ error: result.error });
826
- return;
827
- }
828
- req['agentMessage'] = result.value;
829
- next();
830
- };
831
- }
832
- /**
833
- * Cleanup resources (timers, handlers, etc.)
834
- *
835
- * Call this in tests or when disposing an agent to prevent timer leaks.
836
- * Clears the ephemeral identity auto-cleanup timer if present.
837
- */
838
- cleanup() {
839
- if (this.cleanupTimer) {
840
- clearTimeout(this.cleanupTimer);
841
- this.cleanupTimer = undefined;
842
- }
843
- }
844
- /**
845
- * Dispose of agent resources (alias for cleanup)
846
- *
847
- * Provided for compatibility with test cleanup patterns.
848
- */
849
- dispose() {
850
- this.cleanup();
851
- }
852
- /**
853
- * Attempt sender-side key agreement.
854
- *
855
- * If both sides support ML-KEM-768, uses hybrid (X25519 + ML-KEM-768).
856
- * Otherwise falls back to X25519-only ECDH.
857
- * Returns null if recipient has no X25519 key registered.
858
- * Also returns whether recipient supports ML-DSA-65 for v3 envelopes.
859
- */
860
- async trySenderECDH(recipientDid) {
861
- const entry = await this.registry.getEntry(recipientDid);
862
- if (!entry.ok || !entry.value.x25519PublicKey)
863
- return null;
864
- const recipientHasMlDsa = !!entry.value.mlDsaPublicKey;
865
- const recipientX25519 = await importX25519PublicKey(entry.value.x25519PublicKey);
866
- if (!recipientX25519.ok)
867
- return null;
868
- // Try hybrid if both sides have ML-KEM keys
869
- if (entry.value.mlKemPublicKey && this.identity.mlKemSecretKey) {
870
- const hybrid = await senderHybridKeyAgreement(recipientX25519.value, entry.value.mlKemPublicKey);
871
- if (hybrid.ok) {
872
- return {
873
- sharedKey: hybrid.value.sharedKey,
874
- ephemeralPublicKey: hybrid.value.ephemeralPublicKey,
875
- kemCiphertext: hybrid.value.kemCiphertext,
876
- recipientHasMlDsa,
877
- };
878
- }
879
- }
880
- // Fallback to X25519-only
881
- const result = await senderKeyAgreement(recipientX25519.value);
882
- if (!result.ok)
883
- return null;
884
- return { ...result.value, recipientHasMlDsa };
885
- }
886
- /** Send with ECDH forward secrecy (ephemeral key in envelope). */
887
- async sendWithECDH(opts, plaintext, sharedKey, ephemeralPublicKey, progress) {
888
- progress?.update('Encrypting message with ECDH...', 60);
889
- const envelope = await createEnvelope({
890
- senderDid: this.identity.did,
891
- recipientDid: opts.to,
892
- scope: opts.scope,
893
- plaintext,
894
- privateKey: this.identity.privateKey,
895
- sharedKey,
896
- ephemeralPublicKey,
897
- });
898
- if (!envelope.ok)
899
- return err('ENVELOPE_FAILED:ENCRYPT');
900
- progress?.update('Sending message...', 90);
901
- const result = await this.transports[0].send(envelope.value, opts.to);
902
- if (result.ok) {
903
- progress?.complete();
904
- }
905
- return result;
906
- }
907
- /** Send with hybrid KEM (X25519 + ML-KEM-768) via v2 envelope. */
908
- async sendWithHybrid(opts, plaintext, sharedKey, ephemeralPublicKey, kemCiphertext, progress) {
909
- progress?.update('Encrypting message with hybrid KEM...', 60);
910
- const envelope = await createEnvelopeV2({
911
- senderDid: this.identity.did,
912
- recipientDid: opts.to,
913
- scope: opts.scope,
914
- plaintext,
915
- privateKey: this.identity.privateKey,
916
- sharedKey,
917
- ephemeralPublicKey,
918
- kemCiphertext,
919
- });
920
- if (!envelope.ok)
921
- return err('ENVELOPE_FAILED:ENCRYPT');
922
- progress?.update('Sending message...', 90);
923
- // SAFETY: AnyTransportEnvelope is accepted by transport.send
924
- const result = await this.transports[0].send(envelope.value, opts.to);
925
- if (result.ok) {
926
- progress?.complete();
927
- }
928
- return result;
929
- }
930
- /** Send with hybrid KEM + dual signatures via v3 envelope. */
931
- async sendWithHybridV3(opts, plaintext, sharedKey, ephemeralPublicKey, kemCiphertext, progress) {
932
- if (!this.identity.mlDsaSecretKey) {
933
- return err('ENVELOPE_FAILED:PQ_KEY_MISSING');
934
- }
935
- progress?.update('Encrypting with post-quantum signatures...', 60);
936
- const envelope = await createEnvelopeV3({
937
- senderDid: this.identity.did,
938
- recipientDid: opts.to,
939
- scope: opts.scope,
940
- plaintext,
941
- privateKey: this.identity.privateKey,
942
- sharedKey,
943
- ephemeralPublicKey,
944
- kemCiphertext,
945
- mlDsaSecretKey: this.identity.mlDsaSecretKey,
946
- });
947
- if (!envelope.ok) {
948
- this.lastDetail = `v3 envelope error: ${envelope.error}`;
949
- return err('ENVELOPE_FAILED:ENCRYPT');
950
- }
951
- progress?.update('Sending message...', 90);
952
- // SAFETY: AnyTransportEnvelope is accepted by transport.send
953
- const result = await this.transports[0].send(envelope.value, opts.to);
954
- if (result.ok) {
955
- progress?.complete();
956
- }
957
- return result;
958
- }
959
- async sendDirect(opts, plaintext, sharedKey, progress) {
960
- progress?.update('Encrypting message...', 60);
961
- const envelope = await createEnvelope({
962
- senderDid: this.identity.did,
963
- recipientDid: opts.to,
964
- scope: opts.scope,
965
- plaintext,
966
- privateKey: this.identity.privateKey,
967
- sharedKey,
968
- });
969
- if (!envelope.ok)
970
- return err('ENVELOPE_FAILED:ENCRYPT');
971
- progress?.update('Sending message...', 90);
972
- const result = await this.transports[0].send(envelope.value, opts.to);
973
- if (result.ok) {
974
- progress?.complete();
975
- }
976
- return result;
977
- }
978
- /**
979
- * Check whether the recipient supports Xchange (XorIDA key transport).
980
- *
981
- * @param recipientDid - Recipient DID to check.
982
- * @returns True if recipient has xchange: true in registry.
983
- */
984
- async canUseXchange(recipientDid) {
985
- const entry = await this.registry.getEntry(recipientDid);
986
- if (!entry.ok)
987
- return false;
988
- return entry.value.xchange === true;
989
- }
990
- /**
991
- * Send via Xchange mode: random key + AES-GCM encrypt, bundle, XorIDA split, v4 envelopes.
992
- *
993
- * Opt-in performance mode. No KEM, no key agreement — the random key is
994
- * embedded in the bundle and split across channels. Single security layer
995
- * (information-theoretic) + Ed25519 authentication. ~180x faster than V3.
996
- */
997
- async sendXchange(opts, plaintext, progress) {
998
- const config = opts.splitChannelConfig ?? DEFAULT_SPLIT_CONFIG;
999
- if (this.transports.length < config.totalShares) {
1000
- // eslint-disable-next-line no-console
1001
- console.warn(`Split-channel: ${config.totalShares} shares but only ${this.transports.length} transport(s). ` +
1002
- `For channel separation, provide at least ${config.totalShares} transports.`);
1003
- }
1004
- progress?.update('Generating Xchange key...', 40);
1005
- const keyResult = await generateXchangeKey();
1006
- if (!keyResult.ok)
1007
- return err('KEY_AGREEMENT_FAILED');
1008
- progress?.update('Encrypting message...', 50);
1009
- const bundleResult = await xchangeEncrypt(plaintext, keyResult.value);
1010
- if (!bundleResult.ok)
1011
- return err('ENVELOPE_FAILED:ENCRYPT');
1012
- const n = config.totalShares;
1013
- const k = config.threshold;
1014
- const p = nextOddPrime(n);
1015
- const blockSize = p - 1;
1016
- const padded = pkcs7Pad(bundleResult.value, blockSize);
1017
- const { key: hmacKey, signature: hmacSig } = await generateHMAC(padded);
1018
- progress?.update('Splitting message into shares...', 60);
1019
- let shareArrays;
1020
- try {
1021
- shareArrays = splitXorIDA(padded, n, k);
1022
- }
1023
- catch {
1024
- return err('ENVELOPE_FAILED:SPLIT');
1025
- }
1026
- const hmacKeyB64 = toBase64(hmacKey);
1027
- const hmacSigB64 = toBase64(hmacSig);
1028
- const groupId = generateUUID();
1029
- const results = [];
1030
- progress?.update('Sending shares...', 70);
1031
- for (let i = 0; i < shareArrays.length; i++) {
1032
- const shareData = shareArrays[i];
1033
- const shareB64 = formatShareHeader(toBase64(shareData));
1034
- const shareBytes = new TextEncoder().encode(shareB64);
1035
- const envResult = await createEnvelopeV4({
1036
- senderDid: this.identity.did,
1037
- recipientDid: opts.to,
1038
- scope: opts.scope,
1039
- shareData: shareBytes,
1040
- privateKey: this.identity.privateKey,
1041
- shareIndex: i,
1042
- shareTotal: n,
1043
- shareThreshold: k,
1044
- shareGroupId: groupId,
1045
- shareHmacKey: hmacKeyB64,
1046
- shareHmacSig: hmacSigB64,
1047
- });
1048
- if (!envResult.ok) {
1049
- results.push(err('ENVELOPE_FAILED:ENCRYPT'));
1050
- continue;
1051
- }
1052
- // Route share[i] to transports[i % transports.length]
1053
- const transport = this.transports[i % this.transports.length];
1054
- // SAFETY: Transport accepts v1; v4 has same required fields
1055
- const sendResult = await transport.send(envResult.value, opts.to);
1056
- results.push(sendResult);
1057
- // Update progress for each share sent
1058
- const shareProgress = 70 + Math.floor((i + 1) / shareArrays.length * 20);
1059
- progress?.update(`Sent share ${i + 1}/${shareArrays.length}...`, shareProgress);
1060
- }
1061
- const successes = results.filter((r) => r.ok).length;
1062
- if (successes < k) {
1063
- return err('SEND_FAILED:BELOW_THRESHOLD');
1064
- }
1065
- progress?.complete();
1066
- return ok(undefined);
1067
- }
1068
- /**
1069
- * Split plaintext via XorIDA and send each share as a separate V3 envelope.
1070
- *
1071
- * Default split-channel path with three independent cryptographic layers:
1072
- * XorIDA payload split, hybrid PQ KEM, and dual signatures.
1073
- * Returns ok() if at least threshold sends succeed.
1074
- */
1075
- async sendSplitChannel(opts, plaintext, sharedKey, ephemeralPublicKey, kemCiphertext, recipientHasMlDsa, progress) {
1076
- const config = opts.splitChannelConfig ?? DEFAULT_SPLIT_CONFIG;
1077
- if (this.transports.length < config.totalShares) {
1078
- // eslint-disable-next-line no-console
1079
- console.warn(`Split-channel: ${config.totalShares} shares but only ${this.transports.length} transport(s). ` +
1080
- `For channel separation, provide at least ${config.totalShares} transports.`);
1081
- }
1082
- progress?.update('Splitting message into shares...', 50);
1083
- const splitResult = await splitForChannel(plaintext, config);
1084
- if (!splitResult.ok)
1085
- return err('ENVELOPE_FAILED:SPLIT');
1086
- const shares = splitResult.value;
1087
- progress?.update('Encrypting and sending shares...', 70);
1088
- const results = await this.sendShareEnvelopes(opts, shares, sharedKey, ephemeralPublicKey, kemCiphertext, recipientHasMlDsa, progress);
1089
- const successes = results.filter((r) => r.ok).length;
1090
- if (successes < config.threshold) {
1091
- return err('SEND_FAILED:BELOW_THRESHOLD');
1092
- }
1093
- progress?.complete();
1094
- return ok(undefined);
1095
- }
1096
- /**
1097
- * Create and send an envelope for each share independently.
1098
- *
1099
- * Routes share[i] to transports[i % transports.length] for channel separation.
1100
- */
1101
- async sendShareEnvelopes(opts, shares, sharedKey, ephemeralPublicKey, kemCiphertext, recipientHasMlDsa, progress) {
1102
- const results = [];
1103
- for (let i = 0; i < shares.length; i++) {
1104
- const share = shares[i];
1105
- const shareBytes = new TextEncoder().encode(share.data);
1106
- let envResult;
1107
- if (kemCiphertext && ephemeralPublicKey && recipientHasMlDsa && this.identity.mlDsaSecretKey) {
1108
- envResult = await createEnvelopeV3({
1109
- senderDid: this.identity.did,
1110
- recipientDid: opts.to,
1111
- scope: opts.scope,
1112
- plaintext: shareBytes,
1113
- privateKey: this.identity.privateKey,
1114
- sharedKey,
1115
- ephemeralPublicKey,
1116
- kemCiphertext,
1117
- mlDsaSecretKey: this.identity.mlDsaSecretKey,
1118
- shareIndex: share.index,
1119
- shareTotal: share.total,
1120
- shareThreshold: share.threshold,
1121
- shareGroupId: share.groupId,
1122
- shareHmacKey: share.hmacKey,
1123
- shareHmacSig: share.hmacSig,
1124
- });
1125
- }
1126
- else if (kemCiphertext && ephemeralPublicKey) {
1127
- envResult = await createEnvelopeV2({
1128
- senderDid: this.identity.did,
1129
- recipientDid: opts.to,
1130
- scope: opts.scope,
1131
- plaintext: shareBytes,
1132
- privateKey: this.identity.privateKey,
1133
- sharedKey,
1134
- ephemeralPublicKey,
1135
- kemCiphertext,
1136
- shareIndex: share.index,
1137
- shareTotal: share.total,
1138
- shareThreshold: share.threshold,
1139
- shareGroupId: share.groupId,
1140
- shareHmacKey: share.hmacKey,
1141
- shareHmacSig: share.hmacSig,
1142
- });
1143
- }
1144
- else {
1145
- envResult = await createEnvelope({
1146
- senderDid: this.identity.did,
1147
- recipientDid: opts.to,
1148
- scope: opts.scope,
1149
- plaintext: shareBytes,
1150
- privateKey: this.identity.privateKey,
1151
- sharedKey,
1152
- ephemeralPublicKey,
1153
- shareIndex: share.index,
1154
- shareTotal: share.total,
1155
- shareThreshold: share.threshold,
1156
- shareGroupId: share.groupId,
1157
- shareHmacKey: share.hmacKey,
1158
- shareHmacSig: share.hmacSig,
1159
- });
1160
- }
1161
- if (!envResult.ok) {
1162
- results.push(err('ENVELOPE_FAILED:ENCRYPT'));
1163
- continue;
1164
- }
1165
- // Route share[i] to transports[i % transports.length]
1166
- const transport = this.transports[i % this.transports.length];
1167
- // SAFETY: Transport accepts v1; v2/v3 is a superset of v1 fields
1168
- const sendResult = await transport.send(envResult.value, opts.to);
1169
- results.push(sendResult);
1170
- // Update progress for each share sent
1171
- const shareProgress = 70 + Math.floor((i + 1) / shares.length * 20);
1172
- progress?.update(`Sent share ${i + 1}/${shares.length}...`, shareProgress);
1173
- }
1174
- return results;
1175
- }
1176
- /**
1177
- * Receive and accumulate a split-channel share envelope.
1178
- *
1179
- * Verifies the envelope, extracts share metadata, accumulates shares.
1180
- * When threshold is reached, reconstructs the original plaintext.
1181
- *
1182
- * @param envelope - A share envelope with split-channel metadata
1183
- * @returns AgentMessage if threshold met, null if more shares needed
1184
- */
1185
- async receiveSplitShare(envelope) {
1186
- if (envelope.shareGroupId === undefined) {
1187
- return err('VERIFICATION_FAILED');
1188
- }
1189
- const receiveResult = await this.receiveRaw(envelope);
1190
- if (!receiveResult.ok)
1191
- return receiveResult;
1192
- const { sender, decryptedText, scope, timestamp } = receiveResult.value;
1193
- const share = {
1194
- data: decryptedText,
1195
- index: envelope.shareIndex ?? 0,
1196
- total: envelope.shareTotal ?? 2,
1197
- threshold: envelope.shareThreshold ?? 2,
1198
- groupId: envelope.shareGroupId,
1199
- hmacKey: envelope.shareHmacKey ?? '',
1200
- hmacSig: envelope.shareHmacSig ?? '',
1201
- };
1202
- return this.accumulateShare(share, sender, scope, timestamp);
1203
- }
1204
- /**
1205
- * Receive and accumulate a v4 Xchange share envelope.
1206
- *
1207
- * Verifies Ed25519 signature, extracts raw share data (no decryption —
1208
- * the XorIDA share IS the payload). When threshold is reached,
1209
- * reconstructs and decrypts via Xchange.
1210
- *
1211
- * @param envelope - A v4 Xchange envelope with share metadata.
1212
- * @returns AgentMessage if threshold met, null if more shares needed.
1213
- */
1214
- async receiveXchangeShare(envelope) {
1215
- this.lastDetail = '';
1216
- const verified = await this.verifyEnvelope(envelope);
1217
- if (!verified.ok)
1218
- return verified;
1219
- // V4: payload is the raw share data (base64 of share bytes), NOT encrypted
1220
- const shareText = new TextDecoder().decode(verified.value.payloadBytes);
1221
- const share = {
1222
- data: shareText,
1223
- index: envelope.shareIndex,
1224
- total: envelope.shareTotal,
1225
- threshold: envelope.shareThreshold,
1226
- groupId: envelope.shareGroupId,
1227
- hmacKey: envelope.shareHmacKey,
1228
- hmacSig: envelope.shareHmacSig,
1229
- };
1230
- return this.accumulateXchangeShare(share, envelope.sender, envelope.scope, envelope.timestamp);
1231
- }
1232
- /**
1233
- * Accumulate a Xchange share and attempt reconstruction + decryption.
1234
- *
1235
- * When threshold is met:
1236
- * 1. Reconstruct padded bundle from XorIDA shares
1237
- * 2. Verify HMAC (BEFORE decrypt — CRITICAL)
1238
- * 3. Unpad → extract bundle → xchangeDecrypt → plaintext
1239
- */
1240
- async accumulateXchangeShare(share, sender, scope, timestamp) {
1241
- const existing = this.shareAccumulator.get(share.groupId) ?? [];
1242
- const isDuplicate = existing.some((s) => s.index === share.index);
1243
- if (!isDuplicate) {
1244
- existing.push(share);
1245
- this.shareAccumulator.set(share.groupId, existing);
1246
- }
1247
- if (existing.length < share.threshold) {
1248
- return ok(null);
1249
- }
1250
- this.shareAccumulator.delete(share.groupId);
1251
- const usedShares = existing.slice(0, share.threshold);
1252
- const n = share.total;
1253
- const k = share.threshold;
1254
- // Decode share data from base64
1255
- let shareData;
1256
- try {
1257
- shareData = usedShares.map((s) => fromBase64(parseShareHeader(s.data)));
1258
- }
1259
- catch {
1260
- return err('DECRYPT_FAILED');
1261
- }
1262
- const indices = usedShares.map((s) => s.index);
1263
- // Reconstruct padded bundle
1264
- let padded;
1265
- try {
1266
- padded = reconstructXorIDA(shareData, indices, n, k);
1267
- }
1268
- catch {
1269
- return err('DECRYPT_FAILED');
1270
- }
1271
- // HMAC verification BEFORE decrypt — CRITICAL
1272
- let hmacKey;
1273
- let hmacSig;
1274
- try {
1275
- hmacKey = fromBase64(usedShares[0].hmacKey);
1276
- hmacSig = fromBase64(usedShares[0].hmacSig);
1277
- }
1278
- catch {
1279
- return err('DECRYPT_FAILED');
1280
- }
1281
- const hmacValid = await verifyHMAC(hmacKey, padded, hmacSig);
1282
- if (!hmacValid) {
1283
- this.lastDetail = 'HMAC verification failed before decrypt';
1284
- return err('DECRYPT_FAILED');
1285
- }
1286
- // Unpad
1287
- const p = nextOddPrime(n);
1288
- const blockSize = p - 1;
1289
- const unpadResult = pkcs7Unpad(padded, blockSize);
1290
- if (!unpadResult.ok)
1291
- return err('DECRYPT_FAILED');
1292
- // Xchange decrypt: extract K, IV, ciphertext from bundle
1293
- const decryptResult = await xchangeDecrypt(unpadResult.value);
1294
- if (!decryptResult.ok)
1295
- return err('DECRYPT_FAILED:DECRYPTION');
1296
- let payload;
1297
- try {
1298
- payload = JSON.parse(new TextDecoder().decode(decryptResult.value));
1299
- }
1300
- catch {
1301
- return err('DECRYPT_FAILED:PARSE');
1302
- }
1303
- // Mechanism 2: Protocol information available in return value
1304
- // Applications can display: "Secured with PRIVATE.ME/xBind/v3. Learn more: https://private.me/docs/xbind.html"
1305
- return ok({ sender, payload, scope, timestamp });
1306
- }
1307
- /**
1308
- * Accumulate a share and attempt reconstruction when threshold is met.
1309
- */
1310
- async accumulateShare(share, sender, scope, timestamp) {
1311
- const existing = this.shareAccumulator.get(share.groupId) ?? [];
1312
- const isDuplicate = existing.some((s) => s.index === share.index);
1313
- if (!isDuplicate) {
1314
- existing.push(share);
1315
- this.shareAccumulator.set(share.groupId, existing);
1316
- }
1317
- if (existing.length < share.threshold) {
1318
- return ok(null);
1319
- }
1320
- this.shareAccumulator.delete(share.groupId);
1321
- const result = await reconstructFromChannel(existing);
1322
- if (!result.ok)
1323
- return err('DECRYPT_FAILED');
1324
- let payload;
1325
- try {
1326
- payload = JSON.parse(new TextDecoder().decode(result.value));
1327
- }
1328
- catch {
1329
- return err('DECRYPT_FAILED');
1330
- }
1331
- // Mechanism 2: Protocol information available in return value
1332
- // Applications can display: "Secured with PRIVATE.ME/xBind/v3. Learn more: https://private.me/docs/xbind.html"
1333
- return ok({ sender, payload, scope, timestamp });
1334
- }
1335
- /**
1336
- * Common envelope verification: version, timestamp, nonce, DID, signature, scope.
1337
- *
1338
- * Used by receive(), receiveSigned(), and receiveRaw() to avoid duplication.
1339
- * Consumes the nonce on success (replay prevention).
1340
- */
1341
- async verifyEnvelope(envelope) {
1342
- // Runtime null guard: catch null/undefined despite TypeScript types
1343
- if (!envelope || typeof envelope !== 'object') {
1344
- this.lastDetail = 'envelope is null or not an object';
1345
- return err('VERIFICATION_FAILED:INVALID_ENVELOPE');
1346
- }
1347
- if ((envelope.v !== 1 && envelope.v !== 2 && envelope.v !== 3 && envelope.v !== 4) || envelope.alg !== 'Ed25519') {
1348
- this.lastDetail = `v=${String(envelope.v)}, alg=${String(envelope.alg)}`;
1349
- return err('VERIFICATION_FAILED:UNSUPPORTED_VERSION');
1350
- }
1351
- // SECURITY FIX (v1.1.3): Type guard for timestamp (prevent type confusion)
1352
- // Attack: Send timestamp: "soon" → Date.now() - "soon" = NaN → window check bypassed
1353
- if (typeof envelope.timestamp !== 'number' || !Number.isFinite(envelope.timestamp)) {
1354
- this.lastDetail = `timestamp=${String(envelope.timestamp)} (must be finite number)`;
1355
- return err('VERIFICATION_FAILED:INVALID_ENVELOPE');
1356
- }
1357
- const age = Math.abs(Date.now() - envelope.timestamp);
1358
- if (age > this.timestampWindowMs) {
1359
- this.lastDetail = `age=${age}ms, max=${this.timestampWindowMs}ms`;
1360
- return err('TIMESTAMP_EXPIRED');
1361
- }
1362
- const nonceOk = await this.nonceStore.check(envelope.nonce, envelope.sender);
1363
- if (!nonceOk) {
1364
- this.lastDetail = `nonce=${envelope.nonce}`;
1365
- return err('REPLAY_DETECTED');
1366
- }
1367
- const senderKey = await this.registry.resolve(envelope.sender);
1368
- if (!senderKey.ok) {
1369
- this.lastDetail = `did=${envelope.sender}`;
1370
- return err('VERIFICATION_FAILED:DID_NOT_IN_REGISTRY');
1371
- }
1372
- const pubKey = await importPublicKey(senderKey.value);
1373
- if (!pubKey.ok) {
1374
- this.lastDetail = `did=${envelope.sender}`;
1375
- return err('VERIFICATION_FAILED:KEY_IMPORT_FAILED');
1376
- }
1377
- // SECURITY FIX (v1.1.3): Guard for missing signature field (prevent TypeError crash)
1378
- // Attack: Send envelope without signature field → fromBase64(undefined) throws → DoS
1379
- if (!envelope.signature || typeof envelope.signature !== 'string') {
1380
- this.lastDetail = 'signature field missing or invalid';
1381
- return err('VERIFICATION_FAILED:SIGNATURE_MISMATCH');
1382
- }
1383
- // SECURITY FIX (v1.1.3): Verify signature over canonical envelope representation
1384
- // (not just payload) to prevent replay attacks via nonce substitution
1385
- const sigBytes = fromBase64(envelope.signature);
1386
- // Create canonical representation for signature verification
1387
- const canonicalData = JSON.stringify({
1388
- v: envelope.v,
1389
- alg: envelope.alg,
1390
- sender: envelope.sender,
1391
- recipient: envelope.recipient,
1392
- timestamp: envelope.timestamp,
1393
- nonce: envelope.nonce,
1394
- scope: envelope.scope,
1395
- payload: envelope.payload,
1396
- });
1397
- const canonicalBytes = new TextEncoder().encode(canonicalData);
1398
- // Verify canonical signature (v1.1.3+)
1399
- // SECURITY: No legacy fallback. Pre-v1.1.3 envelopes use payload-only signatures
1400
- // that don't cover nonce, allowing unlimited replay attacks. All senders must upgrade.
1401
- const sigValid = await verify(pubKey.value, sigBytes, canonicalBytes);
1402
- if (!sigValid.ok || !sigValid.value) {
1403
- this.lastDetail = 'signature does not match canonical envelope (v1.1.3+ required)';
1404
- return err('VERIFICATION_FAILED:SIGNATURE_MISMATCH');
1405
- }
1406
- // V3: verify ML-DSA-65 post-quantum signature (both sigs must pass)
1407
- if (envelope.v === 3 && 'pqSignature' in envelope) {
1408
- // SECURITY FIX (v1.1.5): Guard for non-string pqSignature field
1409
- if (typeof envelope.pqSignature !== 'string') {
1410
- this.lastDetail = 'pqSignature field not a string';
1411
- return err('VERIFICATION_FAILED:INVALID_ENVELOPE');
1412
- }
1413
- const senderEntry = await this.registry.getEntry(envelope.sender);
1414
- if (!senderEntry.ok || !senderEntry.value.mlDsaPublicKey) {
1415
- this.lastDetail = `did=${envelope.sender} missing ML-DSA public key`;
1416
- return err('VERIFICATION_FAILED:PQ_KEY_MISSING');
1417
- }
1418
- const pqSigBytes = fromBase64(envelope.pqSignature);
1419
- // Verify ML-DSA-65 post-quantum signature (canonical only, v1.1.3+)
1420
- // SECURITY: No legacy fallback for same replay protection reasons as Ed25519
1421
- const pqValid = await verifyMlDsa65(senderEntry.value.mlDsaPublicKey, pqSigBytes, canonicalBytes);
1422
- if (!pqValid.ok || !pqValid.value) {
1423
- this.lastDetail = 'ML-DSA-65 signature does not match canonical envelope (v1.1.3+ required)';
1424
- return err('VERIFICATION_FAILED:PQ_SIGNATURE_MISMATCH');
1425
- }
1426
- }
1427
- const hasScope = await this.registry.hasScope(envelope.sender, envelope.scope);
1428
- if (!hasScope) {
1429
- this.lastDetail = `scope=${envelope.scope}`;
1430
- return err('SCOPE_DENIED');
1431
- }
1432
- // SECURITY FIX (v1.1.5): Guard for non-string payload field
1433
- if (typeof envelope.payload !== 'string') {
1434
- this.lastDetail = 'payload field not a string';
1435
- return err('VERIFICATION_FAILED:INVALID_ENVELOPE');
1436
- }
1437
- // Return decoded payload bytes for decryption
1438
- const payloadBytes = fromBase64(envelope.payload);
1439
- return ok({ senderRawKey: senderKey.value, payloadBytes });
1440
- }
1441
- /**
1442
- * Verify and decrypt an envelope, returning raw text (no JSON parse).
1443
- * Used by receiveSplitShare to get the raw decrypted share data.
1444
- */
1445
- async receiveRaw(envelope) {
1446
- const verified = await this.verifyEnvelope(envelope);
1447
- if (!verified.ok)
1448
- return verified;
1449
- const { senderRawKey } = verified.value;
1450
- // V4 Xchange: use receiveXchangeShare() instead
1451
- if (envelope.v === 4) {
1452
- return err('VERIFICATION_FAILED:UNSUPPORTED_VERSION');
1453
- }
1454
- let sharedKey;
1455
- // V2/V3 hybrid path
1456
- if ((envelope.v === 2 || envelope.v === 3) && 'kemCiphertext' in envelope) {
1457
- if (!this.identity.mlKemSecretKey) {
1458
- return err('DECRYPT_FAILED:KEY_AGREEMENT');
1459
- }
1460
- // SECURITY FIX (v1.1.5): Guard for non-string fields
1461
- if (typeof envelope.ephemeralPub !== 'string' || typeof envelope.kemCiphertext !== 'string') {
1462
- return err('DECRYPT_FAILED:INVALID_ENVELOPE');
1463
- }
1464
- const ephPubBytes = fromBase64(envelope.ephemeralPub);
1465
- const kemCtBytes = fromBase64(envelope.kemCiphertext);
1466
- const hybridKey = await receiverHybridKeyAgreement(this.identity.x25519PrivateKey, ephPubBytes, kemCtBytes, this.identity.mlKemSecretKey);
1467
- if (!hybridKey.ok)
1468
- return err('DECRYPT_FAILED:KEY_AGREEMENT');
1469
- sharedKey = hybridKey.value;
1470
- }
1471
- else if (envelope.ephemeralPub) {
1472
- // SECURITY FIX (v1.1.5): Guard for non-string field
1473
- if (typeof envelope.ephemeralPub !== 'string') {
1474
- return err('DECRYPT_FAILED:INVALID_ENVELOPE');
1475
- }
1476
- const ephPubBytes = fromBase64(envelope.ephemeralPub);
1477
- const ecdhKey = await receiverKeyAgreement(this.identity.x25519PrivateKey, ephPubBytes);
1478
- if (!ecdhKey.ok)
1479
- return err('DECRYPT_FAILED:KEY_AGREEMENT');
1480
- sharedKey = ecdhKey.value;
1481
- }
1482
- else {
1483
- // SECURITY FIX (v1.1.6): Removed insecure fallback
1484
- // Envelopes without ephemeralPub rejected (sender must use X25519 ECDH)
1485
- return err('DECRYPT_FAILED:NO_EPHEMERAL_KEY');
1486
- }
1487
- const decrypted = await decryptPayload(envelope, sharedKey);
1488
- if (!decrypted.ok)
1489
- return err('DECRYPT_FAILED:DECRYPTION');
1490
- const decryptedText = new TextDecoder().decode(decrypted.value);
1491
- return ok({
1492
- sender: envelope.sender,
1493
- decryptedText,
1494
- scope: envelope.scope,
1495
- timestamp: envelope.timestamp,
1496
- });
1497
- }
1498
- /**
1499
- * Send email invitation to establish connection.
1500
- *
1501
- * Uses email transport to send branded invitation with one-click acceptance.
1502
- * Requires EmailTransport to be configured in agent options.
1503
- *
1504
- * @param opts - Invitation options
1505
- * @returns Result with success status
1506
- *
1507
- * @example
1508
- * ```ts
1509
- * await agent.invite({
1510
- * to: 'fulfillment@acme.com',
1511
- * message: 'Connect our payment systems'
1512
- * });
1513
- * ```
1514
- */
1515
- async invite(opts) {
1516
- if (!this.transports || this.transports.length === 0) {
1517
- return err('SEND_FAILED');
1518
- }
1519
- // Convert raw public key to base64 for transmission
1520
- const publicKeyBase64 = Buffer.from(this.identity.rawPublicKey).toString('base64');
1521
- // Create invitation envelope
1522
- const envelope = {
1523
- from: this.identity.did,
1524
- to: opts.to,
1525
- payload: {
1526
- agentName: this.name,
1527
- message: opts.message,
1528
- publicKey: publicKeyBase64,
1529
- endpoint: '', // Email-based invites don't need endpoint
1530
- },
1531
- };
1532
- // Send via first transport (assumed to be EmailTransport for invite())
1533
- const transport = this.transports[0];
1534
- if (!transport) {
1535
- return err('SEND_FAILED');
1536
- }
1537
- const result = await transport.send(envelope, opts.to);
1538
- if (!result.ok) {
1539
- return err('SEND_FAILED');
1540
- }
1541
- return ok(undefined);
1542
- }
1543
- }
1544
- // SECURITY FIX (v1.1.6): Removed deriveSharedKey export (insecure, public-key-only derivation)
1545
- export { generateSharedKey };
1
+ import{ok,err}from"./_deps/shared/index.js";import{fromBase64,toBase64,generateUUID,formatShareHeader,parseShareHeader}from"./crypto-utils.js";import{loadCryptoPackage,getCrypto}from"./vault-store-loader.js";import{QuotaExceededError,VaultStoreError}from"./errors.js";import{generateIdentity,verify,importPublicKey,identityFromSeed,exportPKCS8,exportX25519PKCS8,extractRawEd25519,extractRawX25519}from"./identity.js";import{createEnvelope,createEnvelopeV2,createEnvelopeV3,createEnvelopeV4,decryptPayload,validateEnvelope,generateSharedKey}from"./envelope.js";import{generateXchangeKey,xchangeEncrypt,xchangeDecrypt}from"./_deps/xchange/index.js";import{verifyMlDsa65}from"./identity.js";import{senderKeyAgreement,receiverKeyAgreement,senderHybridKeyAgreement,receiverHybridKeyAgreement,importX25519PublicKey}from"./key-agreement.js";import{splitForChannel,reconstructFromChannel,DEFAULT_SPLIT_CONFIG}from"./split-channel.js";import{MemoryNonceStore}from"./nonce-store.js";import{HttpsTransportAdapter}from"./transport.js";import{MemoryTrustRegistry,HttpTrustRegistry}from"./trust-registry.js";import{ProgressReporter}from"./_deps/ux-helpers/index.js";import{DefaultSecurityPolicy,describeSecurityMode}from"./security-policy.js";import{DEFAULT_BACKUP_CONFIG}from"./backup-config.js";const DEFAULT_RELAY_URL=process.env.XBIND_RELAY_URL||"https://private.me/relay",DEFAULT_REGISTRY_URL=process.env.XBIND_REGISTRY_URL||"https://private.me/registry";export function parseAgentError(e){const t=e.split(":");return 1===t.length?{code:t[0]??e}:{code:t[0]??e,subCode:t.slice(1).join(":")}}const TIMESTAMP_WINDOW_MS=3e4;function toArrayBuffer(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}function compareBytes(e,t){const r=Math.min(e.length,t.length);for(let i=0;i<r;i++){const r=e[i]??0,a=t[i]??0;if(r!==a)return r-a}return e.length-t.length}function concatBytes(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}export class Agent{identity;name;registry;transports;nonceStore;timestampWindowMs;securityPolicy;backupConfig;shareAccumulator=new Map;lastDetail="";lastSecurityDecision;cleanupTimer;cryptoModule=null;get lastErrorDetail(){return this.lastDetail}get lastSecurity(){return this.lastSecurityDecision}constructor(e,t,r,i,a,s,n,o){this.identity=e,this.name=t,this.registry=r,this.transports=i,this.nonceStore=a,this.timestampWindowMs=s,this.securityPolicy=n??new DefaultSecurityPolicy,this.backupConfig=o??DEFAULT_BACKUP_CONFIG}get did(){return this.identity.did}getTransports(){return this.transports}async ensureCrypto(){if(this.cryptoModule)return this.cryptoModule;const e=getCrypto();if(e)return this.cryptoModule=e,e;const t=await loadCryptoPackage(this.identity);if(!t.ok){if("VAULT_QUOTA_EXCEEDED"===t.error){const e="https://private.me/subscribe?product=xbind&tier=pro";throw new QuotaExceededError(`Monthly usage quota exceeded (Free tier: 100K operations/month). Upgrade to Pro tier for unlimited access at $5 per 100K operations. Visit: ${e}`,e)}throw new VaultStoreError(t.error,`Failed to load crypto package: ${t.error}`)}return this.cryptoModule=t.value,t.value}static isSupported(){try{return void 0!==globalThis.crypto&&void 0!==globalThis.crypto.subtle&&"function"==typeof globalThis.crypto.subtle.generateKey&&"function"==typeof globalThis.crypto.subtle.sign&&"function"==typeof globalThis.crypto.subtle.verify&&"function"==typeof globalThis.crypto.subtle.encrypt&&"function"==typeof globalThis.crypto.getRandomValues}catch{return!1}}static async fromIdentity(e,t){const r=t.nonceStore??new MemoryNonceStore,i=t.timestampWindowMs??3e4,a=Array.isArray(t.transport)?t.transport:[t.transport],s=new Agent(e,t.name??e.did,t.registry,a,r,i,t.securityPolicy,t.backupConfig);return ok(s)}static fromParts(e,t,r,i){const a=Array.isArray(r)?r:[r];return new Agent(e,i?.name??e.did,t,a,i?.nonceStore??new MemoryNonceStore,i?.timestampWindowMs??3e4,i?.securityPolicy,i?.backupConfig)}static async fromSeed(e,t){const r=await identityFromSeed(e,{postQuantumSig:t.postQuantumSig});if(!r.ok)return err("IDENTITY_FAILED:KEYGEN");const i=await t.registry.register(r.value.did,r.value.rawPublicKey,t.name??r.value.did,t.scopes,r.value.rawX25519PublicKey,r.value.mlKemPublicKey,r.value.mlDsaPublicKey,t.xchange??!1);if(!i.ok&&"ALREADY_REGISTERED"!==i.error){const e="NETWORK_ERROR"===i.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return err(e)}const a=t.nonceStore??new MemoryNonceStore,s=t.timestampWindowMs??3e4,n=Array.isArray(t.transport)?t.transport:[t.transport];return ok(new Agent(r.value,t.name??r.value.did,t.registry,n,a,s,t.securityPolicy,t.backupConfig))}static async lazy(e){const{createLazyAgent:t}=await import("./lazy-init.js");return t(e)}isReady(){return void 0!==this.identity&&void 0!==this.registry&&this.transports.length>0}static async create(e){const t=await generateIdentity({postQuantumSig:e.postQuantumSig});if(!t.ok)return err("IDENTITY_FAILED:KEYGEN");const r=await e.registry.register(t.value.did,t.value.rawPublicKey,e.name,e.scopes,t.value.rawX25519PublicKey,t.value.mlKemPublicKey,t.value.mlDsaPublicKey,e.xchange??!1);if(!r.ok){const e="ALREADY_REGISTERED"===r.error?"REGISTRATION_FAILED:ALREADY_REGISTERED":"NETWORK_ERROR"===r.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return err(e)}const i=e.nonceStore??new MemoryNonceStore,a=e.timestampWindowMs??3e4,s=Array.isArray(e.transport)?e.transport:[e.transport],n=new Agent(t.value,e.name,e.registry,s,i,a,e.securityPolicy,e.backupConfig);try{await n.ensureCrypto()}catch(e){return err(e instanceof QuotaExceededError?"QUOTA_EXCEEDED":e instanceof VaultStoreError?"IDENTITY_FAILED:VAULT_STORE":"IDENTITY_FAILED")}return ok(n)}static async quickstart(e){const t=new MemoryTrustRegistry,r=new HttpsTransportAdapter({baseUrl:DEFAULT_RELAY_URL}),i=await generateIdentity({postQuantumSig:!1});if(!i.ok)throw new Error("Failed to generate ephemeral identity");const a=e?.name??`agent-${Date.now()}`,s=await t.register(i.value.did,i.value.rawPublicKey,a,void 0,i.value.rawX25519PublicKey,i.value.mlKemPublicKey,i.value.mlDsaPublicKey,!1);if(!s.ok)throw new Error(`Failed to register ephemeral identity: ${s.error}`);const n=new Agent(i.value,a,t,[r],new MemoryNonceStore,3e4,void 0,void 0);return n.cleanupTimer=setTimeout(async()=>{await t.revoke(i.value.did)},36e5),n}static async from(e={}){const t=e.identity??"persistent",r=e.identityTTL??36e5,i="ephemeral"===t,a="string"==typeof e.registry?new HttpTrustRegistry({baseUrl:e.registry}):e.registry??(i?new MemoryTrustRegistry:new HttpTrustRegistry({baseUrl:DEFAULT_REGISTRY_URL})),s=e.transport?Array.isArray(e.transport)?e.transport:[e.transport]:[new HttpsTransportAdapter({baseUrl:DEFAULT_RELAY_URL})],n=await generateIdentity({postQuantumSig:e.postQuantumSig??!1});if(!n.ok)throw new Error("Failed to generate identity");const o=i?`ephemeral-agent-${Date.now()}`:`agent-${Date.now()}`,c=await a.register(n.value.did,n.value.rawPublicKey,o,void 0,n.value.rawX25519PublicKey,n.value.mlKemPublicKey,n.value.mlDsaPublicKey,!1);if(!c.ok)throw new Error(`Failed to register identity: ${c.error}`);const l=new Agent(n.value,o,a,s,new MemoryNonceStore,3e4,e.securityPolicy,e.backupConfig);return i&&(l.cleanupTimer=setTimeout(async()=>{await a.revoke(n.value.did)},r)),l}async send(e){const t=new ProgressReporter(e.onProgress);t.start("Resolving recipient identity...");const r=await this.registry.resolve(e.to);if(!r.ok)return err("REVOKED"===r.error?"RECIPIENT_REVOKED":"RECIPIENT_NOT_FOUND");t.update("Checking recipient authorization...",10);if(!await this.registry.hasReceiveScope(e.to,e.scope))return this.lastDetail=`recipient=${e.to}, scope=${e.scope}`,err("RECEIVER_SCOPE_DENIED");t.update("Preparing message...",15);const i=(new TextEncoder).encode(JSON.stringify(e.payload));t.update("Determining security level...",20);const a=this.securityPolicy.classify({action:e.action??"send",params:"object"==typeof e.payload&&null!==e.payload?e.payload:{},sender:this.did,recipient:e.to,scope:e.scope,securityOverride:e.security});this.lastSecurityDecision=a,t.update(`Security: ${describeSecurityMode(a.mode)} — ${a.reason}`,25);const s=void 0!==e.splitChannel?e.splitChannel:"split"===a.mode.type;if(s&&(e.xchange||"xchange"===a.mode.type)){t.update("Checking Xchange support...",20);if(await this.canUseXchange(e.to))return this.sendXchange(e,i,t)}t.update("Establishing key agreement...",30);const n=await this.trySenderECDH(e.to);return n?s?this.sendSplitChannel(e,i,n.sharedKey,n.ephemeralPublicKey,n.kemCiphertext,n.recipientHasMlDsa,t):n.kemCiphertext&&n.recipientHasMlDsa&&this.identity.mlDsaSecretKey?this.sendWithHybridV3(e,i,n.sharedKey,n.ephemeralPublicKey,n.kemCiphertext,t):n.kemCiphertext?this.sendWithHybrid(e,i,n.sharedKey,n.ephemeralPublicKey,n.kemCiphertext,t):this.sendWithECDH(e,i,n.sharedKey,n.ephemeralPublicKey,t):err("KEY_AGREEMENT_FAILED:RECIPIENT_HAS_NO_X25519_KEY")}async receive(e,t){this.lastDetail="";const r=new ProgressReporter(t?.onProgress);r.start("Verifying envelope signature...");const i=await this.verifyEnvelope(e);if(!i.ok)return i;const{senderRawKey:a,payloadBytes:s}=i.value;let n;if(4===e.v)return err("VERIFICATION_FAILED:UNSUPPORTED_VERSION");if(r.update("Deriving shared key...",30),2!==e.v&&3!==e.v||!("kemCiphertext"in e)){if(!e.ephemeralPub){if(t?.allowCleartext){let t;try{t=JSON.parse((new TextDecoder).decode(s))}catch{return err("DECRYPT_FAILED:PARSE")}return r.complete(),ok({sender:e.sender,payload:t,scope:e.scope,timestamp:e.timestamp})}return err("DECRYPT_FAILED:NO_EPHEMERAL_KEY")}{if("string"!=typeof e.ephemeralPub)return this.lastDetail="ephemeralPub not string",err("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=fromBase64(e.ephemeralPub),i=await receiverKeyAgreement(this.identity.x25519PrivateKey,t);if(i.ok)n=i.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){const i=await receiverKeyAgreement(e.x25519PrivateKey,t);if(i.ok){n=i.value,r.update("Decrypting with rotated keys...",45);break}}if(!n)return err("DECRYPT_FAILED:KEY_AGREEMENT")}}}else{if(!this.identity.mlKemSecretKey)return err("DECRYPT_FAILED:KEY_AGREEMENT");if("string"!=typeof e.ephemeralPub||"string"!=typeof e.kemCiphertext)return this.lastDetail="ephemeralPub or kemCiphertext not string",err("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=fromBase64(e.ephemeralPub),i=fromBase64(e.kemCiphertext);if(!this.identity.mlKemPublicKey||!this.identity.mlKemSecretKey)return this.lastDetail="ML-KEM keys not available in identity",err("DECRYPT_FAILED:MISSING_MLKEM_KEYS");const a=await receiverHybridKeyAgreement(this.identity.x25519PrivateKey,this.identity.rawX25519PublicKey,t,i,this.identity.mlKemSecretKey,this.identity.mlKemPublicKey);if(a.ok)n=a.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){if(!e.mlKemSecretKey)continue;const a=await receiverHybridKeyAgreement(e.x25519PrivateKey,this.identity.rawX25519PublicKey,t,i,e.mlKemSecretKey,this.identity.mlKemPublicKey);if(a.ok){n=a.value,r.update("Decrypting with rotated keys...",45);break}}if(!n)return err("DECRYPT_FAILED:KEY_AGREEMENT")}}if(r.update("Decrypting payload...",60),!n)return err("DECRYPT_FAILED:KEY_AGREEMENT");const o=await decryptPayload(e,n);if(!o.ok)return err("DECRYPT_FAILED:DECRYPTION");let c;r.update("Parsing message...",90);try{c=JSON.parse((new TextDecoder).decode(o.value))}catch{return err("DECRYPT_FAILED:PARSE")}return r.complete(),ok({sender:e.sender,payload:c,scope:e.scope,timestamp:e.timestamp,metadata:e.protocol&&e.documentationUrl?{protocol:e.protocol,documentationUrl:e.documentationUrl}:void 0})}async verifySignature(e){const t=await this.registry.resolve(e.sender);if(!t.ok)return err("VERIFICATION_FAILED:DID_NOT_IN_REGISTRY");const r=await importPublicKey(t.value);if(!r.ok)return err("VERIFICATION_FAILED:KEY_IMPORT_FAILED");const i=fromBase64(e.signature),a=JSON.stringify({v:e.v,alg:e.alg,sender:e.sender,recipient:e.recipient,timestamp:e.timestamp,nonce:e.nonce,scope:e.scope,payload:e.payload}),s=(new TextEncoder).encode(a),n=await verify(r.value,i,s);return n.ok?ok({sender:e.sender,valid:n.value}):err("VERIFICATION_FAILED:SIGNATURE_MISMATCH")}async exportSeeds(){const e=await exportPKCS8(this.identity.privateKey);if(!e.ok)return err("IDENTITY_FAILED");const t=await exportX25519PKCS8(this.identity.x25519PrivateKey);if(!t.ok)return err("IDENTITY_FAILED");const r=extractRawEd25519(e.value);if(!r.ok)return err("IDENTITY_FAILED");const i=extractRawX25519(t.value);return i.ok?ok({ed25519:r.value,x25519:i.value,mlKemSecretKey:this.identity.mlKemSecretKey,mlKemPublicKey:this.identity.mlKemPublicKey}):err("IDENTITY_FAILED")}async splitKey(e){const{splitKeyWithBackup:t}=await import("./backup-config.js"),r=await t(e,this.backupConfig);return r.ok?r:err("ENVELOPE_FAILED:SPLIT")}async reconstructKey(e){const{reconstructKeyFromBackup:t}=await import("./backup-config.js"),r=await t(e);return r.ok?r:err("DECRYPT_FAILED")}async receiveSigned(e){this.lastDetail="";const t=await this.verifyEnvelope(e);if(!t.ok)return t;let r;try{r=JSON.parse((new TextDecoder).decode(t.value.payloadBytes))}catch{return err("DECRYPT_FAILED:PARSE")}return ok({sender:e.sender,payload:r,scope:e.scope,timestamp:e.timestamp,metadata:e.protocol&&e.documentationUrl?{protocol:e.protocol,documentationUrl:e.documentationUrl}:void 0})}async discover(e){const{getToolRegistry:t}=await import("./agent-call.js"),r=t();if(!r)return[];if(!e)return r.listAll();return r.search(e)}middleware(){return async(e,t,r)=>{const i=validateEnvelope(e.body);if(!i.ok)return void t.status(400).json({error:i.error});const a=await this.receive(i.value);if(!a.ok){const e="TIMESTAMP_EXPIRED"===a.error||"REPLAY_DETECTED"===a.error?403:401;return void t.status(e).json({error:a.error})}e.agentMessage=a.value,r()}}cleanup(){this.cleanupTimer&&(clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0)}dispose(){this.cleanup()}async trySenderECDH(e){const t=await this.registry.getEntry(e);if(!t.ok||!t.value.x25519PublicKey)return null;const r=!!t.value.mlDsaPublicKey,i=await importX25519PublicKey(t.value.x25519PublicKey);if(!i.ok)return null;if(t.value.mlKemPublicKey&&this.identity.mlKemSecretKey){const e=await senderHybridKeyAgreement(i.value,t.value.mlKemPublicKey);if(e.ok)return{sharedKey:e.value.sharedKey,ephemeralPublicKey:e.value.ephemeralPublicKey,kemCiphertext:e.value.kemCiphertext,recipientHasMlDsa:r}}const a=await senderKeyAgreement(i.value);return a.ok?{...a.value,recipientHasMlDsa:r}:null}async sendWithECDH(e,t,r,i,a){a?.update("Encrypting message with ECDH...",60);const s=await createEnvelope({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i});if(!s.ok)return err("ENVELOPE_FAILED:ENCRYPT");a?.update("Sending message...",90);const n=await this.transports[0].send(s.value,e.to);return n.ok&&a?.complete(),n}async sendWithHybrid(e,t,r,i,a,s){s?.update("Encrypting message with hybrid KEM...",60);const n=await createEnvelopeV2({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:a});if(!n.ok)return err("ENVELOPE_FAILED:ENCRYPT");s?.update("Sending message...",90);const o=await this.transports[0].send(n.value,e.to);return o.ok&&s?.complete(),o}async sendWithHybridV3(e,t,r,i,a,s){if(!this.identity.mlDsaSecretKey)return err("ENVELOPE_FAILED:PQ_KEY_MISSING");s?.update("Encrypting with post-quantum signatures...",60);const n=await createEnvelopeV3({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:a,mlDsaSecretKey:this.identity.mlDsaSecretKey});if(!n.ok)return this.lastDetail=`v3 envelope error: ${n.error}`,err("ENVELOPE_FAILED:ENCRYPT");s?.update("Sending message...",90);const o=await this.transports[0].send(n.value,e.to);return o.ok&&s?.complete(),o}async sendDirect(e,t,r,i){i?.update("Encrypting message...",60);const a=await createEnvelope({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:t,privateKey:this.identity.privateKey,sharedKey:r});if(!a.ok)return err("ENVELOPE_FAILED:ENCRYPT");i?.update("Sending message...",90);const s=await this.transports[0].send(a.value,e.to);return s.ok&&i?.complete(),s}async canUseXchange(e){const t=await this.registry.getEntry(e);return!!t.ok&&!0===t.value.xchange}async sendXchange(e,t,r){const i=e.splitChannelConfig??DEFAULT_SPLIT_CONFIG;this.transports.length<i.totalShares&&console.warn(`Split-channel: ${i.totalShares} shares but only ${this.transports.length} transport(s). For channel separation, provide at least ${i.totalShares} transports.`),r?.update("Generating Xchange key...",40);const a=await generateXchangeKey();if(!a.ok)return err("KEY_AGREEMENT_FAILED");r?.update("Encrypting message...",50);const s=await xchangeEncrypt(t,a.value);if(!s.ok)return err("ENVELOPE_FAILED:ENCRYPT");const n=await this.ensureCrypto(),o=i.totalShares,c=i.threshold,l=n.nextOddPrime(o)-1,d=n.pkcs7Pad(s.value,l),{key:u,signature:p}=await n.generateHMAC(d);let y;r?.update("Splitting message into shares...",60);try{y=n.splitXorIDA(d,o,c)}catch{return err("ENVELOPE_FAILED:SPLIT")}const h=toBase64(u),E=toBase64(p),m=generateUUID(),g=[];r?.update("Sending shares...",70);for(let t=0;t<y.length;t++){const i=y[t],a=formatShareHeader(toBase64(i)),s=(new TextEncoder).encode(a),n=await createEnvelopeV4({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,shareData:s,privateKey:this.identity.privateKey,shareIndex:t,shareTotal:o,shareThreshold:c,shareGroupId:m,shareHmacKey:h,shareHmacSig:E});if(!n.ok){g.push(err("ENVELOPE_FAILED:ENCRYPT"));continue}const l=this.transports[t%this.transports.length],d=await l.send(n.value,e.to);g.push(d);const u=70+Math.floor((t+1)/y.length*20);r?.update(`Sent share ${t+1}/${y.length}...`,u)}return g.filter(e=>e.ok).length<c?err("SEND_FAILED:BELOW_THRESHOLD"):(r?.complete(),ok(void 0))}async sendSplitChannel(e,t,r,i,a,s,n){const o=e.splitChannelConfig??DEFAULT_SPLIT_CONFIG;this.transports.length<o.totalShares&&console.warn(`Split-channel: ${o.totalShares} shares but only ${this.transports.length} transport(s). For channel separation, provide at least ${o.totalShares} transports.`),n?.update("Splitting message into shares...",50);const c=await splitForChannel(t,o);if(!c.ok)return err("ENVELOPE_FAILED:SPLIT");const l=c.value;n?.update("Encrypting and sending shares...",70);return(await this.sendShareEnvelopes(e,l,r,i,a,s,n)).filter(e=>e.ok).length<o.threshold?err("SEND_FAILED:BELOW_THRESHOLD"):(n?.complete(),ok(void 0))}async sendShareEnvelopes(e,t,r,i,a,s,n){const o=[];for(let c=0;c<t.length;c++){const l=t[c],d=(new TextEncoder).encode(l.data);let u;if(u=a&&i&&s&&this.identity.mlDsaSecretKey?await createEnvelopeV3({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:a,mlDsaSecretKey:this.identity.mlDsaSecretKey,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}):a&&i?await createEnvelopeV2({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,kemCiphertext:a,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}):await createEnvelope({senderDid:this.identity.did,recipientDid:e.to,scope:e.scope,plaintext:d,privateKey:this.identity.privateKey,sharedKey:r,ephemeralPublicKey:i,shareIndex:l.index,shareTotal:l.total,shareThreshold:l.threshold,shareGroupId:l.groupId,shareHmacKey:l.hmacKey,shareHmacSig:l.hmacSig}),!u.ok){o.push(err("ENVELOPE_FAILED:ENCRYPT"));continue}const p=this.transports[c%this.transports.length],y=await p.send(u.value,e.to);o.push(y);const h=70+Math.floor((c+1)/t.length*20);n?.update(`Sent share ${c+1}/${t.length}...`,h)}return o}async receiveSplitShare(e){if(void 0===e.shareGroupId)return err("VERIFICATION_FAILED");const t=await this.receiveRaw(e);if(!t.ok)return t;const{sender:r,decryptedText:i,scope:a,timestamp:s}=t.value,n={data:i,index:e.shareIndex??0,total:e.shareTotal??2,threshold:e.shareThreshold??2,groupId:e.shareGroupId,hmacKey:e.shareHmacKey??"",hmacSig:e.shareHmacSig??""};return this.accumulateShare(n,r,a,s)}async receiveXchangeShare(e){this.lastDetail="";const t=await this.verifyEnvelope(e);if(!t.ok)return t;const r={data:(new TextDecoder).decode(t.value.payloadBytes),index:e.shareIndex,total:e.shareTotal,threshold:e.shareThreshold,groupId:e.shareGroupId,hmacKey:e.shareHmacKey,hmacSig:e.shareHmacSig};return this.accumulateXchangeShare(r,e.sender,e.scope,e.timestamp)}async accumulateXchangeShare(e,t,r,i){const a=this.shareAccumulator.get(e.groupId)??[];if(a.some(t=>t.index===e.index)||(a.push(e),this.shareAccumulator.set(e.groupId,a)),a.length<e.threshold)return ok(null);this.shareAccumulator.delete(e.groupId);const s=a.slice(0,e.threshold),n=e.total,o=e.threshold;let c;try{c=s.map(e=>fromBase64(parseShareHeader(e.data)))}catch{return err("DECRYPT_FAILED")}const l=s.map(e=>e.index),d=await this.ensureCrypto();let u,p,y;try{u=d.reconstructXorIDA(c,l,n,o)}catch{return err("DECRYPT_FAILED")}try{p=fromBase64(s[0].hmacKey),y=fromBase64(s[0].hmacSig)}catch{return err("DECRYPT_FAILED")}if(!await d.verifyHMAC(p,u,y))return this.lastDetail="HMAC verification failed before decrypt",err("DECRYPT_FAILED");const h=d.nextOddPrime(n)-1,E=d.pkcs7Unpad(u,h);if(!E.ok)return err("DECRYPT_FAILED");const m=await xchangeDecrypt(E.value);if(!m.ok)return err("DECRYPT_FAILED:DECRYPTION");let g;try{g=JSON.parse((new TextDecoder).decode(m.value))}catch{return err("DECRYPT_FAILED:PARSE")}return ok({sender:t,payload:g,scope:r,timestamp:i})}async accumulateShare(e,t,r,i){const a=this.shareAccumulator.get(e.groupId)??[];if(a.some(t=>t.index===e.index)||(a.push(e),this.shareAccumulator.set(e.groupId,a)),a.length<e.threshold)return ok(null);this.shareAccumulator.delete(e.groupId);const s=await reconstructFromChannel(a);if(!s.ok)return err("DECRYPT_FAILED");let n;try{n=JSON.parse((new TextDecoder).decode(s.value))}catch{return err("DECRYPT_FAILED")}return ok({sender:t,payload:n,scope:r,timestamp:i})}async verifyEnvelope(e){if(!e||"object"!=typeof e)return this.lastDetail="envelope is null or not an object",err("VERIFICATION_FAILED:INVALID_ENVELOPE");if(1!==e.v&&2!==e.v&&3!==e.v&&4!==e.v||"Ed25519"!==e.alg)return this.lastDetail=`v=${String(e.v)}, alg=${String(e.alg)}`,err("VERIFICATION_FAILED:UNSUPPORTED_VERSION");if("number"!=typeof e.timestamp||!Number.isFinite(e.timestamp))return this.lastDetail=`timestamp=${String(e.timestamp)} (must be finite number)`,err("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=Math.abs(Date.now()-e.timestamp);if(t>this.timestampWindowMs)return this.lastDetail=`age=${t}ms, max=${this.timestampWindowMs}ms`,err("TIMESTAMP_EXPIRED");const r=void 0!==e.shareGroupId?{shareGroupId:e.shareGroupId,shareIndex:e.shareIndex}:void 0;if(!await this.nonceStore.check(e.nonce,e.sender,r))return this.lastDetail=`nonce=${e.nonce}`,err("REPLAY_DETECTED");const i=await this.registry.resolve(e.sender);if(!i.ok)return this.lastDetail=`did=${e.sender}`,err("VERIFICATION_FAILED:DID_NOT_IN_REGISTRY");const a=await importPublicKey(i.value);if(!a.ok)return this.lastDetail=`did=${e.sender}`,err("VERIFICATION_FAILED:KEY_IMPORT_FAILED");if(!e.signature||"string"!=typeof e.signature)return this.lastDetail="signature field missing or invalid",err("VERIFICATION_FAILED:SIGNATURE_MISMATCH");const s=fromBase64(e.signature),n=JSON.stringify({v:e.v,alg:e.alg,sender:e.sender,recipient:e.recipient,timestamp:e.timestamp,nonce:e.nonce,scope:e.scope,payload:e.payload}),o=(new TextEncoder).encode(n),c=await verify(a.value,s,o);if(!c.ok||!c.value)return this.lastDetail="signature does not match canonical envelope (v1.1.3+ required)",err("VERIFICATION_FAILED:SIGNATURE_MISMATCH");if(3===e.v&&"pqSignature"in e){if("string"!=typeof e.pqSignature)return this.lastDetail="pqSignature field not a string",err("VERIFICATION_FAILED:INVALID_ENVELOPE");const t=await this.registry.getEntry(e.sender);if(!t.ok||!t.value.mlDsaPublicKey)return this.lastDetail=`did=${e.sender} missing ML-DSA public key`,err("VERIFICATION_FAILED:PQ_KEY_MISSING");const r=fromBase64(e.pqSignature),i=await verifyMlDsa65(t.value.mlDsaPublicKey,r,o);if(!i.ok||!i.value)return this.lastDetail="ML-DSA-65 signature does not match canonical envelope (v1.1.3+ required)",err("VERIFICATION_FAILED:PQ_SIGNATURE_MISMATCH")}if(!await this.registry.hasScope(e.sender,e.scope))return this.lastDetail=`scope=${e.scope}`,err("SCOPE_DENIED");if("string"!=typeof e.payload)return this.lastDetail="payload field not a string",err("VERIFICATION_FAILED:INVALID_ENVELOPE");const l=fromBase64(e.payload);return ok({senderRawKey:i.value,payloadBytes:l})}async receiveRaw(e){const t=await this.verifyEnvelope(e);if(!t.ok)return t;const{senderRawKey:r}=t.value;if(4===e.v)return err("VERIFICATION_FAILED:UNSUPPORTED_VERSION");let i;if(2!==e.v&&3!==e.v||!("kemCiphertext"in e)){if(!e.ephemeralPub)return err("DECRYPT_FAILED:NO_EPHEMERAL_KEY");{if("string"!=typeof e.ephemeralPub)return err("DECRYPT_FAILED:INVALID_ENVELOPE");const t=fromBase64(e.ephemeralPub),r=await receiverKeyAgreement(this.identity.x25519PrivateKey,t);if(r.ok)i=r.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){const r=await receiverKeyAgreement(e.x25519PrivateKey,t);if(r.ok){i=r.value;break}}if(!i)return err("DECRYPT_FAILED:KEY_AGREEMENT")}}}else{if(!this.identity.mlKemSecretKey)return err("DECRYPT_FAILED:KEY_AGREEMENT");if("string"!=typeof e.ephemeralPub||"string"!=typeof e.kemCiphertext)return err("DECRYPT_FAILED:INVALID_ENVELOPE");const t=fromBase64(e.ephemeralPub),r=fromBase64(e.kemCiphertext);if(!this.identity.mlKemPublicKey||!this.identity.mlKemSecretKey)return this.lastDetail="ML-KEM keys not available in identity",err("DECRYPT_FAILED:MISSING_MLKEM_KEYS");const a=await receiverHybridKeyAgreement(this.identity.x25519PrivateKey,this.identity.rawX25519PublicKey,t,r,this.identity.mlKemSecretKey,this.identity.mlKemPublicKey);if(a.ok)i=a.value;else{if(this.identity.rotatedKeys&&this.identity.rotatedKeys.length>0)for(const e of this.identity.rotatedKeys){if(!e.mlKemSecretKey)continue;const a=await receiverHybridKeyAgreement(e.x25519PrivateKey,this.identity.rawX25519PublicKey,t,r,e.mlKemSecretKey,this.identity.mlKemPublicKey);if(a.ok){i=a.value;break}}if(!i)return err("DECRYPT_FAILED:KEY_AGREEMENT")}}if(!i)return err("DECRYPT_FAILED:KEY_AGREEMENT");const a=await decryptPayload(e,i);if(!a.ok)return err("DECRYPT_FAILED:DECRYPTION");const s=(new TextDecoder).decode(a.value);return ok({sender:e.sender,decryptedText:s,scope:e.scope,timestamp:e.timestamp})}async createTestEnvelope(e,t,r){const i=await this.registry.getEntry(e);if(!i.ok||!i.value.x25519PublicKey)return null;const a=await importX25519PublicKey(i.value.x25519PublicKey);if(!a.ok)return null;const s=await senderKeyAgreement(a.value);if(!s.ok)return null;const n=(new TextEncoder).encode(JSON.stringify(t)),o=await createEnvelope({senderDid:this.identity.did,recipientDid:e,scope:r,plaintext:n,privateKey:this.identity.privateKey,sharedKey:s.value.sharedKey,ephemeralPublicKey:s.value.ephemeralPublicKey});return o.ok?o.value:null}async invite(e){if(!this.transports||0===this.transports.length)return err("SEND_FAILED");const t=Buffer.from(this.identity.rawPublicKey).toString("base64"),r={from:this.identity.did,to:e.to,payload:{agentName:this.name,message:e.message,publicKey:t,endpoint:""}},i=this.transports[0];if(!i)return err("SEND_FAILED");return(await i.send(r,e.to)).ok?ok(void 0):err("SEND_FAILED")}}export{generateSharedKey};