@private.me/xbind 1.2.0

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