@private.me/xbind 3.0.2 → 3.0.3

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 (221) hide show
  1. package/README.md +2366 -204
  2. package/README.md.backup +2121 -0
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  7. package/dist-standalone/_deps/shared/errors.js +1 -244
  8. package/dist-standalone/_deps/shared/index.js +1 -72
  9. package/dist-standalone/_deps/shared/types.js +1 -86
  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.d.ts +2 -2
  48. package/dist-standalone/agent-call.js +1 -659
  49. package/dist-standalone/agent-sdk.js +1 -328
  50. package/dist-standalone/agent.d.ts +2 -0
  51. package/dist-standalone/agent.js +1 -1800
  52. package/dist-standalone/approval.js +1 -193
  53. package/dist-standalone/async-iterators.d.ts +3 -3
  54. package/dist-standalone/async-iterators.js +1 -382
  55. package/dist-standalone/auth.js +1 -219
  56. package/dist-standalone/auto-accept.js +1 -229
  57. package/dist-standalone/backup-config.js +1 -201
  58. package/dist-standalone/backup.js +1 -326
  59. package/dist-standalone/batch-operations.js +1 -388
  60. package/dist-standalone/cancellation.js +1 -477
  61. package/dist-standalone/checkpoint.js +1 -186
  62. package/dist-standalone/circuit-breaker.js +1 -468
  63. package/dist-standalone/cjs/agent-call.js +1 -701
  64. package/dist-standalone/cjs/agent-sdk.js +1 -332
  65. package/dist-standalone/cjs/agent.js +1 -1837
  66. package/dist-standalone/cjs/approval.js +1 -199
  67. package/dist-standalone/cjs/async-iterators.js +1 -392
  68. package/dist-standalone/cjs/auth.js +1 -225
  69. package/dist-standalone/cjs/auto-accept.js +1 -233
  70. package/dist-standalone/cjs/backup-config.js +1 -207
  71. package/dist-standalone/cjs/backup.js +1 -330
  72. package/dist-standalone/cjs/batch-operations.js +1 -397
  73. package/dist-standalone/cjs/cancellation.js +1 -490
  74. package/dist-standalone/cjs/checkpoint.js +1 -193
  75. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  76. package/dist-standalone/cjs/cli/init.js +1 -492
  77. package/dist-standalone/cjs/config-validation.js +1 -522
  78. package/dist-standalone/cjs/connect.js +1 -312
  79. package/dist-standalone/cjs/connection-pool.js +1 -506
  80. package/dist-standalone/cjs/correlation-id.js +1 -339
  81. package/dist-standalone/cjs/crypto-utils.js +1 -176
  82. package/dist-standalone/cjs/debug-mode.js +1 -534
  83. package/dist-standalone/cjs/did-document.js +1 -101
  84. package/dist-standalone/cjs/did-privateme.js +1 -130
  85. package/dist-standalone/cjs/did-web.js +1 -201
  86. package/dist-standalone/cjs/discovery.js +1 -462
  87. package/dist-standalone/cjs/dual-mode.js +1 -251
  88. package/dist-standalone/cjs/email-templates.js +1 -313
  89. package/dist-standalone/cjs/email-transport.js +1 -239
  90. package/dist-standalone/cjs/envelope.js +1 -538
  91. package/dist-standalone/cjs/errors.js +1 -913
  92. package/dist-standalone/cjs/event-emitter.js +1 -461
  93. package/dist-standalone/cjs/gateway-state.js +1 -55
  94. package/dist-standalone/cjs/gateway-transport.js +1 -120
  95. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  96. package/dist-standalone/cjs/guardrails.js +1 -223
  97. package/dist-standalone/cjs/health-check.js +1 -336
  98. package/dist-standalone/cjs/http-compat.js +1 -272
  99. package/dist-standalone/cjs/http-status-map.js +1 -571
  100. package/dist-standalone/cjs/identity.js +1 -645
  101. package/dist-standalone/cjs/index.js +1 -406
  102. package/dist-standalone/cjs/invitation.js +1 -421
  103. package/dist-standalone/cjs/invite.js +1 -328
  104. package/dist-standalone/cjs/key-agreement.js +1 -335
  105. package/dist-standalone/cjs/lazy-init.js +1 -300
  106. package/dist-standalone/cjs/logger.js +1 -291
  107. package/dist-standalone/cjs/loopback-transport.js +1 -0
  108. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  109. package/dist-standalone/cjs/nonce-store.js +1 -80
  110. package/dist-standalone/cjs/pairing-manager.js +1 -223
  111. package/dist-standalone/cjs/plugin-system.js +1 -264
  112. package/dist-standalone/cjs/plugins/logging.js +1 -168
  113. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  114. package/dist-standalone/cjs/plugins/validation.js +1 -302
  115. package/dist-standalone/cjs/policy.js +1 -320
  116. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  117. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  118. package/dist-standalone/cjs/registry-middleware.js +1 -50
  119. package/dist-standalone/cjs/retry-strategies.js +1 -544
  120. package/dist-standalone/cjs/retry-transport.js +1 -102
  121. package/dist-standalone/cjs/runtime/browser.js +1 -533
  122. package/dist-standalone/cjs/runtime/edge.js +1 -526
  123. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  124. package/dist-standalone/cjs/security-policy.js +1 -245
  125. package/dist-standalone/cjs/serialization.js +1 -1040
  126. package/dist-standalone/cjs/split-channel.js +1 -225
  127. package/dist-standalone/cjs/subscription-proof.js +1 -230
  128. package/dist-standalone/cjs/succession.js +1 -148
  129. package/dist-standalone/cjs/timeouts.js +1 -412
  130. package/dist-standalone/cjs/trace-context.js +1 -424
  131. package/dist-standalone/cjs/trace-spans.js +1 -495
  132. package/dist-standalone/cjs/transport.js +1 -63
  133. package/dist-standalone/cjs/trust-registry.js +1 -991
  134. package/dist-standalone/cjs/types/error-response.js +1 -56
  135. package/dist-standalone/cjs/vault-auth.js +1 -178
  136. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  137. package/dist-standalone/cjs/verify.js +1 -25
  138. package/dist-standalone/cjs/version-info.js +1 -543
  139. package/dist-standalone/cjs/xfetch.js +1 -340
  140. package/dist-standalone/cli/init.js +1 -455
  141. package/dist-standalone/cli/setup.js +1 -514
  142. package/dist-standalone/cli/types.js +1 -27
  143. package/dist-standalone/cli/xbind.js +1 -148
  144. package/dist-standalone/config-validation.js +1 -513
  145. package/dist-standalone/connect.js +1 -274
  146. package/dist-standalone/connection-pool.js +1 -500
  147. package/dist-standalone/correlation-id.js +1 -326
  148. package/dist-standalone/crypto-utils.d.ts +2 -7
  149. package/dist-standalone/crypto-utils.js +1 -157
  150. package/dist-standalone/debug-mode.js +1 -510
  151. package/dist-standalone/did-document.js +1 -96
  152. package/dist-standalone/did-privateme.js +1 -121
  153. package/dist-standalone/did-web.js +1 -196
  154. package/dist-standalone/discovery.js +1 -458
  155. package/dist-standalone/dual-mode.js +1 -247
  156. package/dist-standalone/email-templates.js +1 -309
  157. package/dist-standalone/email-transport.d.ts +2 -2
  158. package/dist-standalone/email-transport.js +1 -232
  159. package/dist-standalone/envelope.js +1 -525
  160. package/dist-standalone/errors.d.ts +13 -3
  161. package/dist-standalone/errors.js +1 -896
  162. package/dist-standalone/event-emitter.js +1 -456
  163. package/dist-standalone/gateway-state.d.ts +1 -1
  164. package/dist-standalone/gateway-state.js +1 -51
  165. package/dist-standalone/gateway-transport.js +1 -116
  166. package/dist-standalone/graceful-degradation.js +1 -396
  167. package/dist-standalone/guardrails.js +1 -216
  168. package/dist-standalone/health-check.d.ts +5 -1
  169. package/dist-standalone/health-check.js +1 -332
  170. package/dist-standalone/http-compat.d.ts +1 -1
  171. package/dist-standalone/http-compat.js +1 -267
  172. package/dist-standalone/http-status-map.js +1 -561
  173. package/dist-standalone/identity.js +1 -619
  174. package/dist-standalone/index.d.ts +15 -4
  175. package/dist-standalone/index.js +1 -78
  176. package/dist-standalone/invitation.js +1 -415
  177. package/dist-standalone/invite.js +1 -324
  178. package/dist-standalone/key-agreement.js +1 -325
  179. package/dist-standalone/lazy-init.d.ts +11 -6
  180. package/dist-standalone/lazy-init.js +1 -295
  181. package/dist-standalone/logger.js +1 -285
  182. package/dist-standalone/loopback-transport.d.ts +87 -0
  183. package/dist-standalone/loopback-transport.js +1 -0
  184. package/dist-standalone/mdns-discovery.js +1 -195
  185. package/dist-standalone/nonce-store.js +1 -76
  186. package/dist-standalone/pairing-manager.js +1 -219
  187. package/dist-standalone/plugin-system.js +1 -257
  188. package/dist-standalone/plugins/logging.js +1 -163
  189. package/dist-standalone/plugins/metrics.d.ts +4 -4
  190. package/dist-standalone/plugins/metrics.js +1 -176
  191. package/dist-standalone/plugins/validation.js +1 -297
  192. package/dist-standalone/policy.js +1 -315
  193. package/dist-standalone/progress-callbacks.js +1 -576
  194. package/dist-standalone/redis-nonce-store.js +1 -72
  195. package/dist-standalone/registry-middleware.js +1 -47
  196. package/dist-standalone/retry-strategies.js +1 -534
  197. package/dist-standalone/retry-transport.js +1 -98
  198. package/dist-standalone/runtime/browser.js +1 -516
  199. package/dist-standalone/runtime/edge.js +1 -511
  200. package/dist-standalone/runtime/react-native.d.ts +1 -1
  201. package/dist-standalone/runtime/react-native.js +1 -383
  202. package/dist-standalone/security-policy.js +1 -239
  203. package/dist-standalone/serialization.js +1 -1031
  204. package/dist-standalone/split-channel.js +1 -219
  205. package/dist-standalone/subscription-proof.js +1 -224
  206. package/dist-standalone/succession.js +1 -142
  207. package/dist-standalone/timeouts.js +1 -398
  208. package/dist-standalone/trace-context.js +1 -414
  209. package/dist-standalone/trace-spans.js +1 -488
  210. package/dist-standalone/transport.js +1 -59
  211. package/dist-standalone/trust-registry.d.ts +3 -3
  212. package/dist-standalone/trust-registry.js +1 -950
  213. package/dist-standalone/types/error-response.js +1 -52
  214. package/dist-standalone/vault-auth.js +1 -174
  215. package/dist-standalone/vault-store-loader.d.ts +9 -0
  216. package/dist-standalone/vault-store-loader.js +1 -187
  217. package/dist-standalone/verify.js +1 -16
  218. package/dist-standalone/version-info.js +1 -530
  219. package/dist-standalone/xfetch.js +1 -335
  220. package/package.json +1 -1
  221. package/share1.dat +0 -0
@@ -1,576 +1 @@
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
+ 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,72 +1 @@
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
+ 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,47 +1 @@
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
- }
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"})}}