@private.me/xbind 3.0.1 → 3.0.2

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 (210) hide show
  1. package/README.md +55 -14
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.js +163 -1
  174. package/dist-standalone/plugins/metrics.js +176 -1
  175. package/dist-standalone/plugins/validation.js +297 -1
  176. package/dist-standalone/policy.js +315 -1
  177. package/dist-standalone/progress-callbacks.js +576 -1
  178. package/dist-standalone/redis-nonce-store.js +72 -1
  179. package/dist-standalone/registry-middleware.js +47 -1
  180. package/dist-standalone/retry-strategies.js +534 -1
  181. package/dist-standalone/retry-transport.js +98 -1
  182. package/dist-standalone/runtime/browser.js +516 -1
  183. package/dist-standalone/runtime/edge.js +511 -1
  184. package/dist-standalone/runtime/react-native.js +383 -1
  185. package/dist-standalone/security-policy.js +239 -1
  186. package/dist-standalone/serialization.js +1031 -1
  187. package/dist-standalone/split-channel.js +219 -1
  188. package/dist-standalone/subscription-proof.js +224 -1
  189. package/dist-standalone/succession.js +142 -1
  190. package/dist-standalone/timeouts.js +398 -1
  191. package/dist-standalone/trace-context.js +414 -1
  192. package/dist-standalone/trace-spans.js +488 -1
  193. package/dist-standalone/transport.js +59 -1
  194. package/dist-standalone/trust-registry.js +950 -1
  195. package/dist-standalone/types/error-response.js +52 -1
  196. package/dist-standalone/vault-auth.js +174 -1
  197. package/dist-standalone/vault-store-loader.js +187 -1
  198. package/dist-standalone/verify.js +16 -1
  199. package/dist-standalone/version-info.js +530 -1
  200. package/dist-standalone/xfetch.js +335 -1
  201. package/package.json +4 -13
  202. package/share1.dat +0 -0
  203. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  204. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  205. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  206. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  207. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  208. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  209. package/dist-standalone/cjs/package.json +0 -3
  210. package/dist-standalone/package.json +0 -10
