@private.me/xbind 3.0.2 → 3.0.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 (222) hide show
  1. package/README.md +2366 -204
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  6. package/dist-standalone/_deps/shared/errors.js +1 -244
  7. package/dist-standalone/_deps/shared/index.js +1 -72
  8. package/dist-standalone/_deps/shared/types.js +1 -86
  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.d.ts +2 -2
  47. package/dist-standalone/agent-call.js +1 -659
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +2 -0
  50. package/dist-standalone/agent.js +1 -1800
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +3 -3
  53. package/dist-standalone/async-iterators.js +1 -382
  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.js +1 -326
  58. package/dist-standalone/batch-operations.js +1 -388
  59. package/dist-standalone/cancellation.js +1 -477
  60. package/dist-standalone/checkpoint.js +1 -186
  61. package/dist-standalone/circuit-breaker.js +1 -468
  62. package/dist-standalone/cjs/agent-call.js +1 -701
  63. package/dist-standalone/cjs/agent-sdk.js +1 -332
  64. package/dist-standalone/cjs/agent.js +1 -1837
  65. package/dist-standalone/cjs/approval.js +1 -199
  66. package/dist-standalone/cjs/async-iterators.js +1 -392
  67. package/dist-standalone/cjs/auth.js +1 -225
  68. package/dist-standalone/cjs/auto-accept.js +1 -233
  69. package/dist-standalone/cjs/backup-config.js +1 -207
  70. package/dist-standalone/cjs/backup.js +1 -330
  71. package/dist-standalone/cjs/batch-operations.js +1 -397
  72. package/dist-standalone/cjs/cancellation.js +1 -490
  73. package/dist-standalone/cjs/checkpoint.js +1 -193
  74. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  75. package/dist-standalone/cjs/cli/init.js +1 -492
  76. package/dist-standalone/cjs/config-validation.js +1 -522
  77. package/dist-standalone/cjs/connect.js +1 -312
  78. package/dist-standalone/cjs/connection-pool.js +1 -506
  79. package/dist-standalone/cjs/correlation-id.js +1 -339
  80. package/dist-standalone/cjs/crypto-utils.js +1 -176
  81. package/dist-standalone/cjs/debug-mode.js +1 -534
  82. package/dist-standalone/cjs/did-document.js +1 -101
  83. package/dist-standalone/cjs/did-privateme.js +1 -130
  84. package/dist-standalone/cjs/did-web.js +1 -201
  85. package/dist-standalone/cjs/discovery.js +1 -462
  86. package/dist-standalone/cjs/dual-mode.js +1 -251
  87. package/dist-standalone/cjs/email-templates.js +1 -313
  88. package/dist-standalone/cjs/email-transport.js +1 -239
  89. package/dist-standalone/cjs/envelope.js +1 -538
  90. package/dist-standalone/cjs/errors.js +1 -913
  91. package/dist-standalone/cjs/event-emitter.js +1 -461
  92. package/dist-standalone/cjs/gateway-state.js +1 -55
  93. package/dist-standalone/cjs/gateway-transport.js +1 -120
  94. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  95. package/dist-standalone/cjs/guardrails.js +1 -223
  96. package/dist-standalone/cjs/health-check.js +1 -336
  97. package/dist-standalone/cjs/http-compat.js +1 -272
  98. package/dist-standalone/cjs/http-status-map.js +1 -571
  99. package/dist-standalone/cjs/identity.js +1 -645
  100. package/dist-standalone/cjs/index.js +1 -406
  101. package/dist-standalone/cjs/invitation.js +1 -421
  102. package/dist-standalone/cjs/invite.js +1 -328
  103. package/dist-standalone/cjs/key-agreement.js +1 -335
  104. package/dist-standalone/cjs/lazy-init.js +1 -300
  105. package/dist-standalone/cjs/logger.js +1 -291
  106. package/dist-standalone/cjs/loopback-transport.js +1 -0
  107. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  108. package/dist-standalone/cjs/nonce-store.js +1 -80
  109. package/dist-standalone/cjs/pairing-manager.js +1 -223
  110. package/dist-standalone/cjs/plugin-system.js +1 -264
  111. package/dist-standalone/cjs/plugins/logging.js +1 -168
  112. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  113. package/dist-standalone/cjs/plugins/validation.js +1 -302
  114. package/dist-standalone/cjs/policy.js +1 -320
  115. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  116. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  117. package/dist-standalone/cjs/registry-middleware.js +1 -50
  118. package/dist-standalone/cjs/retry-strategies.js +1 -544
  119. package/dist-standalone/cjs/retry-transport.js +1 -102
  120. package/dist-standalone/cjs/runtime/browser.js +1 -533
  121. package/dist-standalone/cjs/runtime/edge.js +1 -526
  122. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  123. package/dist-standalone/cjs/security-policy.js +1 -245
  124. package/dist-standalone/cjs/serialization.js +1 -1040
  125. package/dist-standalone/cjs/split-channel.js +1 -225
  126. package/dist-standalone/cjs/subscription-proof.js +1 -230
  127. package/dist-standalone/cjs/succession.js +1 -148
  128. package/dist-standalone/cjs/timeouts.js +1 -412
  129. package/dist-standalone/cjs/trace-context.js +1 -424
  130. package/dist-standalone/cjs/trace-spans.js +1 -495
  131. package/dist-standalone/cjs/transport.js +1 -63
  132. package/dist-standalone/cjs/trust-registry.js +1 -991
  133. package/dist-standalone/cjs/types/error-response.js +1 -56
  134. package/dist-standalone/cjs/vault-auth.js +1 -178
  135. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  136. package/dist-standalone/cjs/verify.js +1 -25
  137. package/dist-standalone/cjs/version-info.js +1 -543
  138. package/dist-standalone/cjs/xfetch.js +1 -340
  139. package/dist-standalone/cli/init.js +1 -455
  140. package/dist-standalone/cli/setup.js +1 -514
  141. package/dist-standalone/cli/types.js +1 -27
  142. package/dist-standalone/cli/xbind.js +1 -148
  143. package/dist-standalone/config-validation.js +1 -513
  144. package/dist-standalone/connect.js +1 -274
  145. package/dist-standalone/connection-pool.js +1 -500
  146. package/dist-standalone/correlation-id.js +1 -326
  147. package/dist-standalone/crypto-utils.d.ts +2 -7
  148. package/dist-standalone/crypto-utils.js +1 -157
  149. package/dist-standalone/debug-mode.js +1 -510
  150. package/dist-standalone/did-document.js +1 -96
  151. package/dist-standalone/did-privateme.js +1 -121
  152. package/dist-standalone/did-web.js +1 -196
  153. package/dist-standalone/discovery.js +1 -458
  154. package/dist-standalone/dual-mode.js +1 -247
  155. package/dist-standalone/email-templates.js +1 -309
  156. package/dist-standalone/email-transport.d.ts +2 -2
  157. package/dist-standalone/email-transport.js +1 -232
  158. package/dist-standalone/envelope.js +1 -525
  159. package/dist-standalone/errors.d.ts +13 -3
  160. package/dist-standalone/errors.js +1 -896
  161. package/dist-standalone/event-emitter.js +1 -456
  162. package/dist-standalone/gateway-state.d.ts +1 -1
  163. package/dist-standalone/gateway-state.js +1 -51
  164. package/dist-standalone/gateway-transport.js +1 -116
  165. package/dist-standalone/graceful-degradation.js +1 -396
  166. package/dist-standalone/guardrails.js +1 -216
  167. package/dist-standalone/health-check.d.ts +5 -1
  168. package/dist-standalone/health-check.js +1 -332
  169. package/dist-standalone/http-compat.d.ts +1 -1
  170. package/dist-standalone/http-compat.js +1 -267
  171. package/dist-standalone/http-status-map.js +1 -561
  172. package/dist-standalone/identity.js +1 -619
  173. package/dist-standalone/index.d.ts +15 -4
  174. package/dist-standalone/index.js +1 -78
  175. package/dist-standalone/invitation.js +1 -415
  176. package/dist-standalone/invite.js +1 -324
  177. package/dist-standalone/key-agreement.js +1 -325
  178. package/dist-standalone/lazy-init.d.ts +11 -6
  179. package/dist-standalone/lazy-init.js +1 -295
  180. package/dist-standalone/logger.js +1 -285
  181. package/dist-standalone/loopback-transport.d.ts +87 -0
  182. package/dist-standalone/loopback-transport.js +1 -0
  183. package/dist-standalone/mdns-discovery.js +1 -195
  184. package/dist-standalone/nonce-store.js +1 -76
  185. package/dist-standalone/pairing-manager.js +1 -219
  186. package/dist-standalone/plugin-system.js +1 -257
  187. package/dist-standalone/plugins/logging.js +1 -163
  188. package/dist-standalone/plugins/metrics.d.ts +4 -4
  189. package/dist-standalone/plugins/metrics.js +1 -176
  190. package/dist-standalone/plugins/validation.js +1 -297
  191. package/dist-standalone/policy.js +1 -315
  192. package/dist-standalone/progress-callbacks.js +1 -576
  193. package/dist-standalone/redis-nonce-store.js +1 -72
  194. package/dist-standalone/registry-middleware.js +1 -47
  195. package/dist-standalone/retry-strategies.js +1 -534
  196. package/dist-standalone/retry-transport.js +1 -98
  197. package/dist-standalone/runtime/browser.js +1 -516
  198. package/dist-standalone/runtime/edge.js +1 -511
  199. package/dist-standalone/runtime/react-native.d.ts +1 -1
  200. package/dist-standalone/runtime/react-native.js +1 -383
  201. package/dist-standalone/security-policy.js +1 -239
  202. package/dist-standalone/serialization.js +1 -1031
  203. package/dist-standalone/split-channel.d.ts +1 -1
  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.d.ts +1 -1
  211. package/dist-standalone/transport.js +1 -59
  212. package/dist-standalone/trust-registry.d.ts +3 -3
  213. package/dist-standalone/trust-registry.js +1 -950
  214. package/dist-standalone/types/error-response.js +1 -52
  215. package/dist-standalone/vault-auth.js +1 -174
  216. package/dist-standalone/vault-store-loader.d.ts +9 -0
  217. package/dist-standalone/vault-store-loader.js +1 -187
  218. package/dist-standalone/verify.js +1 -16
  219. package/dist-standalone/version-info.js +1 -530
  220. package/dist-standalone/xfetch.js +1 -335
  221. package/package.json +1 -1
  222. package/share1.dat +0 -0
