@private.me/xbind 1.3.0 → 2.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/LICENSES.md +212 -0
  2. package/README.md +388 -6
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -275
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -138
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -90
  7. package/dist-standalone/_deps/shared/errors.js +1 -262
  8. package/dist-standalone/_deps/shared/index.js +1 -77
  9. package/dist-standalone/_deps/shared/types.js +1 -91
  10. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  20. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  21. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  28. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  29. package/dist-standalone/_deps/xchange/errors.js +1 -1
  30. package/dist-standalone/_deps/xchange/index.js +1 -1
  31. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  32. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  33. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  34. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  40. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  41. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  42. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  43. package/dist-standalone/_deps/xregistry/index.js +1 -1
  44. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  45. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  46. package/dist-standalone/_deps/xregistry/types.js +1 -1
  47. package/dist-standalone/agent-call.js +1 -642
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +95 -5
  50. package/dist-standalone/agent.js +1 -1545
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +275 -0
  53. package/dist-standalone/async-iterators.js +1 -0
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.d.ts +114 -0
  58. package/dist-standalone/backup.js +1 -0
  59. package/dist-standalone/batch-operations.d.ts +297 -0
  60. package/dist-standalone/batch-operations.js +1 -0
  61. package/dist-standalone/cancellation.d.ts +301 -0
  62. package/dist-standalone/cancellation.js +1 -0
  63. package/dist-standalone/checkpoint.js +1 -186
  64. package/dist-standalone/circuit-breaker.d.ts +351 -0
  65. package/dist-standalone/circuit-breaker.js +1 -0
  66. package/dist-standalone/cjs/agent-call.js +1 -651
  67. package/dist-standalone/cjs/agent-sdk.js +1 -332
  68. package/dist-standalone/cjs/agent.js +1 -1582
  69. package/dist-standalone/cjs/approval.js +1 -199
  70. package/dist-standalone/cjs/async-iterators.js +1 -0
  71. package/dist-standalone/cjs/auth.js +1 -225
  72. package/dist-standalone/cjs/auto-accept.js +1 -233
  73. package/dist-standalone/cjs/backup-config.js +1 -207
  74. package/dist-standalone/cjs/backup.js +1 -0
  75. package/dist-standalone/cjs/batch-operations.js +1 -0
  76. package/dist-standalone/cjs/cancellation.js +1 -0
  77. package/dist-standalone/cjs/checkpoint.js +1 -193
  78. package/dist-standalone/cjs/circuit-breaker.js +1 -0
  79. package/dist-standalone/cjs/cli/init.js +1 -486
  80. package/dist-standalone/cjs/config-validation.js +1 -0
  81. package/dist-standalone/cjs/connect.js +1 -312
  82. package/dist-standalone/cjs/connection-pool.js +1 -0
  83. package/dist-standalone/cjs/correlation-id.js +1 -339
  84. package/dist-standalone/cjs/crypto-utils.js +1 -0
  85. package/dist-standalone/cjs/debug-mode.js +1 -0
  86. package/dist-standalone/cjs/did-document.js +1 -101
  87. package/dist-standalone/cjs/did-privateme.js +1 -130
  88. package/dist-standalone/cjs/did-web.js +1 -201
  89. package/dist-standalone/cjs/discovery.js +1 -462
  90. package/dist-standalone/cjs/dual-mode.js +1 -251
  91. package/dist-standalone/cjs/email-templates.js +1 -313
  92. package/dist-standalone/cjs/email-transport.js +1 -239
  93. package/dist-standalone/cjs/envelope.js +1 -510
  94. package/dist-standalone/cjs/errors.js +1 -826
  95. package/dist-standalone/cjs/event-emitter.js +1 -0
  96. package/dist-standalone/cjs/gateway-state.js +1 -55
  97. package/dist-standalone/cjs/gateway-transport.js +1 -120
  98. package/dist-standalone/cjs/graceful-degradation.js +1 -0
  99. package/dist-standalone/cjs/guardrails.js +1 -223
  100. package/dist-standalone/cjs/health-check.js +1 -0
  101. package/dist-standalone/cjs/http-compat.js +1 -272
  102. package/dist-standalone/cjs/http-status-map.js +1 -571
  103. package/dist-standalone/cjs/identity.js +1 -541
  104. package/dist-standalone/cjs/index.js +1 -237
  105. package/dist-standalone/cjs/invitation.js +1 -421
  106. package/dist-standalone/cjs/invite.js +1 -328
  107. package/dist-standalone/cjs/key-agreement.js +1 -246
  108. package/dist-standalone/cjs/lazy-init.js +1 -300
  109. package/dist-standalone/cjs/logger.js +1 -0
  110. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  111. package/dist-standalone/cjs/nonce-store.js +1 -66
  112. package/dist-standalone/cjs/pairing-manager.js +1 -223
  113. package/dist-standalone/cjs/plugin-system.js +1 -0
  114. package/dist-standalone/cjs/plugins/logging.js +1 -0
  115. package/dist-standalone/cjs/plugins/metrics.js +1 -0
  116. package/dist-standalone/cjs/plugins/validation.js +1 -0
  117. package/dist-standalone/cjs/policy.js +1 -320
  118. package/dist-standalone/cjs/progress-callbacks.js +1 -0
  119. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  120. package/dist-standalone/cjs/registry-middleware.js +1 -50
  121. package/dist-standalone/cjs/retry-strategies.js +1 -0
  122. package/dist-standalone/cjs/retry-transport.js +1 -102
  123. package/dist-standalone/cjs/runtime/browser.js +1 -0
  124. package/dist-standalone/cjs/runtime/edge.js +1 -0
  125. package/dist-standalone/cjs/runtime/react-native.js +1 -0
  126. package/dist-standalone/cjs/security-policy.js +1 -245
  127. package/dist-standalone/cjs/serialization.js +1 -0
  128. package/dist-standalone/cjs/split-channel.js +1 -177
  129. package/dist-standalone/cjs/subscription-proof.js +1 -230
  130. package/dist-standalone/cjs/succession.js +1 -148
  131. package/dist-standalone/cjs/timeouts.js +1 -0
  132. package/dist-standalone/cjs/trace-context.js +1 -0
  133. package/dist-standalone/cjs/trace-spans.js +1 -0
  134. package/dist-standalone/cjs/transport.js +1 -63
  135. package/dist-standalone/cjs/trust-registry.js +1 -742
  136. package/dist-standalone/cjs/types/error-response.js +1 -56
  137. package/dist-standalone/cjs/vault-auth.js +1 -0
  138. package/dist-standalone/cjs/vault-store-loader.js +1 -0
  139. package/dist-standalone/cjs/verify.js +1 -25
  140. package/dist-standalone/cjs/version-info.js +1 -0
  141. package/dist-standalone/cjs/xfetch.js +1 -252
  142. package/dist-standalone/cli/init.js +1 -449
  143. package/dist-standalone/cli/setup.js +1 -514
  144. package/dist-standalone/cli/types.js +1 -27
  145. package/dist-standalone/cli/xbind.js +1 -148
  146. package/dist-standalone/config-validation.d.ts +185 -0
  147. package/dist-standalone/config-validation.js +1 -0
  148. package/dist-standalone/connect.js +1 -274
  149. package/dist-standalone/connection-pool.d.ts +251 -0
  150. package/dist-standalone/connection-pool.js +1 -0
  151. package/dist-standalone/correlation-id.js +1 -326
  152. package/dist-standalone/crypto-utils.d.ts +60 -0
  153. package/dist-standalone/crypto-utils.js +1 -0
  154. package/dist-standalone/debug-mode.d.ts +286 -0
  155. package/dist-standalone/debug-mode.js +1 -0
  156. package/dist-standalone/did-document.js +1 -96
  157. package/dist-standalone/did-privateme.js +1 -121
  158. package/dist-standalone/did-web.js +1 -196
  159. package/dist-standalone/discovery.js +1 -458
  160. package/dist-standalone/dual-mode.js +1 -247
  161. package/dist-standalone/email-templates.js +1 -309
  162. package/dist-standalone/email-transport.js +1 -232
  163. package/dist-standalone/envelope.d.ts +29 -1
  164. package/dist-standalone/envelope.js +1 -497
  165. package/dist-standalone/errors.d.ts +10 -0
  166. package/dist-standalone/errors.js +1 -811
  167. package/dist-standalone/event-emitter.d.ts +395 -0
  168. package/dist-standalone/event-emitter.js +1 -0
  169. package/dist-standalone/gateway-state.js +1 -51
  170. package/dist-standalone/gateway-transport.js +1 -116
  171. package/dist-standalone/graceful-degradation.d.ts +246 -0
  172. package/dist-standalone/graceful-degradation.js +1 -0
  173. package/dist-standalone/guardrails.js +1 -216
  174. package/dist-standalone/health-check.d.ts +150 -0
  175. package/dist-standalone/health-check.js +1 -0
  176. package/dist-standalone/http-compat.js +1 -267
  177. package/dist-standalone/http-status-map.js +1 -561
  178. package/dist-standalone/identity.d.ts +64 -1
  179. package/dist-standalone/identity.js +1 -516
  180. package/dist-standalone/index.d.ts +45 -3
  181. package/dist-standalone/index.js +1 -52
  182. package/dist-standalone/invitation.js +1 -415
  183. package/dist-standalone/invite.js +1 -324
  184. package/dist-standalone/key-agreement.d.ts +61 -13
  185. package/dist-standalone/key-agreement.js +1 -236
  186. package/dist-standalone/lazy-init.js +1 -295
  187. package/dist-standalone/logger.d.ts +77 -0
  188. package/dist-standalone/logger.js +1 -0
  189. package/dist-standalone/mdns-discovery.js +1 -195
  190. package/dist-standalone/nonce-store.d.ts +16 -3
  191. package/dist-standalone/nonce-store.js +1 -62
  192. package/dist-standalone/package.json +0 -1
  193. package/dist-standalone/pairing-manager.js +1 -219
  194. package/dist-standalone/plugin-system.d.ts +145 -0
  195. package/dist-standalone/plugin-system.js +1 -0
  196. package/dist-standalone/policy.js +1 -315
  197. package/dist-standalone/progress-callbacks.d.ts +394 -0
  198. package/dist-standalone/progress-callbacks.js +1 -0
  199. package/dist-standalone/redis-nonce-store.js +1 -72
  200. package/dist-standalone/registry-middleware.js +1 -47
  201. package/dist-standalone/retry-strategies.d.ts +382 -0
  202. package/dist-standalone/retry-strategies.js +1 -0
  203. package/dist-standalone/retry-transport.js +1 -98
  204. package/dist-standalone/security-policy.js +1 -239
  205. package/dist-standalone/serialization.d.ts +244 -0
  206. package/dist-standalone/serialization.js +1 -0
  207. package/dist-standalone/split-channel.d.ts +49 -1
  208. package/dist-standalone/split-channel.js +1 -171
  209. package/dist-standalone/subscription-proof.js +1 -224
  210. package/dist-standalone/succession.js +1 -142
  211. package/dist-standalone/timeouts.d.ts +275 -0
  212. package/dist-standalone/timeouts.js +1 -0
  213. package/dist-standalone/trace-context.d.ts +252 -0
  214. package/dist-standalone/trace-context.js +1 -0
  215. package/dist-standalone/trace-spans.d.ts +360 -0
  216. package/dist-standalone/trace-spans.js +1 -0
  217. package/dist-standalone/transport.js +1 -59
  218. package/dist-standalone/trust-registry.d.ts +106 -5
  219. package/dist-standalone/trust-registry.js +1 -702
  220. package/dist-standalone/vault-auth.d.ts +91 -0
  221. package/dist-standalone/vault-auth.js +1 -0
  222. package/dist-standalone/vault-store-loader.d.ts +110 -0
  223. package/dist-standalone/vault-store-loader.js +1 -0
  224. package/dist-standalone/verify.js +1 -16
  225. package/dist-standalone/version-info.d.ts +259 -0
  226. package/dist-standalone/version-info.js +1 -0
  227. package/dist-standalone/xfetch.js +1 -247
  228. package/llms.txt +1 -0
  229. package/package.json +66 -5
  230. package/share1.dat +0 -0
  231. package/dist-standalone/_deps/crypto/base64.d.ts +0 -29
  232. package/dist-standalone/_deps/crypto/base64.js +0 -209
  233. package/dist-standalone/_deps/crypto/cjs/base64.js +0 -103
  234. package/dist-standalone/_deps/crypto/cjs/errors.js +0 -119
  235. package/dist-standalone/_deps/crypto/cjs/hmac.js +0 -71
  236. package/dist-standalone/_deps/crypto/cjs/index.js +0 -86
  237. package/dist-standalone/_deps/crypto/cjs/padding.js +0 -57
  238. package/dist-standalone/_deps/crypto/cjs/share-header.js +0 -68
  239. package/dist-standalone/_deps/crypto/cjs/shares.js +0 -152
  240. package/dist-standalone/_deps/crypto/cjs/tlv.js +0 -199
  241. package/dist-standalone/_deps/crypto/cjs/uuid.js +0 -61
  242. package/dist-standalone/_deps/crypto/cjs/verify.js +0 -24
  243. package/dist-standalone/_deps/crypto/cjs/xorida.js +0 -221
  244. package/dist-standalone/_deps/crypto/errors.d.ts +0 -51
  245. package/dist-standalone/_deps/crypto/errors.js +0 -109
  246. package/dist-standalone/_deps/crypto/hmac.d.ts +0 -39
  247. package/dist-standalone/_deps/crypto/hmac.js +0 -66
  248. package/dist-standalone/_deps/crypto/index.d.ts +0 -20
  249. package/dist-standalone/_deps/crypto/index.js +0 -45
  250. package/dist-standalone/_deps/crypto/padding.d.ts +0 -19
  251. package/dist-standalone/_deps/crypto/padding.js +0 -53
  252. package/dist-standalone/_deps/crypto/share-header.d.ts +0 -44
  253. package/dist-standalone/_deps/crypto/share-header.js +0 -63
  254. package/dist-standalone/_deps/crypto/shares.d.ts +0 -27
  255. package/dist-standalone/_deps/crypto/shares.js +0 -148
  256. package/dist-standalone/_deps/crypto/tlv.d.ts +0 -26
  257. package/dist-standalone/_deps/crypto/tlv.js +0 -195
  258. package/dist-standalone/_deps/crypto/uuid.d.ts +0 -22
  259. package/dist-standalone/_deps/crypto/uuid.js +0 -56
  260. package/dist-standalone/_deps/crypto/verify.d.ts +0 -15
  261. package/dist-standalone/_deps/crypto/verify.js +0 -15
  262. package/dist-standalone/_deps/crypto/xorida.d.ts +0 -44
  263. package/dist-standalone/_deps/crypto/xorida.js +0 -215
  264. package/dist-standalone/_deps/shared/errors.d.ts.map +0 -1
  265. package/dist-standalone/_deps/shared/errors.js.map +0 -1
  266. package/dist-standalone/_deps/shared/index.d.ts.map +0 -1
  267. package/dist-standalone/_deps/shared/index.js.map +0 -1
  268. package/dist-standalone/_deps/shared/types.d.ts.map +0 -1
  269. package/dist-standalone/_deps/shared/types.js.map +0 -1
  270. package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts.map +0 -1
  271. package/dist-standalone/_deps/ux-helpers/cjs/errors.js.map +0 -1
  272. package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts.map +0 -1
  273. package/dist-standalone/_deps/ux-helpers/cjs/index.js.map +0 -1
  274. package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts.map +0 -1
  275. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js.map +0 -1
  276. package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts.map +0 -1
  277. package/dist-standalone/_deps/ux-helpers/cjs/progress.js.map +0 -1
  278. package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts.map +0 -1
  279. package/dist-standalone/_deps/ux-helpers/cjs/search.js.map +0 -1
  280. package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts.map +0 -1
  281. package/dist-standalone/_deps/ux-helpers/cjs/types.js.map +0 -1
  282. package/dist-standalone/_deps/ux-helpers/errors.d.ts.map +0 -1
  283. package/dist-standalone/_deps/ux-helpers/errors.js.map +0 -1
  284. package/dist-standalone/_deps/ux-helpers/index.d.ts.map +0 -1
  285. package/dist-standalone/_deps/ux-helpers/index.js.map +0 -1
  286. package/dist-standalone/_deps/ux-helpers/pagination.d.ts.map +0 -1
  287. package/dist-standalone/_deps/ux-helpers/pagination.js.map +0 -1
  288. package/dist-standalone/_deps/ux-helpers/progress.d.ts.map +0 -1
  289. package/dist-standalone/_deps/ux-helpers/progress.js.map +0 -1
  290. package/dist-standalone/_deps/ux-helpers/search.d.ts.map +0 -1
  291. package/dist-standalone/_deps/ux-helpers/search.js.map +0 -1
  292. package/dist-standalone/_deps/ux-helpers/types.d.ts.map +0 -1
  293. package/dist-standalone/_deps/ux-helpers/types.js.map +0 -1
  294. package/dist-standalone/_deps/xregistry/discovery.d.ts.map +0 -1
  295. package/dist-standalone/_deps/xregistry/discovery.js.map +0 -1
  296. package/dist-standalone/_deps/xregistry/errors.d.ts.map +0 -1
  297. package/dist-standalone/_deps/xregistry/errors.js.map +0 -1
  298. package/dist-standalone/_deps/xregistry/index.d.ts.map +0 -1
  299. package/dist-standalone/_deps/xregistry/index.js.map +0 -1
  300. package/dist-standalone/_deps/xregistry/registry.d.ts.map +0 -1
  301. package/dist-standalone/_deps/xregistry/registry.js.map +0 -1
  302. package/dist-standalone/_deps/xregistry/schema.d.ts.map +0 -1
  303. package/dist-standalone/_deps/xregistry/schema.js.map +0 -1
  304. package/dist-standalone/_deps/xregistry/types.d.ts.map +0 -1
  305. package/dist-standalone/_deps/xregistry/types.js.map +0 -1