@@ -1 +1,576 @@
1
- import{ProgressReporter}from"./_deps/ux-helpers/index.js";export class OperationProgressTracker{callback;throttleMs;lastUpdateTime=0;currentStage="";currentStageWeight=0;currentStageProgress=0;completedWeight=0;metadata={};constructor(t,e){this.callback=t,this.throttleMs=e?.throttleMs??100}startStage(t,e,s){this.currentStage=t,this.currentStageWeight=Math.max(0,Math.min(100,e)),this.currentStageProgress=0,this.reportProgress(s??`Starting ${t}...`)}updateStageProgress(t,e,s){this.currentStageProgress=Math.max(0,Math.min(100,t)),s&&(this.metadata={...this.metadata,...s});const r=e??`${this.currentStage} (${Math.round(t)}%)`;this.reportProgress(r)}completeStage(){this.currentStageProgress=100,this.completedWeight+=this.currentStageWeight,this.reportProgress(`${this.currentStage} complete`),this.currentStage="",this.currentStageWeight=0,this.currentStageProgress=0}complete(){this.completedWeight=100,this.currentStageProgress=100,this.reportProgress("Complete")}getProgress(){const t=this.currentStageWeight*this.currentStageProgress/100;return Math.min(100,this.completedWeight+t)}updateMetadata(t){this.metadata={...this.metadata,...t}}reportProgress(t){if(!this.callback)return;const e=Date.now();if(e-this.lastUpdateTime<this.throttleMs){if(this.getProgress()<100)return}this.lastUpdateTime=e;const s=this.getProgress();if(this.isEnhancedCallback(this.callback)){const e={stage:this.currentStage,progress:s,stageProgress:this.currentStageProgress,status:t,metadata:Object.keys(this.metadata).length>0?this.metadata:void 0};this.callback(e)}else this.callback(t,s)}isEnhancedCallback(t){return 1===t.length}}export class TransferProgressTracker{totalBytes;callback;reporter;throttleMs;bytesTransferred=0;startTime=Date.now();lastUpdateTime=0;samples=[];maxSamples=10;constructor(t,e,s=100){this.totalBytes=t,this.callback=e,this.throttleMs=s,this.reporter=new ProgressReporter("function"==typeof e&&2===e.length?e:void 0)}addTransferred(t){this.bytesTransferred+=t;const e=Date.now();this.samples.push({time:e,bytes:this.bytesTransferred}),this.samples.length>this.maxSamples&&this.samples.shift(),e-this.lastUpdateTime<this.throttleMs||(this.lastUpdateTime=e,this.reportProgress())}complete(){this.bytesTransferred=this.totalBytes,this.reportProgress()}getProgress(){return 0===this.totalBytes?100:Math.min(100,this.bytesTransferred/this.totalBytes*100)}calculateBytesPerSecond(){if(this.samples.length<2){const t=(Date.now()-this.startTime)/1e3;return t>0?this.bytesTransferred/t:0}const t=this.samples[0],e=this.samples[this.samples.length-1];if(!t||!e)return 0;const s=(e.time-t.time)/1e3,r=e.bytes-t.bytes;return s>0?r/s:0}estimateTimeRemaining(){const t=this.calculateBytesPerSecond();if(0===t)return 0;return(this.totalBytes-this.bytesTransferred)/t*1e3}reportProgress(){if(!this.callback)return;const t=this.getProgress(),e=this.calculateBytesPerSecond(),s=this.estimateTimeRemaining(),r=this.formatStatus(t,e,s);if(this.isEnhancedCallback(this.callback)){const a={stage:"transfer",progress:t,stageProgress:t,status:r,metadata:{bytesTransferred:this.bytesTransferred,totalBytes:this.totalBytes,bytesPerSecond:e,estimatedTimeRemaining:s}};this.callback(a)}else this.reporter.report(r,t)}formatStatus(t,e,s){const r=this.formatBytes(this.bytesTransferred),a=this.formatBytes(this.totalBytes),i=this.formatBytes(e),o=this.formatTime(s);return`Transferring ${r} / ${a} (${Math.round(t)}%) - ${i}/s - ${o} remaining`}formatBytes(t){const e=["B","KB","MB","GB","TB"];let s=t,r=0;for(;s>=1024&&r<e.length-1;)s/=1024,r++;return`${s.toFixed(1)} ${e[r]}`}formatTime(t){const e=Math.floor(t/1e3);if(e<60)return`${e}s`;const s=Math.floor(e/60);if(s<60)return`${s}m ${e%60}s`;return`${Math.floor(s/60)}h ${s%60}m`}isEnhancedCallback(t){return 1===t.length}}export class ShareDistributionTracker{totalShares;callback;reporter;distributedShares=new Set;constructor(t,e){this.totalShares=t,this.callback=e,this.reporter=new ProgressReporter("function"==typeof e&&2===e.length?e:void 0)}markShareDistributed(t){this.distributedShares.add(t),this.reportProgress()}complete(){for(let t=0;t<this.totalShares;t++)this.distributedShares.add(t);this.reportProgress()}getProgress(){return 0===this.totalShares?100:this.distributedShares.size/this.totalShares*100}reportProgress(){if(!this.callback)return;const t=this.getProgress(),e=`Distributed ${this.distributedShares.size} / ${this.totalShares} shares`;if(this.isEnhancedCallback(this.callback)){const s={stage:"distribution",progress:t,stageProgress:t,status:e,metadata:{sharesDistributed:this.distributedShares.size,totalShares:this.totalShares}};this.callback(s)}else this.reporter.report(e,t)}isEnhancedCallback(t){return 1===t.length}}export class EncryptionProgressTracker{operation;totalItems;callback;reporter;itemsProcessed=0;constructor(t,e,s){this.operation=t,this.totalItems=e,this.callback=s,this.reporter=new ProgressReporter("function"==typeof s&&2===s.length?s:void 0)}incrementProcessed(t=1){this.itemsProcessed+=t,this.reportProgress()}complete(){this.itemsProcessed=this.totalItems,this.reportProgress()}getProgress(){return 0===this.totalItems?100:Math.min(100,this.itemsProcessed/this.totalItems*100)}reportProgress(){if(!this.callback)return;const t=this.getProgress(),e=`${this.operation.charAt(0).toUpperCase()+this.operation.slice(1)}ing: ${this.itemsProcessed} / ${this.totalItems} items`;if(this.isEnhancedCallback(this.callback)){const s={stage:this.operation,progress:t,stageProgress:t,status:e,metadata:{cryptoOperation:this.operation,itemsProcessed:this.itemsProcessed,totalItems:this.totalItems}};this.callback(s)}else this.reporter.report(e,t)}isEnhancedCallback(t){return 1===t.length}}
1
+ /**
2
+ * @module progress-callbacks
3
+ * Enhanced progress tracking for xBind operations
4
+ *
5
+ * Provides domain-specific progress callbacks for long-running operations:
6
+ * - Upload/download progress with bandwidth estimation
7
+ * - Share distribution progress (XorIDA multi-channel delivery)
8
+ * - Encryption/decryption progress
9
+ * - Multi-stage operation tracking
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * const tracker = new OperationProgressTracker(onProgress);
14
+ * tracker.startStage('encryption', 40); // 40% of total operation
15
+ * // ... encryption work
16
+ * tracker.updateStageProgress(50); // 50% of encryption stage
17
+ * tracker.completeStage();
18
+ * ```
19
+ */
20
+ import { ProgressReporter } from"./_deps/ux-helpers/index.js";
21
+ /**
22
+ * Multi-stage operation progress tracker.
23
+ *
24
+ * Manages progress across multiple stages with weighted contributions
25
+ * to overall progress. Useful for complex operations like:
26
+ * - Message send: resolve DID (10%) → encrypt (30%) → split shares (20%) → distribute (40%)
27
+ * - File transfer: prepare (5%) → encrypt (25%) → upload (70%)
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * const tracker = new OperationProgressTracker(onProgress);
32
+ *
33
+ * tracker.startStage('preparation', 10);
34
+ * // ... prep work
35
+ * tracker.completeStage();
36
+ *
37
+ * tracker.startStage('encryption', 40);
38
+ * tracker.updateStageProgress(50); // Halfway through encryption
39
+ * tracker.completeStage();
40
+ *
41
+ * tracker.startStage('distribution', 50);
42
+ * // ... distribution work
43
+ * tracker.complete();
44
+ * ```
45
+ */
46
+ export class OperationProgressTracker {
47
+ callback;
48
+ throttleMs;
49
+ lastUpdateTime = 0;
50
+ currentStage = '';
51
+ currentStageWeight = 0;
52
+ currentStageProgress = 0;
53
+ completedWeight = 0;
54
+ metadata = {};
55
+ /**
56
+ * Create a new operation progress tracker.
57
+ *
58
+ * @param onProgress Progress callback (standard or enhanced)
59
+ * @param options Tracking options
60
+ */
61
+ constructor(onProgress, options) {
62
+ this.callback = onProgress;
63
+ this.throttleMs = options?.throttleMs ?? 100; // Default 100ms throttle
64
+ }
65
+ /**
66
+ * Start a new stage.
67
+ *
68
+ * @param name Stage identifier
69
+ * @param weight Weight of this stage (percentage of total, 0-100)
70
+ * @param description Human-readable description
71
+ */
72
+ startStage(name, weight, description) {
73
+ this.currentStage = name;
74
+ this.currentStageWeight = Math.max(0, Math.min(100, weight));
75
+ this.currentStageProgress = 0;
76
+ this.reportProgress(description ?? `Starting ${name}...`);
77
+ }
78
+ /**
79
+ * Update progress within the current stage.
80
+ *
81
+ * @param stagePercent Progress percentage within current stage (0-100)
82
+ * @param status Optional status message
83
+ * @param metadata Optional progress metadata
84
+ */
85
+ updateStageProgress(stagePercent, status, metadata) {
86
+ this.currentStageProgress = Math.max(0, Math.min(100, stagePercent));
87
+ if (metadata) {
88
+ this.metadata = { ...this.metadata, ...metadata };
89
+ }
90
+ const message = status ?? `${this.currentStage} (${Math.round(stagePercent)}%)`;
91
+ this.reportProgress(message);
92
+ }
93
+ /**
94
+ * Complete the current stage and advance overall progress.
95
+ */
96
+ completeStage() {
97
+ this.currentStageProgress = 100;
98
+ this.completedWeight += this.currentStageWeight;
99
+ this.reportProgress(`${this.currentStage} complete`);
100
+ // Reset for next stage
101
+ this.currentStage = '';
102
+ this.currentStageWeight = 0;
103
+ this.currentStageProgress = 0;
104
+ }
105
+ /**
106
+ * Mark the entire operation as complete.
107
+ */
108
+ complete() {
109
+ this.completedWeight = 100;
110
+ this.currentStageProgress = 100;
111
+ this.reportProgress('Complete');
112
+ }
113
+ /**
114
+ * Get current overall progress percentage.
115
+ *
116
+ * @returns Progress percentage (0-100)
117
+ */
118
+ getProgress() {
119
+ const stageContribution = (this.currentStageWeight * this.currentStageProgress) / 100;
120
+ return Math.min(100, this.completedWeight + stageContribution);
121
+ }
122
+ /**
123
+ * Update metadata without changing progress.
124
+ *
125
+ * @param metadata Metadata to merge
126
+ */
127
+ updateMetadata(metadata) {
128
+ this.metadata = { ...this.metadata, ...metadata };
129
+ }
130
+ /**
131
+ * Report progress to callback (with throttling).
132
+ *
133
+ * @param status Status message
134
+ */
135
+ reportProgress(status) {
136
+ if (!this.callback)
137
+ return;
138
+ const now = Date.now();
139
+ if (now - this.lastUpdateTime < this.throttleMs) {
140
+ // Throttle updates unless complete
141
+ const progress = this.getProgress();
142
+ if (progress < 100)
143
+ return;
144
+ }
145
+ this.lastUpdateTime = now;
146
+ const progress = this.getProgress();
147
+ // Check if callback expects enhanced events
148
+ if (this.isEnhancedCallback(this.callback)) {
149
+ const event = {
150
+ stage: this.currentStage,
151
+ progress,
152
+ stageProgress: this.currentStageProgress,
153
+ status,
154
+ metadata: Object.keys(this.metadata).length > 0 ? this.metadata : undefined,
155
+ };
156
+ this.callback(event);
157
+ }
158
+ else {
159
+ // Standard callback
160
+ this.callback(status, progress);
161
+ }
162
+ }
163
+ /**
164
+ * Check if callback expects enhanced events.
165
+ *
166
+ * @param callback Callback to check
167
+ * @returns True if enhanced callback
168
+ */
169
+ isEnhancedCallback(callback) {
170
+ // Enhanced callbacks accept 1 parameter (event object)
171
+ // Standard callbacks accept 2 parameters (status, percent)
172
+ return callback.length === 1;
173
+ }
174
+ }
175
+ /**
176
+ * Transfer progress tracker with bandwidth estimation.
177
+ *
178
+ * Tracks upload/download progress with automatic bandwidth calculation
179
+ * and estimated time remaining.
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * const tracker = new TransferProgressTracker(totalBytes, onProgress);
184
+ *
185
+ * for (const chunk of chunks) {
186
+ * await uploadChunk(chunk);
187
+ * tracker.addTransferred(chunk.length);
188
+ * }
189
+ *
190
+ * tracker.complete();
191
+ * ```
192
+ */
193
+ export class TransferProgressTracker {
194
+ totalBytes;
195
+ callback;
196
+ reporter;
197
+ throttleMs;
198
+ bytesTransferred = 0;
199
+ startTime = Date.now();
200
+ lastUpdateTime = 0;
201
+ samples = [];
202
+ maxSamples = 10;
203
+ /**
204
+ * Create a new transfer progress tracker.
205
+ *
206
+ * @param totalBytes Total bytes to transfer
207
+ * @param onProgress Progress callback
208
+ * @param throttleMs Minimum interval between updates (default: 100ms)
209
+ */
210
+ constructor(totalBytes, onProgress, throttleMs = 100) {
211
+ this.totalBytes = totalBytes;
212
+ this.callback = onProgress;
213
+ this.throttleMs = throttleMs;
214
+ // Create standard progress reporter for fallback
215
+ this.reporter = new ProgressReporter(typeof onProgress === 'function' && onProgress.length === 2
216
+ ? onProgress
217
+ : undefined);
218
+ }
219
+ /**
220
+ * Add transferred bytes and update progress.
221
+ *
222
+ * @param bytes Number of bytes transferred
223
+ */
224
+ addTransferred(bytes) {
225
+ this.bytesTransferred += bytes;
226
+ const now = Date.now();
227
+ // Add sample for bandwidth estimation
228
+ this.samples.push({ time: now, bytes: this.bytesTransferred });
229
+ if (this.samples.length > this.maxSamples) {
230
+ this.samples.shift();
231
+ }
232
+ // Throttle updates
233
+ if (now - this.lastUpdateTime < this.throttleMs) {
234
+ return;
235
+ }
236
+ this.lastUpdateTime = now;
237
+ this.reportProgress();
238
+ }
239
+ /**
240
+ * Mark transfer as complete.
241
+ */
242
+ complete() {
243
+ this.bytesTransferred = this.totalBytes;
244
+ this.reportProgress();
245
+ }
246
+ /**
247
+ * Get current progress percentage.
248
+ *
249
+ * @returns Progress percentage (0-100)
250
+ */
251
+ getProgress() {
252
+ if (this.totalBytes === 0)
253
+ return 100;
254
+ return Math.min(100, (this.bytesTransferred / this.totalBytes) * 100);
255
+ }
256
+ /**
257
+ * Calculate current transfer rate.
258
+ *
259
+ * @returns Bytes per second
260
+ */
261
+ calculateBytesPerSecond() {
262
+ if (this.samples.length < 2) {
263
+ const elapsed = (Date.now() - this.startTime) / 1000;
264
+ return elapsed > 0 ? this.bytesTransferred / elapsed : 0;
265
+ }
266
+ const oldest = this.samples[0];
267
+ const newest = this.samples[this.samples.length - 1];
268
+ if (!oldest || !newest)
269
+ return 0;
270
+ const timeDiff = (newest.time - oldest.time) / 1000; // seconds
271
+ const bytesDiff = newest.bytes - oldest.bytes;
272
+ return timeDiff > 0 ? bytesDiff / timeDiff : 0;
273
+ }
274
+ /**
275
+ * Estimate time remaining.
276
+ *
277
+ * @returns Estimated milliseconds remaining
278
+ */
279
+ estimateTimeRemaining() {
280
+ const bytesPerSecond = this.calculateBytesPerSecond();
281
+ if (bytesPerSecond === 0)
282
+ return 0;
283
+ const bytesRemaining = this.totalBytes - this.bytesTransferred;
284
+ return (bytesRemaining / bytesPerSecond) * 1000; // milliseconds
285
+ }
286
+ /**
287
+ * Report progress to callback.
288
+ */
289
+ reportProgress() {
290
+ if (!this.callback)
291
+ return;
292
+ const progress = this.getProgress();
293
+ const bytesPerSecond = this.calculateBytesPerSecond();
294
+ const estimatedTimeRemaining = this.estimateTimeRemaining();
295
+ const status = this.formatStatus(progress, bytesPerSecond, estimatedTimeRemaining);
296
+ if (this.isEnhancedCallback(this.callback)) {
297
+ const event = {
298
+ stage: 'transfer',
299
+ progress,
300
+ stageProgress: progress,
301
+ status,
302
+ metadata: {
303
+ bytesTransferred: this.bytesTransferred,
304
+ totalBytes: this.totalBytes,
305
+ bytesPerSecond,
306
+ estimatedTimeRemaining,
307
+ },
308
+ };
309
+ this.callback(event);
310
+ }
311
+ else {
312
+ this.reporter.report(status, progress);
313
+ }
314
+ }
315
+ /**
316
+ * Format status message with transfer details.
317
+ *
318
+ * @param progress Progress percentage
319
+ * @param bytesPerSecond Transfer rate
320
+ * @param estimatedTimeRemaining Time remaining in ms
321
+ * @returns Formatted status string
322
+ */
323
+ formatStatus(progress, bytesPerSecond, estimatedTimeRemaining) {
324
+ const transferred = this.formatBytes(this.bytesTransferred);
325
+ const total = this.formatBytes(this.totalBytes);
326
+ const rate = this.formatBytes(bytesPerSecond);
327
+ const remaining = this.formatTime(estimatedTimeRemaining);
328
+ return `Transferring ${transferred} / ${total} (${Math.round(progress)}%) - ${rate}/s - ${remaining} remaining`;
329
+ }
330
+ /**
331
+ * Format bytes for display.
332
+ *
333
+ * @param bytes Number of bytes
334
+ * @returns Formatted string (e.g., "1.5 MB")
335
+ */
336
+ formatBytes(bytes) {
337
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
338
+ let value = bytes;
339
+ let unitIndex = 0;
340
+ while (value >= 1024 && unitIndex < units.length - 1) {
341
+ value /= 1024;
342
+ unitIndex++;
343
+ }
344
+ return `${value.toFixed(1)} ${units[unitIndex]}`;
345
+ }
346
+ /**
347
+ * Format time for display.
348
+ *
349
+ * @param ms Milliseconds
350
+ * @returns Formatted string (e.g., "2m 30s")
351
+ */
352
+ formatTime(ms) {
353
+ const seconds = Math.floor(ms / 1000);
354
+ if (seconds < 60)
355
+ return `${seconds}s`;
356
+ const minutes = Math.floor(seconds / 60);
357
+ const remainingSeconds = seconds % 60;
358
+ if (minutes < 60)
359
+ return `${minutes}m ${remainingSeconds}s`;
360
+ const hours = Math.floor(minutes / 60);
361
+ const remainingMinutes = minutes % 60;
362
+ return `${hours}h ${remainingMinutes}m`;
363
+ }
364
+ /**
365
+ * Check if callback expects enhanced events.
366
+ *
367
+ * @param callback Callback to check
368
+ * @returns True if enhanced callback
369
+ */
370
+ isEnhancedCallback(callback) {
371
+ return callback.length === 1;
372
+ }
373
+ }
374
+ /**
375
+ * Share distribution progress tracker for XorIDA operations.
376
+ *
377
+ * Tracks progress of distributing shares across multiple channels.
378
+ *
379
+ * @example
380
+ * ```typescript
381
+ * const tracker = new ShareDistributionTracker(3, onProgress);
382
+ *
383
+ * await distributeShare(0);
384
+ * tracker.markShareDistributed(0);
385
+ *
386
+ * await distributeShare(1);
387
+ * tracker.markShareDistributed(1);
388
+ *
389
+ * await distributeShare(2);
390
+ * tracker.markShareDistributed(2);
391
+ *
392
+ * tracker.complete();
393
+ * ```
394
+ */
395
+ export class ShareDistributionTracker {
396
+ totalShares;
397
+ callback;
398
+ reporter;
399
+ distributedShares = new Set();
400
+ /**
401
+ * Create a new share distribution tracker.
402
+ *
403
+ * @param totalShares Total number of shares to distribute
404
+ * @param onProgress Progress callback
405
+ */
406
+ constructor(totalShares, onProgress) {
407
+ this.totalShares = totalShares;
408
+ this.callback = onProgress;
409
+ this.reporter = new ProgressReporter(typeof onProgress === 'function' && onProgress.length === 2
410
+ ? onProgress
411
+ : undefined);
412
+ }
413
+ /**
414
+ * Mark a share as successfully distributed.
415
+ *
416
+ * @param shareIndex Zero-based share index
417
+ */
418
+ markShareDistributed(shareIndex) {
419
+ this.distributedShares.add(shareIndex);
420
+ this.reportProgress();
421
+ }
422
+ /**
423
+ * Mark all shares as distributed and complete.
424
+ */
425
+ complete() {
426
+ for (let i = 0; i < this.totalShares; i++) {
427
+ this.distributedShares.add(i);
428
+ }
429
+ this.reportProgress();
430
+ }
431
+ /**
432
+ * Get current progress percentage.
433
+ *
434
+ * @returns Progress percentage (0-100)
435
+ */
436
+ getProgress() {
437
+ if (this.totalShares === 0)
438
+ return 100;
439
+ return (this.distributedShares.size / this.totalShares) * 100;
440
+ }
441
+ /**
442
+ * Report progress to callback.
443
+ */
444
+ reportProgress() {
445
+ if (!this.callback)
446
+ return;
447
+ const progress = this.getProgress();
448
+ const status = `Distributed ${this.distributedShares.size} / ${this.totalShares} shares`;
449
+ if (this.isEnhancedCallback(this.callback)) {
450
+ const event = {
451
+ stage: 'distribution',
452
+ progress,
453
+ stageProgress: progress,
454
+ status,
455
+ metadata: {
456
+ sharesDistributed: this.distributedShares.size,
457
+ totalShares: this.totalShares,
458
+ },
459
+ };
460
+ this.callback(event);
461
+ }
462
+ else {
463
+ this.reporter.report(status, progress);
464
+ }
465
+ }
466
+ /**
467
+ * Check if callback expects enhanced events.
468
+ *
469
+ * @param callback Callback to check
470
+ * @returns True if enhanced callback
471
+ */
472
+ isEnhancedCallback(callback) {
473
+ return callback.length === 1;
474
+ }
475
+ }
476
+ /**
477
+ * Encryption progress tracker.
478
+ *
479
+ * Tracks progress of encryption/decryption operations on large data.
480
+ *
481
+ * @example
482
+ * ```typescript
483
+ * const tracker = new EncryptionProgressTracker('encrypt', totalChunks, onProgress);
484
+ *
485
+ * for (const chunk of chunks) {
486
+ * await encryptChunk(chunk);
487
+ * tracker.incrementProcessed();
488
+ * }
489
+ *
490
+ * tracker.complete();
491
+ * ```
492
+ */
493
+ export class EncryptionProgressTracker {
494
+ operation;
495
+ totalItems;
496
+ callback;
497
+ reporter;
498
+ itemsProcessed = 0;
499
+ /**
500
+ * Create a new encryption progress tracker.
501
+ *
502
+ * @param operation Cryptographic operation type
503
+ * @param totalItems Total number of items to process
504
+ * @param onProgress Progress callback
505
+ */
506
+ constructor(operation, totalItems, onProgress) {
507
+ this.operation = operation;
508
+ this.totalItems = totalItems;
509
+ this.callback = onProgress;
510
+ this.reporter = new ProgressReporter(typeof onProgress === 'function' && onProgress.length === 2
511
+ ? onProgress
512
+ : undefined);
513
+ }
514
+ /**
515
+ * Increment the number of processed items.
516
+ *
517
+ * @param count Number of items to add (default: 1)
518
+ */
519
+ incrementProcessed(count = 1) {
520
+ this.itemsProcessed += count;
521
+ this.reportProgress();
522
+ }
523
+ /**
524
+ * Mark operation as complete.
525
+ */
526
+ complete() {
527
+ this.itemsProcessed = this.totalItems;
528
+ this.reportProgress();
529
+ }
530
+ /**
531
+ * Get current progress percentage.
532
+ *
533
+ * @returns Progress percentage (0-100)
534
+ */
535
+ getProgress() {
536
+ if (this.totalItems === 0)
537
+ return 100;
538
+ return Math.min(100, (this.itemsProcessed / this.totalItems) * 100);
539
+ }
540
+ /**
541
+ * Report progress to callback.
542
+ */
543
+ reportProgress() {
544
+ if (!this.callback)
545
+ return;
546
+ const progress = this.getProgress();
547
+ const operationName = this.operation.charAt(0).toUpperCase() + this.operation.slice(1);
548
+ const status = `${operationName}ing: ${this.itemsProcessed} / ${this.totalItems} items`;
549
+ if (this.isEnhancedCallback(this.callback)) {
550
+ const event = {
551
+ stage: this.operation,
552
+ progress,
553
+ stageProgress: progress,
554
+ status,
555
+ metadata: {
556
+ cryptoOperation: this.operation,
557
+ itemsProcessed: this.itemsProcessed,
558
+ totalItems: this.totalItems,
559
+ },
560
+ };
561
+ this.callback(event);
562
+ }
563
+ else {
564
+ this.reporter.report(status, progress);
565
+ }
566
+ }
567
+ /**
568
+ * Check if callback expects enhanced events.
569
+ *
570
+ * @param callback Callback to check
571
+ * @returns True if enhanced callback
572
+ */
573
+ isEnhancedCallback(callback) {
574
+ return callback.length === 1;
575
+ }
576
+ }
@@ -1 +1,72 @@
1
- const DEFAULT_TTL_SECONDS=600,DEFAULT_KEY_PREFIX="nonce:";export class RedisNonceStore{client;ttlSeconds;keyPrefix;constructor(t){this.client=t.client,this.ttlSeconds=t.ttlSeconds??600,this.keyPrefix=t.keyPrefix??"nonce:"}async check(t,e){const c=`${this.keyPrefix}${e}:${t}`;return"OK"===await this.client.setNX(c,"1",this.ttlSeconds)}cleanup(){}dispose(){this.client.quit()}}
1
+ /* -- RedisNonceStore -- Cross-Node Replay Prevention -- */
2
+ /** Default TTL for nonce entries: 600 seconds (10 minutes). */
3
+ const DEFAULT_TTL_SECONDS = 600;
4
+ /** Default key prefix for Redis nonce keys. */
5
+ const DEFAULT_KEY_PREFIX = 'nonce:';
6
+ /**
7
+ * Redis-backed nonce store for multi-node deployments.
8
+ *
9
+ * Uses Redis SET NX with TTL for atomic, distributed nonce deduplication.
10
+ * Nonce expiry is handled by Redis TTL -- no manual cleanup needed.
11
+ * Zero npm dependencies: users provide their own RedisClient implementation.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { RedisNonceStore } from '@private.me/xbind';
16
+ * import Redis from 'ioredis';
17
+ *
18
+ * const redis = new Redis();
19
+ * const store = new RedisNonceStore({
20
+ * client: {
21
+ * setNX: (key, value, ttl) =>
22
+ * redis.set(key, value, 'EX', ttl, 'NX'),
23
+ * del: (key) => redis.del(key),
24
+ * quit: () => redis.quit(),
25
+ * },
26
+ * });
27
+ * ```
28
+ */
29
+ export class RedisNonceStore {
30
+ client;
31
+ ttlSeconds;
32
+ keyPrefix;
33
+ constructor(opts) {
34
+ this.client = opts.client;
35
+ this.ttlSeconds = opts.ttlSeconds ?? DEFAULT_TTL_SECONDS;
36
+ this.keyPrefix = opts.keyPrefix ?? DEFAULT_KEY_PREFIX;
37
+ }
38
+ /**
39
+ * Check if a nonce is fresh and record it atomically via Redis SET NX.
40
+ *
41
+ * Uses Redis SET with NX (set-if-not-exists) and EX (TTL in seconds)
42
+ * for atomic, distributed deduplication. If the key already exists in
43
+ * any Redis-connected node, the nonce is rejected as a duplicate.
44
+ *
45
+ * @param nonce - The nonce string to check.
46
+ * @param senderDid - The DID of the sender.
47
+ * @returns true if the nonce is new (accepted), false if duplicate (rejected).
48
+ */
49
+ async check(nonce, senderDid) {
50
+ const key = `${this.keyPrefix}${senderDid}:${nonce}`;
51
+ const result = await this.client.setNX(key, '1', this.ttlSeconds);
52
+ return result === 'OK';
53
+ }
54
+ /**
55
+ * No-op for Redis store -- TTL-based expiry is handled automatically.
56
+ *
57
+ * This method exists to satisfy the NonceStore interface. Redis keys
58
+ * expire based on the TTL set during setNX, so no manual cleanup is needed.
59
+ */
60
+ cleanup() {
61
+ // No-op: Redis TTL handles expiry automatically
62
+ }
63
+ /**
64
+ * Disconnect from Redis gracefully.
65
+ *
66
+ * Calls the underlying RedisClient quit() method to close the connection.
67
+ * After calling dispose(), the store should not be used.
68
+ */
69
+ dispose() {
70
+ void this.client.quit();
71
+ }
72
+ }
@@ -1 +1,47 @@
1
- export function createRegistryAuthMiddleware(r){return(t,e,o)=>{const s=t.method.toUpperCase();if("GET"===s||"HEAD"===s)return void o();const i="string"==typeof t.headers.authorization?t.headers.authorization:void 0;if(!i||!i.startsWith("Bearer "))return void e.status(401).json({error:"UNAUTHORIZED"});i.slice(7)===r?o():e.status(401).json({error:"UNAUTHORIZED"})}}
1
+ /**
2
+ * Express middleware for protecting trust registry endpoints with bearer auth.
3
+ *
4
+ * GET/HEAD requests pass through (public reads). POST/PUT/DELETE require
5
+ * a valid Bearer token matching the configured admin token.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import express from 'express';
10
+ * import { createRegistryAuthMiddleware } from '@private.me/xbind';
11
+ *
12
+ * const app = express();
13
+ * app.use('/registry', createRegistryAuthMiddleware(process.env.REGISTRY_ADMIN_TOKEN!));
14
+ * ```
15
+ */
16
+ /**
17
+ * Create an Express-compatible middleware that protects write operations
18
+ * on registry endpoints with bearer token authentication.
19
+ *
20
+ * GET and HEAD requests pass through without authentication.
21
+ * POST, PUT, and DELETE require `Authorization: Bearer <token>`.
22
+ *
23
+ * @param token - The admin token to validate against.
24
+ * @returns Express middleware function.
25
+ */
26
+ export function createRegistryAuthMiddleware(token) {
27
+ return (req, res, next) => {
28
+ const method = req.method.toUpperCase();
29
+ if (method === 'GET' || method === 'HEAD') {
30
+ next();
31
+ return;
32
+ }
33
+ const authHeader = typeof req.headers['authorization'] === 'string'
34
+ ? req.headers['authorization']
35
+ : undefined;
36
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
37
+ res.status(401).json({ error: 'UNAUTHORIZED' });
38
+ return;
39
+ }
40
+ const provided = authHeader.slice('Bearer '.length);
41
+ if (provided !== token) {
42
+ res.status(401).json({ error: 'UNAUTHORIZED' });
43
+ return;
44
+ }
45
+ next();
46
+ };
47
+ }