@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,335 +1 @@
1
- /**
2
- * @module xfetch
3
- * Drop-in fetch() replacement with auto-upgrade to xBind
4
- *
5
- * Provides transparent upgrade from HTTP to xBind when both parties support it.
6
- * Falls back to regular HTTP fetch() when xBind is not available.
7
- */
8
- import { Agent } from './agent.js';
9
- import { AgentError, AgentErrorCode } from './agent-call.js';
10
- /**
11
- * Check if endpoint supports xBind
12
- *
13
- * Sends OPTIONS request with xBind capability header.
14
- * Endpoint responds with xBind-Support header if available.
15
- *
16
- * @param url - Target URL
17
- * @returns Capability check result
18
- */
19
- async function checkXBindSupport(url) {
20
- try {
21
- const response = await fetch(url, {
22
- method: 'OPTIONS',
23
- headers: {
24
- 'X-Capability-Check': 'xbind',
25
- },
26
- });
27
- const supported = response.headers.get('X-xBind-Support') === 'true';
28
- if (!supported) {
29
- return { supported: false };
30
- }
31
- return {
32
- supported: true,
33
- endpoint: response.headers.get('X-xBind-Endpoint') || undefined,
34
- peerDID: response.headers.get('X-xBind-DID') || undefined,
35
- version: response.headers.get('X-xBind-Version') || undefined,
36
- };
37
- }
38
- catch (error) {
39
- // Network error or CORS - assume no xBind support
40
- return { supported: false };
41
- }
42
- }
43
- /**
44
- * Send request via xBind transport
45
- *
46
- * Uses synchronous request-response pattern with direct signing and encryption.
47
- * This is more appropriate for HTTP semantics than async agent.send().
48
- *
49
- * Architecture:
50
- * 1. Wrap HTTP request in payload
51
- * 2. Add correlation ID for response matching
52
- * 3. Send via agent.send() to server DID
53
- * 4. Wait for response with matching correlation ID
54
- * 5. Decrypt and verify response
55
- * 6. Return as standard HTTP Response
56
- *
57
- * @param url - Target URL
58
- * @param capability - xBind capability info
59
- * @param options - Request options
60
- * @param agent - Agent instance
61
- * @returns xBind response
62
- */
63
- async function sendViaXBind(url, capability, options, agent) {
64
- const startTime = Date.now();
65
- // Validate that server provided DID and endpoint
66
- if (!capability.peerDID) {
67
- throw new AgentError(AgentErrorCode.NETWORK_ERROR, 'Server supports xBind but did not provide X-xBind-DID header', { url, capability });
68
- }
69
- const peerDID = capability.peerDID; // Type narrowing for later use
70
- const xbindEndpoint = capability.endpoint || url;
71
- // Generate secure correlation ID using crypto.getRandomValues()
72
- const randomBytes = new Uint8Array(16);
73
- crypto.getRandomValues(randomBytes);
74
- const randomHex = Array.from(randomBytes)
75
- .map(b => b.toString(16).padStart(2, '0'))
76
- .join('');
77
- const correlationId = `xfetch_${Date.now()}_${randomHex}`;
78
- // Build HTTP request payload to wrap in envelope
79
- const httpRequest = {
80
- correlationId,
81
- method: options.method || 'GET',
82
- url,
83
- headers: options.headers || {},
84
- body: options.body ? (typeof options.body === 'string'
85
- ? options.body
86
- : JSON.stringify(options.body)) : undefined,
87
- };
88
- // Set up response handler BEFORE sending request
89
- const responsePromise = new Promise((resolve, reject) => {
90
- const timeout = setTimeout(() => {
91
- reject(new AgentError(AgentErrorCode.TIMEOUT, 'xBind request timed out waiting for response', { url, correlationId, timeout: options.timeout || 30000 }));
92
- }, options.timeout || 30000);
93
- // Listen for response message
94
- // TODO: This requires agent to support message handlers
95
- // For now, we'll use a polling approach via the server's HTTP endpoint
96
- // Alternative: Send request and poll for response
97
- // This is less elegant but works without modifying Agent
98
- (async () => {
99
- try {
100
- // Send request via agent.send()
101
- const sendResult = await agent.send({
102
- to: peerDID,
103
- payload: httpRequest,
104
- scope: 'xfetch',
105
- action: 'http_request',
106
- });
107
- if (!sendResult.ok) {
108
- clearTimeout(timeout);
109
- reject(new AgentError(AgentErrorCode.NETWORK_ERROR, `Failed to send xBind request: ${sendResult.error}`, { url, error: sendResult.error }));
110
- return;
111
- }
112
- // Poll server for response (synchronous HTTP endpoint)
113
- // Server should provide /xfetch/response/:correlationId endpoint
114
- const responseUrl = `${xbindEndpoint}/response/${correlationId}`;
115
- const pollInterval = 100; // Poll every 100ms
116
- const maxPolls = (options.timeout || 30000) / pollInterval;
117
- for (let i = 0; i < maxPolls; i++) {
118
- await new Promise(r => setTimeout(r, pollInterval));
119
- try {
120
- const response = await fetch(responseUrl);
121
- if (response.status === 200) {
122
- // Got response
123
- clearTimeout(timeout);
124
- const latency = Date.now() - startTime;
125
- resolve(Object.assign(response, {
126
- usedXBind: true,
127
- transport: {
128
- protocol: 'xbind',
129
- latency,
130
- peerDID: peerDID,
131
- },
132
- }));
133
- return;
134
- }
135
- // 404 or 202 means still processing, continue polling
136
- }
137
- catch (pollError) {
138
- // Network error during polling, continue
139
- continue;
140
- }
141
- }
142
- // Timeout
143
- clearTimeout(timeout);
144
- reject(new AgentError(AgentErrorCode.TIMEOUT, 'Response not available after polling', { url, correlationId, polls: maxPolls }));
145
- }
146
- catch (error) {
147
- clearTimeout(timeout);
148
- reject(error instanceof AgentError ? error : new AgentError(AgentErrorCode.NETWORK_ERROR, 'xBind request failed', { url, error: String(error) }));
149
- }
150
- })();
151
- });
152
- return responsePromise;
153
- }
154
- /**
155
- * Send request via standard HTTP fetch
156
- *
157
- * @param url - Target URL
158
- * @param options - Request options
159
- * @returns HTTP response wrapped as XFetchResponse
160
- */
161
- async function sendViaHTTP(url, options) {
162
- const startTime = Date.now();
163
- // Remove xFetch-specific options before passing to fetch
164
- const { forceXBind, disableXBind, agent, retry, ...fetchOptions } = options;
165
- const response = await fetch(url, fetchOptions);
166
- const latency = Date.now() - startTime;
167
- // Wrap Response with xFetch metadata
168
- return Object.assign(response, {
169
- usedXBind: false,
170
- transport: {
171
- protocol: url.startsWith('https') ? 'https' : 'http',
172
- latency,
173
- },
174
- });
175
- }
176
- /**
177
- * Retry logic with exponential backoff
178
- *
179
- * @param fn - Function to retry
180
- * @param options - Retry configuration
181
- * @returns Result of function
182
- */
183
- async function withRetry(fn, options) {
184
- const maxAttempts = options?.maxAttempts ?? 3;
185
- const initialDelay = options?.initialDelay ?? 1000;
186
- const multiplier = options?.multiplier ?? 2;
187
- let lastError;
188
- let delay = initialDelay;
189
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
190
- try {
191
- return await fn();
192
- }
193
- catch (error) {
194
- lastError = error instanceof Error ? error : new Error(String(error));
195
- // Don't retry on client errors (4xx)
196
- if (error instanceof Response && error.status >= 400 && error.status < 500) {
197
- throw error;
198
- }
199
- if (attempt < maxAttempts) {
200
- await new Promise((resolve) => setTimeout(resolve, delay));
201
- delay *= multiplier;
202
- }
203
- }
204
- }
205
- throw lastError;
206
- }
207
- /**
208
- * xFetch - Drop-in fetch() replacement with auto-upgrade to xBind
209
- *
210
- * @param url - Target URL
211
- * @param options - Request options (extends fetch RequestInit)
212
- * @returns Response with xBind metadata
213
- *
214
- * @example
215
- * ```typescript
216
- * // Basic usage (auto-upgrades to xBind if supported)
217
- * const response = await xfetch('https://api.example.com/data');
218
- * console.log('Used xBind?', response.usedXBind);
219
- * const data = await response.json();
220
- * ```
221
- *
222
- * @example
223
- * ```typescript
224
- * // Force xBind (fail if not supported)
225
- * const response = await xfetch('https://api.example.com/secure', {
226
- * forceXBind: true,
227
- * });
228
- * ```
229
- *
230
- * @example
231
- * ```typescript
232
- * // Disable xBind (HTTP only)
233
- * const response = await xfetch('https://api.example.com/public', {
234
- * disableXBind: true,
235
- * });
236
- * ```
237
- *
238
- * @example
239
- * ```typescript
240
- * // With retry and timeout
241
- * const response = await xfetch('https://api.example.com/data', {
242
- * timeout: 10000,
243
- * retry: {
244
- * maxAttempts: 5,
245
- * initialDelay: 500,
246
- * multiplier: 2,
247
- * },
248
- * });
249
- * ```
250
- */
251
- export async function xfetch(url, options = {}) {
252
- // Validate URL
253
- let parsedURL;
254
- try {
255
- parsedURL = new URL(url);
256
- }
257
- catch (error) {
258
- throw new AgentError(AgentErrorCode.INVALID_PARAMS, `Invalid URL: ${url}`, { url, error });
259
- }
260
- // Only support HTTP(S) protocols
261
- if (!['http:', 'https:'].includes(parsedURL.protocol)) {
262
- throw new AgentError(AgentErrorCode.INVALID_PARAMS, `Unsupported protocol: ${parsedURL.protocol}`, { url, protocol: parsedURL.protocol });
263
- }
264
- // Apply timeout if specified
265
- const timeout = options.timeout ?? 30000;
266
- const controller = new AbortController();
267
- const timeoutId = setTimeout(() => controller.abort(), timeout);
268
- try {
269
- // Merge abort signals if user provided one
270
- const signal = options.signal
271
- ? AbortSignal.any?.([options.signal, controller.signal]) ?? controller.signal
272
- : controller.signal;
273
- const requestOptions = {
274
- ...options,
275
- signal,
276
- };
277
- // If xBind is explicitly disabled, use HTTP directly
278
- if (options.disableXBind) {
279
- return await withRetry(() => sendViaHTTP(url, requestOptions), options.retry);
280
- }
281
- // Check if endpoint supports xBind
282
- const capability = await checkXBindSupport(url);
283
- // If xBind is forced but not supported, fail
284
- if (options.forceXBind && !capability.supported) {
285
- throw new AgentError(AgentErrorCode.NETWORK_ERROR, `xBind required but endpoint does not support it: ${url}`, { url, forceXBind: true, capability });
286
- }
287
- // If xBind is supported, use it
288
- if (capability.supported) {
289
- // Create or use provided agent
290
- const agent = options.agent ?? await Agent.from({ identity: 'ephemeral', identityTTL: 3600000 });
291
- return await withRetry(() => sendViaXBind(url, capability, requestOptions, agent), options.retry);
292
- }
293
- // Fallback to HTTP
294
- return await withRetry(() => sendViaHTTP(url, requestOptions), options.retry);
295
- }
296
- finally {
297
- clearTimeout(timeoutId);
298
- }
299
- }
300
- /**
301
- * Check if a URL supports xBind
302
- *
303
- * Utility function for checking xBind support before making a request.
304
- *
305
- * @param url - URL to check
306
- * @returns True if endpoint supports xBind
307
- *
308
- * @example
309
- * ```typescript
310
- * const supported = await isXBindSupported('https://api.example.com');
311
- * if (supported) {
312
- * console.log('Endpoint supports xBind - request will be upgraded');
313
- * }
314
- * ```
315
- */
316
- export async function isXBindSupported(url) {
317
- const capability = await checkXBindSupport(url);
318
- return capability.supported;
319
- }
320
- /**
321
- * Get xBind capability information for a URL
322
- *
323
- * @param url - URL to check
324
- * @returns Capability information
325
- *
326
- * @example
327
- * ```typescript
328
- * const info = await getXBindCapability('https://api.example.com');
329
- * console.log('Peer DID:', info.peerDID);
330
- * console.log('xBind version:', info.version);
331
- * ```
332
- */
333
- export async function getXBindCapability(url) {
334
- return checkXBindSupport(url);
335
- }
1
+ import{Agent}from"./agent.js";import{AgentError,AgentErrorCode}from"./agent-call.js";async function checkXBindSupport(t){try{const e=await fetch(t,{method:"OPTIONS",headers:{"X-Capability-Check":"xbind"}});return"true"===e.headers.get("X-xBind-Support")?{supported:!0,endpoint:e.headers.get("X-xBind-Endpoint")||void 0,peerDID:e.headers.get("X-xBind-DID")||void 0,version:e.headers.get("X-xBind-Version")||void 0}:{supported:!1}}catch{return{supported:!1}}}async function sendViaXBind(t,e,r,o){const n=Date.now();if(!e.peerDID)throw new AgentError(AgentErrorCode.NETWORK_ERROR,"Server supports xBind but did not provide X-xBind-DID header",{url:t,capability:e});const i=e.peerDID,a=e.endpoint||t,s=new Uint8Array(16);crypto.getRandomValues(s);const d=Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join(""),c=`xfetch_${Date.now()}_${d}`,p={correlationId:c,method:r.method||"GET",url:t,headers:r.headers||{},body:r.body?"string"==typeof r.body?r.body:JSON.stringify(r.body):void 0};return new Promise((e,s)=>{const d=setTimeout(()=>{s(new AgentError(AgentErrorCode.TIMEOUT,"xBind request timed out waiting for response",{url:t,correlationId:c,timeout:r.timeout||3e4}))},r.timeout||3e4);(async()=>{try{const u=await o.send({to:i,payload:p,scope:"xfetch",action:"http_request"});if(!u.ok)return clearTimeout(d),void s(new AgentError(AgentErrorCode.NETWORK_ERROR,`Failed to send xBind request: ${u.error}`,{url:t,error:u.error}));const l=`${a}/response/${c}`,g=100,h=(r.timeout||3e4)/g;for(let t=0;t<h;t++){await new Promise(t=>setTimeout(t,g));try{const t=await fetch(l);if(200===t.status){clearTimeout(d);const r=Date.now()-n;return void e(Object.assign(t,{usedXBind:!0,transport:{protocol:"xbind",latency:r,peerDID:i}}))}}catch{continue}}clearTimeout(d),s(new AgentError(AgentErrorCode.TIMEOUT,"Response not available after polling",{url:t,correlationId:c,polls:h}))}catch(e){clearTimeout(d),s(e instanceof AgentError?e:new AgentError(AgentErrorCode.NETWORK_ERROR,"xBind request failed",{url:t,error:String(e)}))}})()})}async function sendViaHTTP(t,e){const r=Date.now(),{forceXBind:o,disableXBind:n,agent:i,retry:a,...s}=e,d=await fetch(t,s),c=Date.now()-r;return Object.assign(d,{usedXBind:!1,transport:{protocol:t.startsWith("https")?"https":"http",latency:c}})}async function withRetry(t,e){const r=e?.maxAttempts??3,o=e?.initialDelay??1e3,n=e?.multiplier??2;let i,a=o;for(let e=1;e<=r;e++)try{return await t()}catch(t){if(i=t instanceof Error?t:new Error(String(t)),t instanceof Response&&t.status>=400&&t.status<500)throw t;e<r&&(await new Promise(t=>setTimeout(t,a)),a*=n)}throw i}export async function xfetch(t,e={}){let r;try{r=new URL(t)}catch(e){throw new AgentError(AgentErrorCode.INVALID_PARAMS,`Invalid URL: ${t}`,{url:t,error:e})}if(!["http:","https:"].includes(r.protocol))throw new AgentError(AgentErrorCode.INVALID_PARAMS,`Unsupported protocol: ${r.protocol}`,{url:t,protocol:r.protocol});const o=e.timeout??3e4,n=new AbortController,i=setTimeout(()=>n.abort(),o);try{const r=e.signal?AbortSignal.any?.([e.signal,n.signal])??n.signal:n.signal,o={...e,signal:r};if(e.disableXBind)return await withRetry(()=>sendViaHTTP(t,o),e.retry);const i=await checkXBindSupport(t);if(e.forceXBind&&!i.supported)throw new AgentError(AgentErrorCode.NETWORK_ERROR,`xBind required but endpoint does not support it: ${t}`,{url:t,forceXBind:!0,capability:i});if(i.supported){const r=e.agent??await Agent.from({identity:"ephemeral",identityTTL:36e5});return await withRetry(()=>sendViaXBind(t,i,o,r),e.retry)}return await withRetry(()=>sendViaHTTP(t,o),e.retry)}finally{clearTimeout(i)}}export async function isXBindSupported(t){return(await checkXBindSupport(t)).supported}export async function getXBindCapability(t){return checkXBindSupport(t)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@private.me/xbind",
3
- "version": "3.0.2",
3
+ "version": "3.0.3",
4
4
  "description": "Identity-based M2M authentication (Contains encryption - export restrictions apply)",
5
5
  "license": "Proprietary",
6
6
  "author": "Private.Me Contributors",
package/share1.dat CHANGED
Binary file