@@ -1,207 +1 @@
1
- "use strict";
2
- /**
3
- * XorIDA Backup Configuration for Key Splitting
4
- *
5
- * Provides default backup configuration (k=2, n=3) and utilities for
6
- * splitting cryptographic keys across multiple shares using information-
7
- * theoretic threshold secret sharing.
8
- *
9
- * @module backup-config
10
- */
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.DEFAULT_BACKUP_CONFIG = void 0;
13
- exports.validateBackupConfig = validateBackupConfig;
14
- exports.splitKeyWithBackup = splitKeyWithBackup;
15
- exports.reconstructKeyFromBackup = reconstructKeyFromBackup;
16
- const shared_1 = require("../_deps/shared/index.js");
17
- const crypto_1 = require("../_deps/crypto/index.js");
18
- /* ── Constants ── */
19
- /**
20
- * Default backup configuration: 2-of-3 threshold sharing.
21
- *
22
- * - 3 shares generated
23
- * - Any 2 shares can reconstruct the key
24
- * - Lose 1 share and still recover (fault tolerance)
25
- * - Information-theoretic security (each share reveals zero information)
26
- */
27
- exports.DEFAULT_BACKUP_CONFIG = {
28
- threshold: 2,
29
- totalShares: 3,
30
- };
31
- /* ── Validation ── */
32
- /**
33
- * Validate backup configuration parameters.
34
- *
35
- * Rules:
36
- * - threshold must be >= 2 (single share = no threshold)
37
- * - totalShares must be >= threshold
38
- * - totalShares must be <= 255 (XorIDA limit)
39
- *
40
- * @param config - Backup configuration to validate.
41
- * @returns Ok if valid, error otherwise.
42
- */
43
- function validateBackupConfig(config) {
44
- if (config.threshold < 2) {
45
- return (0, shared_1.err)('INVALID_CONFIG');
46
- }
47
- if (config.totalShares < config.threshold) {
48
- return (0, shared_1.err)('INVALID_CONFIG');
49
- }
50
- if (config.totalShares > 255) {
51
- return (0, shared_1.err)('INVALID_CONFIG');
52
- }
53
- return (0, shared_1.ok)(undefined);
54
- }
55
- /* ── Key Splitting ── */
56
- /**
57
- * Split a cryptographic key into backup shares using XorIDA.
58
- *
59
- * The key is padded, split via information-theoretic threshold sharing,
60
- * and returned as BackupShare objects with HMAC integrity protection.
61
- *
62
- * Any `threshold` shares can reconstruct the original key. Each share
63
- * reveals zero information about the key (information-theoretic security).
64
- *
65
- * @param key - The key to split (32 or 64 bytes typical).
66
- * @param config - Backup configuration (defaults to 2-of-3).
67
- * @returns Array of backup shares or error.
68
- *
69
- * @example
70
- * ```typescript
71
- * import { splitKeyWithBackup, DEFAULT_BACKUP_CONFIG } from '@private.me/xbind';
72
- *
73
- * const key = crypto.getRandomValues(new Uint8Array(32));
74
- *
75
- * // Use defaults (2-of-3)
76
- * const shares = await splitKeyWithBackup(key);
77
- *
78
- * // Custom config (3-of-5)
79
- * const shares2 = await splitKeyWithBackup(key, {
80
- * threshold: 3,
81
- * totalShares: 5
82
- * });
83
- *
84
- * if (shares.ok) {
85
- * // Store shares in separate locations
86
- * shares.value.forEach((share, i) => {
87
- * storeShare(`backup-${i}.json`, JSON.stringify(share));
88
- * });
89
- * }
90
- * ```
91
- */
92
- async function splitKeyWithBackup(key, config = exports.DEFAULT_BACKUP_CONFIG) {
93
- const validation = validateBackupConfig(config);
94
- if (!validation.ok)
95
- return validation;
96
- if (key.length === 0) {
97
- return (0, shared_1.err)('INVALID_KEY_LENGTH');
98
- }
99
- const n = config.totalShares;
100
- const k = config.threshold;
101
- const p = (0, crypto_1.nextOddPrime)(n);
102
- const blockSize = p - 1;
103
- // Pad to block size
104
- const padded = (0, crypto_1.pkcs7Pad)(key, blockSize);
105
- // Generate HMAC for integrity verification
106
- const { key: hmacKey, signature: hmacSig } = await (0, crypto_1.generateHMAC)(padded);
107
- const hmacKeyB64 = (0, crypto_1.toBase64)(hmacKey);
108
- const hmacSigB64 = (0, crypto_1.toBase64)(hmacSig);
109
- // Split via XorIDA
110
- let shareArrays;
111
- try {
112
- shareArrays = (0, crypto_1.splitXorIDA)(padded, n, k);
113
- }
114
- catch {
115
- return (0, shared_1.err)('SPLIT_FAILED');
116
- }
117
- // Package as BackupShare objects
118
- const shares = shareArrays.map((data, index) => ({
119
- index,
120
- data: (0, crypto_1.toBase64)(data),
121
- total: n,
122
- threshold: k,
123
- hmacKey: hmacKeyB64,
124
- hmacSig: hmacSigB64,
125
- }));
126
- return (0, shared_1.ok)(shares);
127
- }
128
- /* ── Key Reconstruction ── */
129
- /**
130
- * Reconstruct a cryptographic key from backup shares.
131
- *
132
- * Requires at least `threshold` shares. Verifies HMAC before returning
133
- * the reconstructed key to prevent tampering.
134
- *
135
- * @param shares - Backup shares (must be >= threshold).
136
- * @returns Reconstructed key or error.
137
- *
138
- * @example
139
- * ```typescript
140
- * import { reconstructKeyFromBackup } from '@private.me/xbind';
141
- *
142
- * // Load shares from storage
143
- * const share0 = JSON.parse(loadShare('backup-0.json'));
144
- * const share1 = JSON.parse(loadShare('backup-1.json'));
145
- *
146
- * // Reconstruct from any 2 shares (threshold=2)
147
- * const key = await reconstructKeyFromBackup([share0, share1]);
148
- *
149
- * if (key.ok) {
150
- * // Use reconstructed key
151
- * const agent = await Agent.fromSeed(key.value, opts);
152
- * } else {
153
- * console.error('Reconstruction failed:', key.error);
154
- * }
155
- * ```
156
- */
157
- async function reconstructKeyFromBackup(shares) {
158
- if (shares.length === 0) {
159
- return (0, shared_1.err)('INSUFFICIENT_SHARES');
160
- }
161
- const threshold = shares[0].threshold;
162
- const total = shares[0].total;
163
- if (shares.length < threshold) {
164
- return (0, shared_1.err)('INSUFFICIENT_SHARES');
165
- }
166
- // Use first `threshold` shares
167
- const usedShares = shares.slice(0, threshold);
168
- // Decode share data
169
- let shareData;
170
- try {
171
- shareData = usedShares.map((s) => (0, crypto_1.fromBase64)(s.data));
172
- }
173
- catch {
174
- return (0, shared_1.err)('INVALID_SHARE_DATA');
175
- }
176
- const indices = usedShares.map((s) => s.index);
177
- // Reconstruct padded key
178
- let padded;
179
- try {
180
- padded = (0, crypto_1.reconstructXorIDA)(shareData, indices, total, threshold);
181
- }
182
- catch {
183
- return (0, shared_1.err)('RECONSTRUCT_FAILED');
184
- }
185
- // Verify HMAC
186
- let hmacKey;
187
- let hmacSig;
188
- try {
189
- hmacKey = (0, crypto_1.fromBase64)(usedShares[0].hmacKey);
190
- hmacSig = (0, crypto_1.fromBase64)(usedShares[0].hmacSig);
191
- }
192
- catch {
193
- return (0, shared_1.err)('INVALID_SHARE_DATA');
194
- }
195
- const hmacValid = await (0, crypto_1.verifyHMAC)(hmacKey, padded, hmacSig);
196
- if (!hmacValid) {
197
- return (0, shared_1.err)('HMAC_VERIFICATION_FAILED');
198
- }
199
- // Unpad to recover original key
200
- const p = (0, crypto_1.nextOddPrime)(total);
201
- const blockSize = p - 1;
202
- const unpadResult = (0, crypto_1.pkcs7Unpad)(padded, blockSize);
203
- if (!unpadResult.ok) {
204
- return (0, shared_1.err)('RECONSTRUCT_FAILED');
205
- }
206
- return (0, shared_1.ok)(unpadResult.value);
207
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DEFAULT_BACKUP_CONFIG=void 0,exports.validateBackupConfig=validateBackupConfig,exports.splitKeyWithBackup=splitKeyWithBackup,exports.reconstructKeyFromBackup=reconstructKeyFromBackup;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js");function validateBackupConfig(t){return t.threshold<2||t.totalShares<t.threshold||t.totalShares>255?(0,shared_1.err)("INVALID_CONFIG"):(0,shared_1.ok)(void 0)}async function splitKeyWithBackup(t,r=exports.DEFAULT_BACKUP_CONFIG){const e=validateBackupConfig(r);if(!e.ok)return e;if(0===t.length)return(0,shared_1.err)("INVALID_KEY_LENGTH");const s=r.totalShares,_=r.threshold,a=(0,crypto_utils_js_1.nextOddPrime)(s)-1,o=(0,crypto_utils_js_1.pkcs7Pad)(t,a),{key:c,signature:i}=await(0,crypto_utils_js_1.generateHMAC)(o),u=(0,crypto_utils_js_1.toBase64)(c),n=(0,crypto_utils_js_1.toBase64)(i);let l;try{l=(0,crypto_utils_js_1.splitXorIDA)(o,s,_)}catch{return(0,shared_1.err)("SPLIT_FAILED")}const h=l.map((t,r)=>({index:r,data:(0,crypto_utils_js_1.toBase64)(t),total:s,threshold:_,hmacKey:u,hmacSig:n}));return(0,shared_1.ok)(h)}async function reconstructKeyFromBackup(t){if(0===t.length)return(0,shared_1.err)("INSUFFICIENT_SHARES");const r=t[0].threshold,e=t[0].total;if(t.length<r)return(0,shared_1.err)("INSUFFICIENT_SHARES");const s=t.slice(0,r);let _;try{_=s.map(t=>(0,crypto_utils_js_1.fromBase64)(t.data))}catch{return(0,shared_1.err)("INVALID_SHARE_DATA")}const a=s.map(t=>t.index);let o,c,i;try{o=(0,crypto_utils_js_1.reconstructXorIDA)(_,a,e,r)}catch{return(0,shared_1.err)("RECONSTRUCT_FAILED")}try{c=(0,crypto_utils_js_1.fromBase64)(s[0].hmacKey),i=(0,crypto_utils_js_1.fromBase64)(s[0].hmacSig)}catch{return(0,shared_1.err)("INVALID_SHARE_DATA")}if(!await(0,crypto_utils_js_1.verifyHMAC)(c,o,i))return(0,shared_1.err)("HMAC_VERIFICATION_FAILED");const u=(0,crypto_utils_js_1.nextOddPrime)(e)-1,n=(0,crypto_utils_js_1.pkcs7Unpad)(o,u);return n.ok?(0,shared_1.ok)(n.value):(0,shared_1.err)("RECONSTRUCT_FAILED")}exports.DEFAULT_BACKUP_CONFIG={threshold:2,totalShares:3};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.exportBackup=exportBackup,exports.importBackup=importBackup;const shared_1=require("../_deps/shared/index.js"),crypto_utils_js_1=require("./crypto-utils.js"),identity_js_1=require("./identity.js"),PBKDF2_ITERATIONS=31e4,SALT_LENGTH=16,IV_LENGTH=12,KEY_LENGTH=32;function toArrayBuffer(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function deriveKey(e,t){try{if(t.length!==SALT_LENGTH)return(0,shared_1.err)("INVALID_BACKUP");const r=await crypto.subtle.importKey("raw",(new TextEncoder).encode(e),"PBKDF2",!1,["deriveBits"]),s=new Uint8Array(await crypto.subtle.deriveBits({name:"PBKDF2",hash:"SHA-256",salt:toArrayBuffer(t),iterations:31e4},r,256)),a=await crypto.subtle.importKey("raw",toArrayBuffer(s),{name:"AES-GCM"},!1,["encrypt","decrypt"]);return(0,shared_1.ok)(a)}catch{return(0,shared_1.err)("PBKDF2_FAILED")}}async function serializeIdentity(e){try{const t=await(0,identity_js_1.exportPKCS8)(e.privateKey);if(!t.ok)return(0,shared_1.err)("EXPORT_FAILED");const r=await(0,identity_js_1.exportX25519PKCS8)(e.x25519PrivateKey);if(!r.ok)return(0,shared_1.err)("EXPORT_FAILED");const s=(0,identity_js_1.exportMlKemSecretKey)(e),a=(0,identity_js_1.exportMlKemPublicKey)(e),o=(0,identity_js_1.exportMlDsaSecretKey)(e),i=(0,identity_js_1.exportMlDsaPublicKey)(e),_=e.rotatedKeys?await Promise.all(e.rotatedKeys.map(async e=>{const t=await(0,identity_js_1.exportX25519PKCS8)(e.x25519PrivateKey);if(!t.ok)throw new Error("Failed to export rotated X25519 key");return{rotatedAt:e.rotatedAt,x25519Pkcs8:(0,crypto_utils_js_1.toBase64)(t.value),...e.mlKemSecretKey?{mlKemSecretKey:(0,crypto_utils_js_1.toBase64)(e.mlKemSecretKey)}:{}}})):void 0;return(0,shared_1.ok)({did:e.did,rawPublicKey:(0,crypto_utils_js_1.toBase64)(e.rawPublicKey),ed25519Pkcs8:(0,crypto_utils_js_1.toBase64)(t.value),x25519Pkcs8:(0,crypto_utils_js_1.toBase64)(r.value),...s?{mlKemSecretKey:(0,crypto_utils_js_1.toBase64)(s)}:{},...a?{mlKemPublicKey:(0,crypto_utils_js_1.toBase64)(a)}:{},...o?{mlDsaSecretKey:(0,crypto_utils_js_1.toBase64)(o)}:{},...i?{mlDsaPublicKey:(0,crypto_utils_js_1.toBase64)(i)}:{},..._?{rotatedKeys:_}:{},exportedAt:Date.now()})}catch{return(0,shared_1.err)("EXPORT_FAILED")}}async function exportBackup(e,t){try{const r=await serializeIdentity(e);if(!r.ok)return r;const s=crypto.getRandomValues(new Uint8Array(SALT_LENGTH)),a=crypto.getRandomValues(new Uint8Array(IV_LENGTH)),o=await deriveKey(t,s);if(!o.ok)return o;const i=JSON.stringify(r.value),_=(new TextEncoder).encode(i),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:toArrayBuffer(a)},o.value,_),n=new Uint8Array(c);if(n.length<16)return(0,shared_1.err)("ENCRYPTION_FAILED");const y=n.length-16,u=n.slice(0,y),l=n.slice(y);return(0,shared_1.ok)({version:1,salt:(0,crypto_utils_js_1.toBase64)(s),iv:(0,crypto_utils_js_1.toBase64)(a),ciphertext:(0,crypto_utils_js_1.toBase64)(u),tag:(0,crypto_utils_js_1.toBase64)(l)})}catch{return(0,shared_1.err)("ENCRYPTION_FAILED")}}async function importBackup(e,t){try{if(1!==e.version)return(0,shared_1.err)("INVALID_BACKUP");let r,s,a,o;try{r=(0,crypto_utils_js_1.fromBase64)(e.salt),s=(0,crypto_utils_js_1.fromBase64)(e.iv),a=(0,crypto_utils_js_1.fromBase64)(e.ciphertext),o=(0,crypto_utils_js_1.fromBase64)(e.tag)}catch{return(0,shared_1.err)("INVALID_BACKUP")}if(r.length!==SALT_LENGTH||s.length!==IV_LENGTH||16!==o.length)return(0,shared_1.err)("INVALID_BACKUP");const i=await deriveKey(t,r);if(!i.ok)return i;const _=new Uint8Array(a.length+o.length);let c,n,y,u,l,d,p,K;_.set(a),_.set(o,a.length);try{c=await crypto.subtle.decrypt({name:"AES-GCM",iv:toArrayBuffer(s)},i.value,toArrayBuffer(_))}catch(e){return console.warn("[xBind] GCM verification failed:",e),(0,shared_1.err)("INVALID_PASSWORD")}try{const e=(new TextDecoder).decode(c);n=JSON.parse(e)}catch{return(0,shared_1.err)("INVALID_BACKUP")}if(!n.did||!n.ed25519Pkcs8||!n.x25519Pkcs8)return(0,shared_1.err)("INVALID_BACKUP");try{y=(0,crypto_utils_js_1.fromBase64)(n.ed25519Pkcs8),u=(0,crypto_utils_js_1.fromBase64)(n.x25519Pkcs8),n.mlKemSecretKey&&(l=(0,crypto_utils_js_1.fromBase64)(n.mlKemSecretKey)),n.mlKemPublicKey&&(d=(0,crypto_utils_js_1.fromBase64)(n.mlKemPublicKey)),n.mlDsaSecretKey&&(p=(0,crypto_utils_js_1.fromBase64)(n.mlDsaSecretKey)),n.mlDsaPublicKey&&(K=(0,crypto_utils_js_1.fromBase64)(n.mlDsaPublicKey))}catch{return(0,shared_1.err)("INVALID_BACKUP")}const m=await(0,identity_js_1.importIdentity)(y,u,l,d,p,K);if(!m.ok)return(0,shared_1.err)("IMPORT_FAILED");if(n.rotatedKeys&&n.rotatedKeys.length>0){const e=m.value,t=await Promise.all(n.rotatedKeys.map(async e=>{const t=(0,crypto_utils_js_1.fromBase64)(e.x25519Pkcs8),r=await crypto.subtle.importKey("pkcs8",toArrayBuffer(t),{name:"X25519"},!0,["deriveBits"]),s=e.mlKemSecretKey?(0,crypto_utils_js_1.fromBase64)(e.mlKemSecretKey):void 0;return{rotatedAt:e.rotatedAt,x25519PrivateKey:r,...s?{mlKemSecretKey:s}:{}}}));return(0,shared_1.ok)({...e,rotatedKeys:t})}return m}catch(e){return console.warn("[xBind] Import backup failed:",e),(0,shared_1.err)("DECRYPTION_FAILED")}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BatchOperationError=void 0,exports.batchSend=batchSend,exports.batchReceive=batchReceive,exports.batchRegistryOps=batchRegistryOps,exports.batchResolve=batchResolve,exports.batchGetEntries=batchGetEntries;const shared_1=require("../_deps/shared/index.js"),ux_helpers_1=require("../_deps/ux-helpers/index.js");class BatchOperationError extends Error{summary;constructor(e,t){super(e),this.summary=t,this.name="BatchOperationError"}}async function batchSend(e,t){const r=new ux_helpers_1.ProgressReporter(t.onProgress),n=Date.now(),{messages:s,strategy:o="parallel",concurrency:a=10,continueOnError:c=!0}=t;r.start(`Sending ${s.length} messages (${o} mode)...`);const i=[];if("sequential"===o)for(let t=0;t<s.length;t++){const n=s[t],o=Date.now();r.update(`Sending message ${t+1}/${s.length}...`,t/s.length*100);const a=await e.send(n),u=Date.now()-o;if(i.push({index:t,result:a,durationMs:u}),!c&&!a.ok)break}else if("failfast"===o){const t=s.map((t,r)=>{const s=Date.now();return e.send(t).then(e=>{const t=Date.now()-s;if(!e.ok)throw new BatchOperationError(`Batch send failed at index ${r}: ${e.error}`,createSummary(i,Date.now()-n));return{index:r,result:e,durationMs:t}})});try{const e=await Promise.all(t);i.push(...e)}catch(e){if(e instanceof BatchOperationError)throw e;throw new BatchOperationError("Batch send failed",createSummary(i,Date.now()-n))}}else{const t=chunkArray(s,a);for(let n=0;n<t.length;n++){const s=t[n],o=n*a;r.update(`Processing chunk ${n+1}/${t.length}...`,n/t.length*100);const c=await Promise.all(s.map(async(t,r)=>{const n=o+r,s=Date.now();return{index:n,result:await e.send(t),durationMs:Date.now()-s}}));i.push(...c)}}return r.complete(),createSummary(i,Date.now()-n)}async function batchReceive(e,t){const r=new ux_helpers_1.ProgressReporter(t.onProgress),n=Date.now(),{envelopes:s,receiveOptions:o,strategy:a="parallel",concurrency:c=10,continueOnError:i=!0}=t;r.start(`Receiving ${s.length} envelopes (${a} mode)...`);const u=[];if("sequential"===a)for(let t=0;t<s.length;t++){const n=s[t],a=Date.now();r.update(`Receiving envelope ${t+1}/${s.length}...`,t/s.length*100);const c=await e.receive(n,o),l=Date.now()-a;if(u.push({index:t,result:c,durationMs:l}),!i&&!c.ok)break}else{const t=chunkArray(s,c);for(let n=0;n<t.length;n++){const s=t[n],a=n*c;r.update(`Processing chunk ${n+1}/${t.length}...`,n/t.length*100);const i=await Promise.all(s.map(async(t,r)=>{const n=a+r,s=Date.now();return{index:n,result:await e.receive(t,o),durationMs:Date.now()-s}}));u.push(...i)}}return r.complete(),createSummary(u,Date.now()-n)}async function batchRegistryOps(e,t){const r=new ux_helpers_1.ProgressReporter(t.onProgress),n=Date.now(),{operations:s,atomic:o=!1,strategy:a="parallel",concurrency:c=5}=t;r.start(`Executing ${s.length} registry operations (${o?"atomic":"best-effort"} mode)...`);const i=[];if(o&&r.update("Warning: Atomic mode not fully implemented - using best-effort",10),"sequential"===a)for(let t=0;t<s.length;t++){const n=s[t],a=Date.now();r.update(`Operation ${t+1}/${s.length}: ${n.type} ${n.did}`,t/s.length*100);const c=await executeRegistryOperation(e,n),u=Date.now()-a;if(i.push({index:t,result:c,durationMs:u}),o&&!c.ok)break}else{const t=chunkArray(s,c);for(let n=0;n<t.length;n++){const s=t[n],a=n*c;r.update(`Processing chunk ${n+1}/${t.length}...`,n/t.length*100);const u=await Promise.all(s.map(async(t,r)=>{const n=a+r,s=Date.now();return{index:n,result:await executeRegistryOperation(e,t),durationMs:Date.now()-s}}));if(i.push(...u),o&&u.some(e=>!e.result.ok))break}}return r.complete(),createSummary(i,Date.now()-n)}async function batchResolve(e,t,r){const n=new ux_helpers_1.ProgressReporter(r?.onProgress),s=Date.now(),o=r?.concurrency??10;n.start(`Resolving ${t.length} DIDs...`);const a=[],c=chunkArray(t,o);for(let t=0;t<c.length;t++){const r=c[t],s=t*o;n.update(`Resolving chunk ${t+1}/${c.length}...`,t/c.length*100);const i=await Promise.all(r.map(async(t,r)=>{const n=s+r,o=Date.now();return{index:n,result:await e.resolve(t),durationMs:Date.now()-o}}));a.push(...i)}return n.complete(),createSummary(a,Date.now()-s)}async function batchGetEntries(e,t,r){const n=new ux_helpers_1.ProgressReporter(r?.onProgress),s=Date.now(),o=r?.concurrency??10;n.start(`Fetching ${t.length} registry entries...`);const a=[],c=chunkArray(t,o);for(let t=0;t<c.length;t++){const r=c[t],s=t*o;n.update(`Fetching chunk ${t+1}/${c.length}...`,t/c.length*100);const i=await Promise.all(r.map(async(t,r)=>{const n=s+r,o=Date.now();return{index:n,result:await e.getEntry(t),durationMs:Date.now()-o}}));a.push(...i)}return n.complete(),createSummary(a,Date.now()-s)}async function executeRegistryOperation(e,t){switch(t.type){case"register":{if(!t.params)return(0,shared_1.err)("INVALID_PARAMS");const{publicKey:r,name:n,scopes:s,x25519PublicKey:o,mlKemPublicKey:a,mlDsaPublicKey:c,xchange:i,receiveScopes:u,sdkVersion:l,minEnvelopeVersion:h,maxEnvelopeVersion:p,ttlMs:g}=t.params;return e.register(t.did,r,n,s,o,a,c,i,u,l,h,p,g)}case"revoke":return e.revoke(t.did);case"updateScopes":return t.newScopes&&"updateScopes"in e&&"function"==typeof e.updateScopes?e.updateScopes(t.did,t.newScopes):(0,shared_1.err)("INVALID_PARAMS");default:return(0,shared_1.err)("INVALID_OPERATION")}}function createSummary(e,t){const r=e.filter(e=>e.result.ok).length,n=e.filter(e=>!e.result.ok).length,s=e.length>0?e.reduce((e,t)=>e+t.durationMs,0)/e.length:0;return{total:e.length,succeeded:r,failed:n,results:e,totalDurationMs:t,avgDurationMs:s}}function chunkArray(e,t){const r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}exports.BatchOperationError=BatchOperationError;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CancellationError=void 0,exports.createTimeoutSignal=createTimeoutSignal,exports.combineSignals=combineSignals,exports.onCancellation=onCancellation,exports.throwIfAborted=throwIfAborted,exports.withCancellation=withCancellation,exports.delay=delay,exports.withRetry=withRetry,exports.createCancellationController=createCancellationController,exports.isCancellationError=isCancellationError;const shared_1=require("../_deps/shared/index.js");class CancellationError extends Error{reason;context;constructor(e,r,n){super(e),this.reason=r,this.context=n,this.name="CancellationError"}}function createTimeoutSignal(e,r){const n=new AbortController,t=Date.now(),o=setTimeout(()=>{const t=r?.reason||`Operation timed out after ${e}ms`;n.abort(new CancellationError(t,"timeout",r?.context))},e);return{signal:n.signal,clear:()=>{clearTimeout(o)},remaining:()=>{const r=Date.now()-t;return Math.max(0,e-r)}}}function combineSignals(e){const r=e.filter(e=>e&&!e.aborted);if(0===r.length){const r=e.find(e=>e?.aborted);return r||(new AbortController).signal}if(1===r.length)return r[0];if("function"==typeof AbortSignal.any)return AbortSignal.any(r);const n=new AbortController,t=[];for(const e of r){const r=()=>{n.abort(e.reason),t.forEach(e=>e())};e.addEventListener("abort",r,{once:!0}),t.push(()=>{e.removeEventListener("abort",r)})}return n.signal}function onCancellation(e,r){e.aborted?Promise.resolve().then(()=>r()).catch(()=>{}):e.addEventListener("abort",()=>{Promise.resolve().then(()=>r()).catch(()=>{})},{once:!0})}function throwIfAborted(e,r){if(e?.aborted){const n=e.reason instanceof Error?e.reason.message:String(e.reason||"Operation was cancelled");throw new CancellationError(n,"aborted",r)}}async function withCancellation(e,r){if(!r)try{const r=await e;return(0,shared_1.ok)(r)}catch(e){return(0,shared_1.err)(new CancellationError(e instanceof Error?e.message:String(e),"promise_rejected"))}if(r.aborted){const e=r.reason instanceof Error?r.reason.message:String(r.reason||"Operation was cancelled");return(0,shared_1.err)(new CancellationError(e,"aborted"))}return new Promise(n=>{const t=()=>{const e=r.reason instanceof Error?r.reason.message:String(r.reason||"Operation was cancelled");n((0,shared_1.err)(new CancellationError(e,"aborted")))};r.addEventListener("abort",t,{once:!0}),e.then(e=>{r.removeEventListener("abort",t),n((0,shared_1.ok)(e))}).catch(e=>{r.removeEventListener("abort",t),n((0,shared_1.err)(new CancellationError(e instanceof Error?e.message:String(e),"promise_rejected")))})})}function delay(e,r){return new Promise((n,t)=>{if(r?.aborted){const e=r.reason instanceof Error?r.reason.message:String(r.reason||"Delay cancelled");return void t(new CancellationError(e,"aborted"))}const o=setTimeout(()=>{r&&r.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(o);const e=r.reason instanceof Error?r.reason.message:String(r.reason||"Delay cancelled");t(new CancellationError(e,"aborted"))};r&&r.addEventListener("abort",a,{once:!0})})}async function withRetry(e,r){const n=r?.maxAttempts??3,t=r?.initialDelay??1e3,o=r?.multiplier??2,a=r?.signal,i=r?.shouldRetry??(()=>!0);let s,l=t;for(let r=1;r<=n;r++){if(a?.aborted){const e=a.reason instanceof Error?a.reason.message:String(a.reason||"Operation was cancelled");return(0,shared_1.err)(new CancellationError(e,"aborted",{attempt:r}))}try{const r=await e();return(0,shared_1.ok)(r)}catch(e){if(s=e instanceof Error?e:new Error(String(e)),r>=n||!i(e,r))break;try{await delay(l,a),l*=o}catch(e){if(e instanceof CancellationError)return(0,shared_1.err)(e);throw e}}}return(0,shared_1.err)(s||new Error("Operation failed after retries"))}function createCancellationController(){const e=new AbortController;let r;return{signal:e.signal,get isCancelled(){return e.signal.aborted},get reason(){return r},cancel(n){r=n||"Operation cancelled",e.abort(new CancellationError(r,"manual"))},throwIfCancelled(r){throwIfAborted(e.signal,r)}}}function isCancellationError(e){return e instanceof CancellationError||e instanceof Error&&"AbortError"===e.name||e instanceof Error&&"CancellationError"===e.name}exports.CancellationError=CancellationError;
@@ -1,193 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createCheckpoint = createCheckpoint;
4
- exports.verifyCheckpoint = verifyCheckpoint;
5
- exports.isCacheStale = isCacheStale;
6
- exports.encodeCheckpoint = encodeCheckpoint;
7
- exports.decodeCheckpoint = decodeCheckpoint;
8
- const shared_1 = require("../_deps/shared/index.js");
9
- const identity_js_1 = require("./identity.js");
10
- /* ── Checkpoint Creation (Gateway-side) ── */
11
- /**
12
- * Create a signed checkpoint for a DID (gateway-side operation).
13
- *
14
- * Gateway signs the DID state snapshot using its ML-DSA-65 private key.
15
- * Clients verify this signature using the gateway's published public key.
16
- *
17
- * @param subject - DID being checkpointed
18
- * @param publicKey - Current public key bytes
19
- * @param revoked - Current revocation status
20
- * @param rotationSequence - Current rotation sequence counter
21
- * @param gatewayPrivateKey - Gateway's ML-DSA-65 secret key (32-byte seed or 4032-byte expanded)
22
- * @returns Signed checkpoint or error
23
- *
24
- * @example
25
- * ```typescript
26
- * const checkpoint = await createCheckpoint(
27
- * 'did:key:z6Mk...',
28
- * publicKeyBytes,
29
- * false,
30
- * 5,
31
- * gatewaySecretKey
32
- * );
33
- * if (checkpoint.ok) {
34
- * // Send checkpoint to client for staleness detection
35
- * sendToClient(checkpoint.value);
36
- * }
37
- * ```
38
- */
39
- async function createCheckpoint(subject, publicKey, revoked, rotationSequence, gatewayPrivateKey) {
40
- const timestamp = Date.now();
41
- // Construct canonical message to sign
42
- const publicKeyB64 = Buffer.from(publicKey).toString('base64');
43
- const message = `DIDStateCheckpoint||1.0||${subject}||${publicKeyB64}||${revoked}||${rotationSequence}||${timestamp}`;
44
- const messageBytes = new TextEncoder().encode(message);
45
- // Sign using gateway's ML-DSA-65 key
46
- const sigResult = await (0, identity_js_1.signMlDsa65)(gatewayPrivateKey, messageBytes);
47
- if (!sigResult.ok) {
48
- return (0, shared_1.err)('SIGN_FAILED');
49
- }
50
- return (0, shared_1.ok)({
51
- type: 'DIDStateCheckpoint',
52
- version: '1.0',
53
- subject,
54
- current_public_key: publicKeyB64,
55
- revoked,
56
- rotation_sequence: rotationSequence,
57
- timestamp,
58
- checkpoint_signature_algorithm: 'ML-DSA-65',
59
- checkpoint_signature: Buffer.from(sigResult.value).toString('base64')
60
- });
61
- }
62
- /* ── Checkpoint Verification (Client-side) ── */
63
- /**
64
- * Verify a checkpoint signature (client-side operation).
65
- *
66
- * Clients MUST verify checkpoint signatures before trusting the state.
67
- * Uses gateway's published ML-DSA-65 public key to verify signature.
68
- *
69
- * @param checkpoint - Checkpoint to verify
70
- * @param gatewayPublicKey - Gateway's ML-DSA-65 public key (1952 bytes)
71
- * @returns true if signature valid, false if invalid, error if verification fails
72
- *
73
- * @example
74
- * ```typescript
75
- * const valid = await verifyCheckpoint(checkpoint, gatewayPubKey);
76
- * if (valid.ok && valid.value) {
77
- * // Checkpoint is authentic - safe to use for staleness detection
78
- * if (isCacheStale(localCache, checkpoint)) {
79
- * // Refresh local cache
80
- * }
81
- * }
82
- * ```
83
- */
84
- async function verifyCheckpoint(checkpoint, gatewayPublicKey) {
85
- // Validate checkpoint format
86
- if (checkpoint.type !== 'DIDStateCheckpoint') {
87
- return (0, shared_1.err)('INVALID_FORMAT');
88
- }
89
- if (checkpoint.version !== '1.0') {
90
- return (0, shared_1.err)('INVALID_FORMAT');
91
- }
92
- if (!checkpoint.subject || !checkpoint.current_public_key) {
93
- return (0, shared_1.err)('INVALID_FORMAT');
94
- }
95
- if (typeof checkpoint.rotation_sequence !== 'number' || checkpoint.rotation_sequence < 0) {
96
- return (0, shared_1.err)('INVALID_FORMAT');
97
- }
98
- if (typeof checkpoint.timestamp !== 'number' || checkpoint.timestamp <= 0) {
99
- return (0, shared_1.err)('INVALID_TIMESTAMP');
100
- }
101
- if (checkpoint.checkpoint_signature_algorithm !== 'ML-DSA-65') {
102
- return (0, shared_1.err)('INVALID_FORMAT');
103
- }
104
- // Reconstruct canonical message
105
- const message = `DIDStateCheckpoint||1.0||${checkpoint.subject}||${checkpoint.current_public_key}||${checkpoint.revoked}||${checkpoint.rotation_sequence}||${checkpoint.timestamp}`;
106
- const messageBytes = new TextEncoder().encode(message);
107
- // Decode signature
108
- let signature;
109
- try {
110
- signature = Buffer.from(checkpoint.checkpoint_signature, 'base64');
111
- }
112
- catch {
113
- return (0, shared_1.err)('INVALID_SIGNATURE');
114
- }
115
- // Verify signature using gateway public key
116
- const verifyResult = await (0, identity_js_1.verifyMlDsa65)(gatewayPublicKey, signature, messageBytes);
117
- if (!verifyResult.ok) {
118
- return (0, shared_1.err)('VERIFY_FAILED');
119
- }
120
- return (0, shared_1.ok)(verifyResult.value);
121
- }
122
- /* ── Staleness Detection ── */
123
- /**
124
- * Detect if local cache is stale compared to gateway checkpoint.
125
- *
126
- * Cache is stale if:
127
- * 1. Checkpoint rotation_sequence > local rotationSequence (key rotated)
128
- * 2. Checkpoint revoked !== local revoked (revocation status changed)
129
- * 3. Checkpoint public key !== local publicKey (state drift)
130
- *
131
- * @param localCache - Local cache entry for DID
132
- * @param checkpoint - Verified checkpoint from gateway
133
- * @returns true if cache needs refresh, false if cache is current
134
- *
135
- * @example
136
- * ```typescript
137
- * if (isCacheStale(localCache, checkpoint)) {
138
- * // Local cache is outdated - fetch fresh state from gateway
139
- * const freshState = await registry.getEntry(did);
140
- * }
141
- * ```
142
- */
143
- function isCacheStale(localCache, checkpoint) {
144
- // Sequence number mismatch indicates key rotation
145
- if (checkpoint.rotation_sequence > localCache.rotationSequence) {
146
- return true;
147
- }
148
- // Revocation status changed
149
- if (checkpoint.revoked !== localCache.revoked) {
150
- return true;
151
- }
152
- // Public key mismatch indicates state drift
153
- const checkpointPubKey = Buffer.from(checkpoint.current_public_key, 'base64');
154
- if (!Buffer.from(localCache.publicKey).equals(checkpointPubKey)) {
155
- return true;
156
- }
157
- return false;
158
- }
159
- /* ── Encoding/Decoding ── */
160
- /**
161
- * Encode checkpoint to JSON string for wire transport.
162
- *
163
- * @param checkpoint - Checkpoint to encode
164
- * @returns JSON string
165
- */
166
- function encodeCheckpoint(checkpoint) {
167
- return JSON.stringify(checkpoint);
168
- }
169
- /**
170
- * Decode checkpoint from JSON string.
171
- *
172
- * @param encoded - JSON string
173
- * @returns Parsed checkpoint or error
174
- */
175
- function decodeCheckpoint(encoded) {
176
- try {
177
- const parsed = JSON.parse(encoded);
178
- // Basic validation
179
- if (parsed.type !== 'DIDStateCheckpoint') {
180
- return (0, shared_1.err)('INVALID_FORMAT');
181
- }
182
- if (parsed.version !== '1.0') {
183
- return (0, shared_1.err)('INVALID_FORMAT');
184
- }
185
- if (!parsed.subject || !parsed.current_public_key || !parsed.checkpoint_signature) {
186
- return (0, shared_1.err)('INVALID_FORMAT');
187
- }
188
- return (0, shared_1.ok)(parsed);
189
- }
190
- catch {
191
- return (0, shared_1.err)('INVALID_FORMAT');
192
- }
193
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createCheckpoint=createCheckpoint,exports.verifyCheckpoint=verifyCheckpoint,exports.isCacheStale=isCacheStale,exports.encodeCheckpoint=encodeCheckpoint,exports.decodeCheckpoint=decodeCheckpoint;const shared_1=require("../_deps/shared/index.js"),identity_js_1=require("./identity.js");async function createCheckpoint(e,r,t,n,i){const o=Date.now(),c=Buffer.from(r).toString("base64"),s=`DIDStateCheckpoint||1.0||${e}||${c}||${t}||${n}||${o}`,a=(new TextEncoder).encode(s),u=await(0,identity_js_1.signMlDsa65)(i,a);return u.ok?(0,shared_1.ok)({type:"DIDStateCheckpoint",version:"1.0",subject:e,current_public_key:c,revoked:t,rotation_sequence:n,timestamp:o,checkpoint_signature_algorithm:"ML-DSA-65",checkpoint_signature:Buffer.from(u.value).toString("base64")}):(0,shared_1.err)("SIGN_FAILED")}async function verifyCheckpoint(e,r){if("DIDStateCheckpoint"!==e.type)return(0,shared_1.err)("INVALID_FORMAT");if("1.0"!==e.version)return(0,shared_1.err)("INVALID_FORMAT");if(!e.subject||!e.current_public_key)return(0,shared_1.err)("INVALID_FORMAT");if("number"!=typeof e.rotation_sequence||e.rotation_sequence<0)return(0,shared_1.err)("INVALID_FORMAT");if("number"!=typeof e.timestamp||e.timestamp<=0)return(0,shared_1.err)("INVALID_TIMESTAMP");if("ML-DSA-65"!==e.checkpoint_signature_algorithm)return(0,shared_1.err)("INVALID_FORMAT");const t=`DIDStateCheckpoint||1.0||${e.subject}||${e.current_public_key}||${e.revoked}||${e.rotation_sequence}||${e.timestamp}`,n=(new TextEncoder).encode(t);let i;try{i=Buffer.from(e.checkpoint_signature,"base64")}catch{return(0,shared_1.err)("INVALID_SIGNATURE")}const o=await(0,identity_js_1.verifyMlDsa65)(r,i,n);return o.ok?(0,shared_1.ok)(o.value):(0,shared_1.err)("VERIFY_FAILED")}function isCacheStale(e,r){if(r.rotation_sequence>e.rotationSequence)return!0;if(r.revoked!==e.revoked)return!0;const t=Buffer.from(r.current_public_key,"base64");return!Buffer.from(e.publicKey).equals(t)}function encodeCheckpoint(e){return JSON.stringify(e)}function decodeCheckpoint(e){try{const r=JSON.parse(e);return"DIDStateCheckpoint"!==r.type||"1.0"!==r.version?(0,shared_1.err)("INVALID_FORMAT"):r.subject&&r.current_public_key&&r.checkpoint_signature?(0,shared_1.ok)(r):(0,shared_1.err)("INVALID_FORMAT")}catch{return(0,shared_1.err)("INVALID_FORMAT")}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CircuitBreakerManager=exports.CircuitBreaker=void 0,exports.createRegistryCircuitBreaker=createRegistryCircuitBreaker,exports.createGatewayCircuitBreaker=createGatewayCircuitBreaker,exports.createS3CircuitBreaker=createS3CircuitBreaker;const shared_1=require("../_deps/shared/index.js");class CircuitBreaker{state="CLOSED";consecutiveFailures=0;consecutiveSuccesses=0;successCount=0;failureCount=0;rejectedCount=0;lastOpenedAt;lastClosedAt;recoveryTimer;failureThreshold;recoveryTimeout;halfOpenMaxCalls;successThreshold;name;onStateChange;onOpen;onClose;onHalfOpen;constructor(e={}){this.failureThreshold=e.failureThreshold??5,this.recoveryTimeout=e.recoveryTimeout??6e4,this.halfOpenMaxCalls=e.halfOpenMaxCalls??3,this.successThreshold=e.successThreshold??2,this.name=e.name??"default",this.onStateChange=e.onStateChange,this.onOpen=e.onOpen,this.onClose=e.onClose,this.onHalfOpen=e.onHalfOpen}async execute(e){if("OPEN"===this.state)return this.rejectedCount++,(0,shared_1.err)("CIRCUIT_OPEN");if("HALF_OPEN"===this.state){if(this.consecutiveSuccesses+(this.consecutiveFailures>0?1:0)>=this.halfOpenMaxCalls)return this.rejectedCount++,(0,shared_1.err)("HALF_OPEN_LIMIT_EXCEEDED")}try{const t=await e();return this.onSuccess(),(0,shared_1.ok)(t)}catch(e){return this.onFailure(e),(0,shared_1.err)("EXECUTION_FAILED")}}getMetrics(){return{state:this.state,successCount:this.successCount,failureCount:this.failureCount,rejectedCount:this.rejectedCount,consecutiveFailures:this.consecutiveFailures,consecutiveSuccesses:this.consecutiveSuccesses,lastOpenedAt:this.lastOpenedAt,lastClosedAt:this.lastClosedAt,name:this.name}}getState(){return this.state}reset(){this.clearRecoveryTimer(),this.transitionTo("CLOSED","manual reset"),this.consecutiveFailures=0,this.consecutiveSuccesses=0}forceOpen(e="manual intervention"){this.transitionTo("OPEN",e),this.scheduleRecovery()}dispose(){this.clearRecoveryTimer()}onSuccess(){this.successCount++,this.consecutiveFailures=0,"HALF_OPEN"===this.state&&(this.consecutiveSuccesses++,this.consecutiveSuccesses>=this.successThreshold&&(this.transitionTo("CLOSED",`${this.consecutiveSuccesses} consecutive successes`),this.consecutiveSuccesses=0))}onFailure(e){if(this.failureCount++,this.consecutiveFailures++,this.consecutiveSuccesses=0,"CLOSED"===this.state&&this.consecutiveFailures>=this.failureThreshold){const e=`${this.consecutiveFailures} consecutive failures`;this.transitionTo("OPEN",e),this.scheduleRecovery()}"HALF_OPEN"===this.state&&(this.transitionTo("OPEN","failure in HALF_OPEN state"),this.scheduleRecovery())}transitionTo(e,t){const s=this.state;s!==e&&(this.state=e,"OPEN"===e?(this.lastOpenedAt=Date.now(),this.onOpen?.(t)):"CLOSED"===e?(this.lastClosedAt=Date.now(),this.onClose?.()):"HALF_OPEN"===e&&this.onHalfOpen?.(),this.onStateChange?.(s,e,t))}scheduleRecovery(){this.clearRecoveryTimer(),this.recoveryTimer=setTimeout(()=>{"OPEN"===this.state&&this.transitionTo("HALF_OPEN","recovery timeout elapsed")},this.recoveryTimeout),this.recoveryTimer.unref&&this.recoveryTimer.unref()}clearRecoveryTimer(){this.recoveryTimer&&(clearTimeout(this.recoveryTimer),this.recoveryTimer=void 0)}}function createRegistryCircuitBreaker(e={}){return new CircuitBreaker({name:"registry",failureThreshold:10,recoveryTimeout:12e4,halfOpenMaxCalls:5,successThreshold:3,...e})}function createGatewayCircuitBreaker(e={}){return new CircuitBreaker({name:"gateway",failureThreshold:5,recoveryTimeout:6e4,halfOpenMaxCalls:3,successThreshold:2,...e})}function createS3CircuitBreaker(e={}){return new CircuitBreaker({name:"s3",failureThreshold:3,recoveryTimeout:3e4,halfOpenMaxCalls:2,successThreshold:2,...e})}exports.CircuitBreaker=CircuitBreaker;class CircuitBreakerManager{breakers=new Map;constructor(){this.breakers.set("registry",createRegistryCircuitBreaker()),this.breakers.set("gateway",createGatewayCircuitBreaker()),this.breakers.set("s3",createS3CircuitBreaker())}async executeRegistry(e){const t=this.breakers.get("registry");return t?t.execute(e):(0,shared_1.err)("Circuit breaker not found: registry")}async executeGateway(e){const t=this.breakers.get("gateway");return t?t.execute(e):(0,shared_1.err)("Circuit breaker not found: gateway")}async executeS3(e){const t=this.breakers.get("s3");return t?t.execute(e):(0,shared_1.err)("Circuit breaker not found: s3")}getMetrics(e){return this.breakers.get(e)?.getMetrics()}getAllMetrics(){const e={};for(const[t,s]of this.breakers.entries())e[t]=s.getMetrics();return e}getOrCreate(e,t){let s=this.breakers.get(e);return s||(s=new CircuitBreaker({...t,name:e}),this.breakers.set(e,s)),s}resetAll(){for(const e of this.breakers.values())e.reset()}dispose(){for(const e of this.breakers.values())e.dispose();this.breakers.clear()}}exports.CircuitBreakerManager=CircuitBreakerManager;