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