@@ -1,510 +1 @@
1
- /**
2
- * @module debug-mode
3
- * Debug mode for enhanced developer experience with verbose logging and state inspection
4
- *
5
- * Provides comprehensive debugging capabilities including:
6
- * - Verbose logging of all operations
7
- * - Internal state dumping and inspection
8
- * - Network request/response logging
9
- * - Crypto operation tracing
10
- * - Performance profiling and timing
11
- * - Memory usage tracking
12
- *
13
- * Usage:
14
- * ```typescript
15
- * import { enableDebugMode, dumpState, createDebugLogger } from '@private.me/xbind/debug-mode';
16
- *
17
- * // Enable debug mode globally
18
- * enableDebugMode({ verbose: true, traceNetwork: true });
19
- *
20
- * // Create debug logger for component
21
- * const debug = createDebugLogger('agent');
22
- * debug.trace('Operation starting', { did: 'did:key:...' });
23
- *
24
- * // Dump internal state
25
- * const state = dumpState(agent);
26
- * console.log(state);
27
- * ```
28
- */
29
- import { createLogger, LogLevel } from './logger.js';
30
- /**
31
- * Global debug mode state
32
- */
33
- class DebugModeState {
34
- enabled = false;
35
- options = {};
36
- measurements = [];
37
- networkTraces = [];
38
- cryptoTraces = [];
39
- stateSnapshots = [];
40
- activeTimers = new Map();
41
- }
42
- const globalDebugState = new DebugModeState();
43
- /**
44
- * Enable debug mode with optional configuration
45
- *
46
- * @param options - Debug mode options
47
- */
48
- export function enableDebugMode(options = {}) {
49
- globalDebugState.enabled = true;
50
- globalDebugState.options = {
51
- verbose: options.verbose ?? false,
52
- traceNetwork: options.traceNetwork ?? false,
53
- traceCrypto: options.traceCrypto ?? false,
54
- profile: options.profile ?? false,
55
- trackMemory: options.trackMemory ?? false,
56
- traceState: options.traceState ?? false,
57
- output: options.output ?? console.log,
58
- filters: options.filters,
59
- };
60
- const logger = createLogger('debug-mode');
61
- logger.setLevel(LogLevel.DEBUG);
62
- logger.info('Debug mode enabled', { options: globalDebugState.options });
63
- }
64
- /**
65
- * Disable debug mode and clear collected data
66
- */
67
- export function disableDebugMode() {
68
- globalDebugState.enabled = false;
69
- globalDebugState.measurements = [];
70
- globalDebugState.networkTraces = [];
71
- globalDebugState.cryptoTraces = [];
72
- globalDebugState.stateSnapshots = [];
73
- globalDebugState.activeTimers.clear();
74
- const logger = createLogger('debug-mode');
75
- logger.info('Debug mode disabled');
76
- }
77
- /**
78
- * Check if debug mode is enabled
79
- */
80
- export function isDebugEnabled() {
81
- return globalDebugState.enabled;
82
- }
83
- /**
84
- * Get current debug mode options
85
- */
86
- export function getDebugOptions() {
87
- return { ...globalDebugState.options };
88
- }
89
- /**
90
- * Create a debug logger for a specific component
91
- *
92
- * @param component - Component name
93
- * @returns Logger instance with debug capabilities
94
- */
95
- export function createDebugLogger(component) {
96
- const logger = createLogger(component);
97
- if (globalDebugState.enabled && globalDebugState.options.verbose) {
98
- logger.setLevel(LogLevel.DEBUG);
99
- }
100
- return {
101
- ...logger,
102
- trace(message, context) {
103
- if (!globalDebugState.enabled || !globalDebugState.options.verbose) {
104
- return;
105
- }
106
- // Apply filters if configured
107
- if (globalDebugState.options.filters) {
108
- const { include, exclude } = globalDebugState.options.filters;
109
- if (include && !include.some((pattern) => pattern.test(message))) {
110
- return;
111
- }
112
- if (exclude && exclude.some((pattern) => pattern.test(message))) {
113
- return;
114
- }
115
- }
116
- logger.debug(message, context);
117
- },
118
- };
119
- }
120
- /**
121
- * Start performance measurement for an operation
122
- *
123
- * @param operation - Operation name
124
- * @param context - Optional context
125
- */
126
- export function startProfiling(operation, context) {
127
- if (!globalDebugState.enabled || !globalDebugState.options.profile) {
128
- return;
129
- }
130
- const startTime = performance.now();
131
- globalDebugState.activeTimers.set(operation, { startTime, context });
132
- const logger = createDebugLogger('profiler');
133
- logger.trace(`[PROFILE] Starting: ${operation}`, context);
134
- }
135
- /**
136
- * End performance measurement and record result
137
- *
138
- * @param operation - Operation name
139
- * @param context - Optional context (overrides context from startProfiling if provided)
140
- */
141
- export function endProfiling(operation, context) {
142
- if (!globalDebugState.enabled || !globalDebugState.options.profile) {
143
- return;
144
- }
145
- const timerData = globalDebugState.activeTimers.get(operation);
146
- if (!timerData) {
147
- const logger = createDebugLogger('profiler');
148
- logger.warn(`[PROFILE] No start time found for: ${operation}`);
149
- return;
150
- }
151
- const endTime = performance.now();
152
- const duration = endTime - timerData.startTime;
153
- // Use context from endProfiling if provided, otherwise use context from startProfiling
154
- const finalContext = context ?? timerData.context;
155
- let memoryBefore;
156
- let memoryAfter;
157
- let memoryDelta;
158
- if (globalDebugState.options.trackMemory && typeof process !== 'undefined' && process.memoryUsage) {
159
- const mem = process.memoryUsage();
160
- memoryAfter = mem.heapUsed;
161
- // Estimate (not precise without tracking before)
162
- memoryBefore = memoryAfter;
163
- memoryDelta = 0;
164
- }
165
- const measurement = {
166
- operation,
167
- startTime: timerData.startTime,
168
- endTime,
169
- duration,
170
- memoryBefore,
171
- memoryAfter,
172
- memoryDelta,
173
- context: finalContext,
174
- };
175
- globalDebugState.measurements.push(measurement);
176
- globalDebugState.activeTimers.delete(operation);
177
- const logger = createDebugLogger('profiler');
178
- logger.trace(`[PROFILE] Completed: ${operation} (${duration.toFixed(2)}ms)`, {
179
- duration,
180
- memoryDelta,
181
- ...context,
182
- });
183
- }
184
- /**
185
- * Get all performance measurements
186
- */
187
- export function getPerformanceMeasurements() {
188
- return [...globalDebugState.measurements];
189
- }
190
- /**
191
- * Clear performance measurements
192
- */
193
- export function clearPerformanceMeasurements() {
194
- globalDebugState.measurements = [];
195
- globalDebugState.activeTimers.clear();
196
- }
197
- /**
198
- * Log network request start
199
- *
200
- * @param id - Request ID
201
- * @param method - HTTP method
202
- * @param url - URL
203
- * @param headers - Request headers
204
- * @param body - Request body
205
- */
206
- export function traceNetworkRequest(id, method, url, headers, body) {
207
- if (!globalDebugState.enabled || !globalDebugState.options.traceNetwork) {
208
- return;
209
- }
210
- const trace = {
211
- id,
212
- method,
213
- url,
214
- requestHeaders: redactHeaders(headers),
215
- requestBody: truncateBody(body),
216
- startTime: performance.now(),
217
- };
218
- globalDebugState.networkTraces.push(trace);
219
- const logger = createDebugLogger('network');
220
- logger.trace(`[NETWORK] ${method} ${url}`, {
221
- requestId: id,
222
- headers: trace.requestHeaders,
223
- bodyLength: body?.length ?? 0,
224
- });
225
- }
226
- /**
227
- * Log network response
228
- *
229
- * @param id - Request ID
230
- * @param status - HTTP status code
231
- * @param headers - Response headers
232
- * @param body - Response body
233
- * @param error - Error (if failed)
234
- */
235
- export function traceNetworkResponse(id, status, headers, body, error) {
236
- if (!globalDebugState.enabled || !globalDebugState.options.traceNetwork) {
237
- return;
238
- }
239
- const trace = globalDebugState.networkTraces.find((t) => t.id === id);
240
- if (!trace) {
241
- return;
242
- }
243
- trace.endTime = performance.now();
244
- trace.duration = trace.endTime - trace.startTime;
245
- trace.status = status;
246
- trace.responseHeaders = headers ? redactHeaders(headers) : undefined;
247
- trace.responseBody = truncateBody(body);
248
- trace.error = error;
249
- const logger = createDebugLogger('network');
250
- logger.trace(`[NETWORK] Response ${status ?? 'ERROR'} (${trace.duration.toFixed(2)}ms)`, {
251
- requestId: id,
252
- status,
253
- duration: trace.duration,
254
- error,
255
- });
256
- }
257
- /**
258
- * Get all network traces
259
- */
260
- export function getNetworkTraces() {
261
- return [...globalDebugState.networkTraces];
262
- }
263
- /**
264
- * Clear network traces
265
- */
266
- export function clearNetworkTraces() {
267
- globalDebugState.networkTraces = [];
268
- }
269
- /**
270
- * Log crypto operation
271
- *
272
- * @param operation - Operation type
273
- * @param algorithm - Algorithm name
274
- * @param inputSize - Input size (bytes)
275
- * @param outputSize - Output size (bytes)
276
- * @param duration - Duration (ms)
277
- * @param success - Success flag
278
- * @param error - Error message (if failed)
279
- */
280
- export function traceCryptoOperation(operation, algorithm, inputSize, outputSize, duration, success, error) {
281
- if (!globalDebugState.enabled || !globalDebugState.options.traceCrypto) {
282
- return;
283
- }
284
- const trace = {
285
- operation,
286
- algorithm,
287
- inputSize,
288
- outputSize,
289
- duration: duration ?? 0,
290
- success: success ?? true,
291
- error,
292
- timestamp: Date.now(),
293
- };
294
- globalDebugState.cryptoTraces.push(trace);
295
- const logger = createDebugLogger('crypto');
296
- logger.trace(`[CRYPTO] ${operation} (${algorithm})`, {
297
- inputSize,
298
- outputSize,
299
- duration,
300
- success,
301
- error,
302
- });
303
- }
304
- /**
305
- * Get all crypto traces
306
- */
307
- export function getCryptoTraces() {
308
- return [...globalDebugState.cryptoTraces];
309
- }
310
- /**
311
- * Clear crypto traces
312
- */
313
- export function clearCryptoTraces() {
314
- globalDebugState.cryptoTraces = [];
315
- }
316
- /**
317
- * Dump internal state of an agent
318
- *
319
- * @param agent - Agent instance
320
- * @returns State snapshot
321
- */
322
- export function dumpState(agent) {
323
- const snapshot = {
324
- did: agent.did,
325
- identityMode: agent.identityMode ?? 'persistent',
326
- registered: agent.registered ?? false,
327
- registryUrl: agent.registry?.url,
328
- nonceStoreType: agent.nonceStore?.constructor?.name ?? 'unknown',
329
- nonceCount: agent.nonceStore?.size ?? 0,
330
- transportType: agent.transport?.constructor?.name ?? 'unknown',
331
- securityPolicy: {
332
- level: agent.securityPolicy?.level ?? 'unknown',
333
- replayWindow: agent.securityPolicy?.replayWindow ?? 0,
334
- timestampTolerance: agent.securityPolicy?.timestampTolerance ?? 0,
335
- },
336
- postQuantum: agent.postQuantum ?? false,
337
- memoryUsage: typeof process !== 'undefined' && process.memoryUsage
338
- ? process.memoryUsage().heapUsed
339
- : undefined,
340
- timestamp: Date.now(),
341
- };
342
- if (globalDebugState.enabled && globalDebugState.options.traceState) {
343
- globalDebugState.stateSnapshots.push(snapshot);
344
- }
345
- const logger = createDebugLogger('state');
346
- logger.trace('[STATE] Agent snapshot', snapshot);
347
- return snapshot;
348
- }
349
- /**
350
- * Get all state snapshots
351
- */
352
- export function getStateSnapshots() {
353
- return [...globalDebugState.stateSnapshots];
354
- }
355
- /**
356
- * Clear state snapshots
357
- */
358
- export function clearStateSnapshots() {
359
- globalDebugState.stateSnapshots = [];
360
- }
361
- /**
362
- * Export all debug data as JSON
363
- *
364
- * @returns JSON string with all debug data
365
- */
366
- export function exportDebugData() {
367
- const data = {
368
- enabled: globalDebugState.enabled,
369
- options: globalDebugState.options,
370
- measurements: globalDebugState.measurements,
371
- networkTraces: globalDebugState.networkTraces,
372
- cryptoTraces: globalDebugState.cryptoTraces,
373
- stateSnapshots: globalDebugState.stateSnapshots,
374
- exportedAt: new Date().toISOString(),
375
- };
376
- return JSON.stringify(data, null, 2);
377
- }
378
- /**
379
- * Clear all debug data
380
- */
381
- export function clearAllDebugData() {
382
- clearPerformanceMeasurements();
383
- clearNetworkTraces();
384
- clearCryptoTraces();
385
- clearStateSnapshots();
386
- }
387
- /**
388
- * Redact sensitive headers
389
- */
390
- function redactHeaders(headers) {
391
- const redacted = {};
392
- const sensitiveHeaders = new Set([
393
- 'authorization',
394
- 'cookie',
395
- 'set-cookie',
396
- 'x-api-key',
397
- 'x-auth-token',
398
- ]);
399
- for (const [key, value] of Object.entries(headers)) {
400
- const lowerKey = key.toLowerCase();
401
- if (sensitiveHeaders.has(lowerKey)) {
402
- redacted[key] = '[REDACTED]';
403
- }
404
- else {
405
- redacted[key] = value;
406
- }
407
- }
408
- return redacted;
409
- }
410
- /**
411
- * Truncate body to reasonable size for logging
412
- */
413
- function truncateBody(body) {
414
- if (!body)
415
- return undefined;
416
- const maxLength = 1000;
417
- if (body.length <= maxLength) {
418
- return body;
419
- }
420
- return body.substring(0, maxLength) + `... (${body.length - maxLength} more bytes)`;
421
- }
422
- /**
423
- * Generate debug report
424
- *
425
- * @returns Human-readable debug report
426
- */
427
- export function generateDebugReport() {
428
- const lines = [];
429
- lines.push('='.repeat(80));
430
- lines.push('xBind Debug Report');
431
- lines.push('='.repeat(80));
432
- lines.push('');
433
- lines.push(`Generated: ${new Date().toISOString()}`);
434
- lines.push(`Debug Mode: ${globalDebugState.enabled ? 'ENABLED' : 'DISABLED'}`);
435
- lines.push('');
436
- if (globalDebugState.measurements.length > 0) {
437
- lines.push('Performance Measurements:');
438
- lines.push('-'.repeat(80));
439
- for (const m of globalDebugState.measurements) {
440
- lines.push(` ${m.operation}: ${m.duration.toFixed(2)}ms`);
441
- if (m.memoryDelta !== undefined) {
442
- lines.push(` Memory: ${formatBytes(m.memoryDelta)}`);
443
- }
444
- }
445
- lines.push('');
446
- }
447
- if (globalDebugState.networkTraces.length > 0) {
448
- lines.push('Network Traces:');
449
- lines.push('-'.repeat(80));
450
- for (const n of globalDebugState.networkTraces) {
451
- lines.push(` ${n.method} ${n.url}`);
452
- if (n.status) {
453
- lines.push(` Status: ${n.status}`);
454
- }
455
- if (n.duration) {
456
- lines.push(` Duration: ${n.duration.toFixed(2)}ms`);
457
- }
458
- if (n.error) {
459
- lines.push(` Error: ${n.error}`);
460
- }
461
- }
462
- lines.push('');
463
- }
464
- if (globalDebugState.cryptoTraces.length > 0) {
465
- lines.push('Crypto Operations:');
466
- lines.push('-'.repeat(80));
467
- for (const c of globalDebugState.cryptoTraces) {
468
- lines.push(` ${c.operation} (${c.algorithm})`);
469
- lines.push(` Input: ${formatBytes(c.inputSize)}`);
470
- if (c.outputSize) {
471
- lines.push(` Output: ${formatBytes(c.outputSize)}`);
472
- }
473
- lines.push(` Duration: ${c.duration.toFixed(2)}ms`);
474
- lines.push(` Success: ${c.success}`);
475
- if (c.error) {
476
- lines.push(` Error: ${c.error}`);
477
- }
478
- }
479
- lines.push('');
480
- }
481
- if (globalDebugState.stateSnapshots.length > 0) {
482
- lines.push('State Snapshots:');
483
- lines.push('-'.repeat(80));
484
- const latest = globalDebugState.stateSnapshots[globalDebugState.stateSnapshots.length - 1];
485
- if (latest) {
486
- lines.push(` DID: ${latest.did}`);
487
- lines.push(` Mode: ${latest.identityMode}`);
488
- lines.push(` Registered: ${latest.registered}`);
489
- lines.push(` Post-Quantum: ${latest.postQuantum}`);
490
- lines.push(` Nonce Count: ${latest.nonceCount}`);
491
- if (latest.memoryUsage) {
492
- lines.push(` Memory Usage: ${formatBytes(latest.memoryUsage)}`);
493
- }
494
- }
495
- lines.push('');
496
- }
497
- lines.push('='.repeat(80));
498
- return lines.join('\n');
499
- }
500
- /**
501
- * Format bytes as human-readable string
502
- */
503
- function formatBytes(bytes) {
504
- if (bytes === 0)
505
- return '0 B';
506
- const units = ['B', 'KB', 'MB', 'GB'];
507
- const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024));
508
- const value = bytes / Math.pow(1024, i);
509
- return `${value.toFixed(2)} ${units[i]}`;
510
- }
1
+ import{createLogger,LogLevel}from"./logger.js";class DebugModeState{enabled=!1;options={};measurements=[];networkTraces=[];cryptoTraces=[];stateSnapshots=[];activeTimers=new Map}const globalDebugState=new DebugModeState;export function enableDebugMode(e={}){globalDebugState.enabled=!0,globalDebugState.options={verbose:e.verbose??!1,traceNetwork:e.traceNetwork??!1,traceCrypto:e.traceCrypto??!1,profile:e.profile??!1,trackMemory:e.trackMemory??!1,traceState:e.traceState??!1,output:e.output??console.log,filters:e.filters};const t=createLogger("debug-mode");t.setLevel(LogLevel.DEBUG),t.info("Debug mode enabled",{options:globalDebugState.options})}export function disableDebugMode(){globalDebugState.enabled=!1,globalDebugState.measurements=[],globalDebugState.networkTraces=[],globalDebugState.cryptoTraces=[],globalDebugState.stateSnapshots=[],globalDebugState.activeTimers.clear();createLogger("debug-mode").info("Debug mode disabled")}export function isDebugEnabled(){return globalDebugState.enabled}export function getDebugOptions(){return{...globalDebugState.options}}export function createDebugLogger(e){const t=createLogger(e);return globalDebugState.enabled&&globalDebugState.options.verbose&&t.setLevel(LogLevel.DEBUG),{...t,trace(e,o){if(globalDebugState.enabled&&globalDebugState.options.verbose){if(globalDebugState.options.filters){const{include:t,exclude:o}=globalDebugState.options.filters;if(t&&!t.some(t=>t.test(e)))return;if(o&&o.some(t=>t.test(e)))return}t.debug(e,o)}}}}export function startProfiling(e,t){if(!globalDebugState.enabled||!globalDebugState.options.profile)return;const o=performance.now();globalDebugState.activeTimers.set(e,{startTime:o,context:t});createDebugLogger("profiler").trace(`[PROFILE] Starting: ${e}`,t)}export function endProfiling(e,t){if(!globalDebugState.enabled||!globalDebugState.options.profile)return;const o=globalDebugState.activeTimers.get(e);if(!o){return void createDebugLogger("profiler").warn(`[PROFILE] No start time found for: ${e}`)}const r=performance.now(),a=r-o.startTime,s=t??o.context;let n,u,g;if(globalDebugState.options.trackMemory&&"undefined"!=typeof process&&process.memoryUsage){u=process.memoryUsage().heapUsed,n=u,g=0}const l={operation:e,startTime:o.startTime,endTime:r,duration:a,memoryBefore:n,memoryAfter:u,memoryDelta:g,context:s};globalDebugState.measurements.push(l),globalDebugState.activeTimers.delete(e);createDebugLogger("profiler").trace(`[PROFILE] Completed: ${e} (${a.toFixed(2)}ms)`,{duration:a,memoryDelta:g,...t})}export function getPerformanceMeasurements(){return[...globalDebugState.measurements]}export function clearPerformanceMeasurements(){globalDebugState.measurements=[],globalDebugState.activeTimers.clear()}export function traceNetworkRequest(e,t,o,r,a){if(!globalDebugState.enabled||!globalDebugState.options.traceNetwork)return;const s={id:e,method:t,url:o,requestHeaders:redactHeaders(r),requestBody:truncateBody(a),startTime:performance.now()};globalDebugState.networkTraces.push(s);createDebugLogger("network").trace(`[NETWORK] ${t} ${o}`,{requestId:e,headers:s.requestHeaders,bodyLength:a?.length??0})}export function traceNetworkResponse(e,t,o,r,a){if(!globalDebugState.enabled||!globalDebugState.options.traceNetwork)return;const s=globalDebugState.networkTraces.find(t=>t.id===e);if(!s)return;s.endTime=performance.now(),s.duration=s.endTime-s.startTime,s.status=t,s.responseHeaders=o?redactHeaders(o):void 0,s.responseBody=truncateBody(r),s.error=a;createDebugLogger("network").trace(`[NETWORK] Response ${t??"ERROR"} (${s.duration.toFixed(2)}ms)`,{requestId:e,status:t,duration:s.duration,error:a})}export function getNetworkTraces(){return[...globalDebugState.networkTraces]}export function clearNetworkTraces(){globalDebugState.networkTraces=[]}export function traceCryptoOperation(e,t,o,r,a,s,n){if(!globalDebugState.enabled||!globalDebugState.options.traceCrypto)return;const u={operation:e,algorithm:t,inputSize:o,outputSize:r,duration:a??0,success:s??!0,error:n,timestamp:Date.now()};globalDebugState.cryptoTraces.push(u);createDebugLogger("crypto").trace(`[CRYPTO] ${e} (${t})`,{inputSize:o,outputSize:r,duration:a,success:s,error:n})}export function getCryptoTraces(){return[...globalDebugState.cryptoTraces]}export function clearCryptoTraces(){globalDebugState.cryptoTraces=[]}export function dumpState(e){const t=e,o={did:e.did,identityMode:t.identityMode??"persistent",registered:t.registered??!1,registryUrl:t.registry?.url,nonceStoreType:t.nonceStore?.constructor?.name??"unknown",nonceCount:t.nonceStore?.size??0,transportType:t.transport?.constructor?.name??"unknown",securityPolicy:{level:t.securityPolicy?.level??"unknown",replayWindow:t.securityPolicy?.replayWindow??0,timestampTolerance:t.securityPolicy?.timestampTolerance??0},postQuantum:t.postQuantum??!1,memoryUsage:"undefined"!=typeof process&&process.memoryUsage?process.memoryUsage().heapUsed:void 0,timestamp:Date.now()};globalDebugState.enabled&&globalDebugState.options.traceState&&globalDebugState.stateSnapshots.push(o);return createDebugLogger("state").trace("[STATE] Agent snapshot",o),o}export function getStateSnapshots(){return[...globalDebugState.stateSnapshots]}export function clearStateSnapshots(){globalDebugState.stateSnapshots=[]}export function exportDebugData(){const e={enabled:globalDebugState.enabled,options:globalDebugState.options,measurements:globalDebugState.measurements,networkTraces:globalDebugState.networkTraces,cryptoTraces:globalDebugState.cryptoTraces,stateSnapshots:globalDebugState.stateSnapshots,exportedAt:(new Date).toISOString()};return JSON.stringify(e,null,2)}export function clearAllDebugData(){clearPerformanceMeasurements(),clearNetworkTraces(),clearCryptoTraces(),clearStateSnapshots()}function redactHeaders(e){const t={},o=new Set(["authorization","cookie","set-cookie","x-api-key","x-auth-token"]);for(const[r,a]of Object.entries(e)){const e=r.toLowerCase();o.has(e)?t[r]="[REDACTED]":t[r]=a}return t}function truncateBody(e){if(!e)return;const t=1e3;return e.length<=t?e:e.substring(0,t)+`... (${e.length-t} more bytes)`}export function generateDebugReport(){const e=[];if(e.push("=".repeat(80)),e.push("xBind Debug Report"),e.push("=".repeat(80)),e.push(""),e.push(`Generated: ${(new Date).toISOString()}`),e.push("Debug Mode: "+(globalDebugState.enabled?"ENABLED":"DISABLED")),e.push(""),globalDebugState.measurements.length>0){e.push("Performance Measurements:"),e.push("-".repeat(80));for(const t of globalDebugState.measurements)e.push(` ${t.operation}: ${t.duration.toFixed(2)}ms`),void 0!==t.memoryDelta&&e.push(` Memory: ${formatBytes(t.memoryDelta)}`);e.push("")}if(globalDebugState.networkTraces.length>0){e.push("Network Traces:"),e.push("-".repeat(80));for(const t of globalDebugState.networkTraces)e.push(` ${t.method} ${t.url}`),t.status&&e.push(` Status: ${t.status}`),t.duration&&e.push(` Duration: ${t.duration.toFixed(2)}ms`),t.error&&e.push(` Error: ${t.error}`);e.push("")}if(globalDebugState.cryptoTraces.length>0){e.push("Crypto Operations:"),e.push("-".repeat(80));for(const t of globalDebugState.cryptoTraces)e.push(` ${t.operation} (${t.algorithm})`),e.push(` Input: ${formatBytes(t.inputSize)}`),t.outputSize&&e.push(` Output: ${formatBytes(t.outputSize)}`),e.push(` Duration: ${t.duration.toFixed(2)}ms`),e.push(` Success: ${t.success}`),t.error&&e.push(` Error: ${t.error}`);e.push("")}if(globalDebugState.stateSnapshots.length>0){e.push("State Snapshots:"),e.push("-".repeat(80));const t=globalDebugState.stateSnapshots[globalDebugState.stateSnapshots.length-1];t&&(e.push(` DID: ${t.did}`),e.push(` Mode: ${t.identityMode}`),e.push(` Registered: ${t.registered}`),e.push(` Post-Quantum: ${t.postQuantum}`),e.push(` Nonce Count: ${t.nonceCount}`),t.memoryUsage&&e.push(` Memory Usage: ${formatBytes(t.memoryUsage)}`)),e.push("")}return e.push("=".repeat(80)),e.join("\n")}function formatBytes(e){if(0===e)return"0 B";const t=Math.floor(Math.log(Math.abs(e))/Math.log(1024));return`${(e/Math.pow(1024,t)).toFixed(2)} ${["B","KB","MB","GB"][t]}`}
@@ -1,96 +1 @@
1
- import { ok, err } from"./_deps/shared/index.js";
2
- import { toBase64 } from './crypto-utils.js';
3
- /**
4
- * Generate a DID document for a given DID.
5
- *
6
- * Includes service endpoints that advertise PRIVATE.ME/xBind.
7
- * Both did:key and did:privateme DIDs generate the same service endpoints.
8
- *
9
- * @param did - The DID (did:key:z... or did:privateme:z...)
10
- * @param rawPublicKey - The 32-byte Ed25519 public key
11
- * @param name - Optional name for the identity
12
- * @returns DID document with service endpoints
13
- */
14
- export function generateDidDocument(did, rawPublicKey, name) {
15
- if (!did.startsWith('did:key:') && !did.startsWith('did:privateme:')) {
16
- return err('INVALID_DID_FORMAT');
17
- }
18
- // Convert public key to base64 for inclusion in document
19
- const publicKeyBase64 = toBase64(rawPublicKey);
20
- const document = {
21
- '@context': [
22
- 'https://www.w3.org/ns/did/v1',
23
- 'https://w3id.org/security/suites/ed25519-2020/v1',
24
- ],
25
- id: did,
26
- publicKey: [
27
- {
28
- id: `${did}#key-1`,
29
- type: 'Ed25519VerificationKey2020',
30
- controller: did,
31
- publicKeyBase64,
32
- },
33
- ],
34
- authentication: [`${did}#key-1`],
35
- assertionMethod: [`${did}#key-1`],
36
- keyAgreement: [`${did}#key-1`],
37
- service: [
38
- {
39
- id: `${did}#identity-provider`,
40
- type: 'IdentityProvider',
41
- serviceEndpoint: 'https://private.me',
42
- description: 'PRIVATE.ME xBind Agent - M2M identity authentication',
43
- },
44
- {
45
- id: `${did}#documentation`,
46
- type: 'Documentation',
47
- serviceEndpoint: 'https://private.me/docs/xbind.html',
48
- description: 'Learn more about PRIVATE.ME/xBind protocol',
49
- },
50
- ],
51
- ...(name ? { name } : {}),
52
- };
53
- return ok(document);
54
- }
55
- /**
56
- * Resolve a DID to its document (simulated).
57
- *
58
- * In a production system, this would query a DID resolver.
59
- * For now, this generates a synthetic document based on the DID.
60
- *
61
- * @param did - The DID to resolve
62
- * @param rawPublicKey - The 32-byte Ed25519 public key
63
- * @returns DID document or error
64
- */
65
- export async function resolveDid(did, rawPublicKey) {
66
- // In a production system, this would make an HTTP request to a DID resolver
67
- // For now, generate a synthetic document
68
- return generateDidDocument(did, rawPublicKey);
69
- }
70
- /**
71
- * Extract service endpoints from a DID document.
72
- *
73
- * Filters for PRIVATE.ME service endpoints to provide discovery information.
74
- *
75
- * @param document - The DID document
76
- * @returns Array of service endpoints advertising PRIVATE.ME services
77
- */
78
- export function getServiceEndpoints(document) {
79
- if (!document.service)
80
- return [];
81
- return document.service
82
- .filter((svc) => {
83
- const endpoint = typeof svc.serviceEndpoint === 'string' ? svc.serviceEndpoint : '';
84
- return (endpoint.includes('private.me') ||
85
- svc.type.includes('PRIVATE.ME') ||
86
- svc.type === 'IdentityProvider' ||
87
- svc.type === 'Documentation');
88
- })
89
- .map((svc) => ({
90
- type: svc.type,
91
- endpoint: typeof svc.serviceEndpoint === 'string'
92
- ? svc.serviceEndpoint
93
- : JSON.stringify(svc.serviceEndpoint),
94
- description: svc.description,
95
- }));
96
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{toBase64}from"./crypto-utils.js";export function generateDidDocument(e,t,i){if(!e.startsWith("did:key:")&&!e.startsWith("did:privateme:"))return err("INVALID_DID_FORMAT");const n={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/ed25519-2020/v1"],id:e,publicKey:[{id:`${e}#key-1`,type:"Ed25519VerificationKey2020",controller:e,publicKeyBase64:toBase64(t)}],authentication:[`${e}#key-1`],assertionMethod:[`${e}#key-1`],keyAgreement:[`${e}#key-1`],service:[{id:`${e}#identity-provider`,type:"IdentityProvider",serviceEndpoint:"https://private.me",description:"PRIVATE.ME xBind Agent - M2M identity authentication"},{id:`${e}#documentation`,type:"Documentation",serviceEndpoint:"https://private.me/docs/xbind.html",description:"Learn more about PRIVATE.ME/xBind protocol"}],...i?{name:i}:{}};return ok(n)}export async function resolveDid(e,t){return generateDidDocument(e,t)}export function getServiceEndpoints(e){return e.service?e.service.filter(e=>("string"==typeof e.serviceEndpoint?e.serviceEndpoint:"").includes("private.me")||e.type.includes("PRIVATE.ME")||"IdentityProvider"===e.type||"Documentation"===e.type).map(e=>({type:e.type,endpoint:"string"==typeof e.serviceEndpoint?e.serviceEndpoint:JSON.stringify(e.serviceEndpoint),description:e.description})):[]}