@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,511 +1 @@
1
- /**
2
- * Edge Runtime Support for xBind
3
- *
4
- * Enables xBind to run on edge compute platforms:
5
- * - Cloudflare Workers
6
- * - Vercel Edge Functions
7
- * - Deno Deploy
8
- *
9
- * Key Features:
10
- * - Edge-compatible crypto operations (Web Crypto API only)
11
- * - KV storage integration for nonce stores and trust registry
12
- * - Size-optimized build (<1MB constraint)
13
- * - No Node.js dependencies (no fs, crypto, process)
14
- */
15
- import { ok, err } from"../_deps/shared/index.js";
16
- /**
17
- * Detect the current edge runtime environment.
18
- *
19
- * Detection order:
20
- * 1. Cloudflare Workers: globalThis.caches + EdgeRuntime
21
- * 2. Vercel Edge: process.env.VERCEL + EdgeRuntime
22
- * 3. Deno Deploy: globalThis.Deno
23
- * 4. Node.js: process.versions.node
24
- * 5. Unknown: fallback
25
- */
26
- export function detectRuntime() {
27
- // SAFETY: Edge runtime detection requires checking for vendor-specific globals
28
- const global = globalThis;
29
- // Cloudflare Workers: Has global caches API and no process
30
- if (typeof global.caches !== 'undefined' &&
31
- typeof global.EdgeRuntime === 'string') {
32
- return 'cloudflare';
33
- }
34
- // Vercel Edge: Has EdgeRuntime and process.env.VERCEL
35
- if (typeof global.EdgeRuntime === 'string' &&
36
- typeof process !== 'undefined' &&
37
- process.env?.VERCEL === '1') {
38
- return 'vercel';
39
- }
40
- // Deno Deploy: Has global Deno object
41
- if (typeof global.Deno !== 'undefined') {
42
- return 'deno';
43
- }
44
- // Node.js: Has process.versions.node
45
- if (typeof process !== 'undefined' &&
46
- typeof process.versions?.node === 'string') {
47
- return 'node';
48
- }
49
- return 'unknown';
50
- }
51
- /**
52
- * Check if the current runtime is an edge environment.
53
- */
54
- export function isEdgeRuntime() {
55
- const runtime = detectRuntime();
56
- return runtime === 'cloudflare' || runtime === 'vercel' || runtime === 'deno';
57
- }
58
- /**
59
- * Validate that the runtime supports required Web Crypto APIs.
60
- *
61
- * Edge runtimes MUST provide:
62
- * - crypto.subtle (Ed25519, X25519, AES-GCM, HMAC)
63
- * - crypto.getRandomValues()
64
- * - TextEncoder/TextDecoder
65
- */
66
- export function validateEdgeRuntime() {
67
- // Check Web Crypto API
68
- if (typeof globalThis.crypto === 'undefined') {
69
- return err('Missing globalThis.crypto');
70
- }
71
- if (typeof globalThis.crypto.subtle === 'undefined') {
72
- return err('Missing crypto.subtle');
73
- }
74
- if (typeof globalThis.crypto.getRandomValues !== 'function') {
75
- return err('Missing crypto.getRandomValues');
76
- }
77
- // Check required subtle crypto methods
78
- const requiredMethods = [
79
- 'generateKey',
80
- 'sign',
81
- 'verify',
82
- 'encrypt',
83
- 'decrypt',
84
- 'deriveBits',
85
- 'importKey',
86
- 'exportKey',
87
- ];
88
- for (const method of requiredMethods) {
89
- if (typeof globalThis.crypto.subtle[method] !== 'function') {
90
- return err(`Missing crypto.subtle.${method}`);
91
- }
92
- }
93
- // Check TextEncoder/TextDecoder
94
- if (typeof globalThis.TextEncoder === 'undefined') {
95
- return err('Missing TextEncoder');
96
- }
97
- if (typeof globalThis.TextDecoder === 'undefined') {
98
- return err('Missing TextDecoder');
99
- }
100
- // Check fetch API
101
- if (typeof globalThis.fetch !== 'function') {
102
- return err('Missing fetch API');
103
- }
104
- return ok(undefined);
105
- }
106
- /**
107
- * Adapter for Cloudflare Workers KV.
108
- */
109
- export class CloudflareKVAdapter {
110
- namespace;
111
- constructor(namespace) {
112
- this.namespace = namespace;
113
- }
114
- async get(key) {
115
- return await this.namespace.get(key);
116
- }
117
- async put(key, value, ttlSeconds) {
118
- const options = ttlSeconds ? { expirationTtl: ttlSeconds } : undefined;
119
- await this.namespace.put(key, value, options);
120
- }
121
- async delete(key) {
122
- await this.namespace.delete(key);
123
- }
124
- async list(prefix, limit) {
125
- const result = await this.namespace.list({ prefix, limit });
126
- return result.keys.map((k) => k.name);
127
- }
128
- }
129
- /**
130
- * Adapter for Vercel KV (Redis).
131
- */
132
- export class VercelKVAdapter {
133
- client;
134
- constructor(client) {
135
- this.client = client;
136
- }
137
- async get(key) {
138
- return await this.client.get(key);
139
- }
140
- async put(key, value, ttlSeconds) {
141
- const options = ttlSeconds ? { ex: ttlSeconds } : undefined;
142
- await this.client.set(key, value, options);
143
- }
144
- async delete(key) {
145
- await this.client.del(key);
146
- }
147
- async list(prefix, limit) {
148
- const pattern = prefix ? `${prefix}*` : '*';
149
- const allKeys = await this.client.keys(pattern);
150
- return limit ? allKeys.slice(0, limit) : allKeys;
151
- }
152
- }
153
- /**
154
- * Adapter for Deno KV.
155
- */
156
- export class DenoKVAdapter {
157
- kv;
158
- constructor(kv) {
159
- this.kv = kv;
160
- }
161
- async get(key) {
162
- const result = await this.kv.get([key]);
163
- return result.value;
164
- }
165
- async put(key, value, ttlSeconds) {
166
- const options = ttlSeconds ? { expireIn: ttlSeconds * 1000 } : undefined;
167
- await this.kv.set([key], value, options);
168
- }
169
- async delete(key) {
170
- await this.kv.delete([key]);
171
- }
172
- async list(prefix, limit) {
173
- const selector = { prefix: prefix ? [prefix] : [] };
174
- const keys = [];
175
- for await (const entry of this.kv.list(selector)) {
176
- keys.push(entry.key.join('/'));
177
- if (limit && keys.length >= limit)
178
- break;
179
- }
180
- return keys;
181
- }
182
- }
183
- /* ── KV-Backed Nonce Store ── */
184
- /**
185
- * Nonce store implementation using KV storage.
186
- *
187
- * Suitable for edge runtimes where in-memory storage
188
- * is ephemeral across invocations.
189
- */
190
- export class KVNonceStore {
191
- kv;
192
- ttlSeconds;
193
- constructor(kv, ttlMs = 10 * 60 * 1000) {
194
- this.kv = kv;
195
- this.ttlSeconds = Math.floor(ttlMs / 1000);
196
- }
197
- /**
198
- * Build composite key: xbind:nonce:{senderDid}:{nonce}:{shareGroupId}:{shareIndex}
199
- */
200
- buildKey(nonce, senderDid, shareContext) {
201
- const base = `xbind:nonce:${senderDid}:${nonce}`;
202
- if (!shareContext)
203
- return base;
204
- const groupId = shareContext.shareGroupId ?? '';
205
- const index = shareContext.shareIndex !== undefined ? String(shareContext.shareIndex) : '';
206
- return `${base}:${groupId}:${index}`;
207
- }
208
- async check(nonce, senderDid, shareContext) {
209
- const key = this.buildKey(nonce, senderDid, shareContext);
210
- const existing = await this.kv.get(key);
211
- if (existing !== null) {
212
- // Nonce already seen
213
- return false;
214
- }
215
- // Record nonce with TTL
216
- await this.kv.put(key, Date.now().toString(), this.ttlSeconds);
217
- return true;
218
- }
219
- cleanup() {
220
- // KV stores auto-expire via TTL, no manual cleanup needed
221
- }
222
- dispose() {
223
- // No resources to clean up
224
- }
225
- }
226
- /* ── KV-Backed Trust Registry ── */
227
- /**
228
- * Trust registry implementation using KV storage.
229
- *
230
- * Stores DID registrations in edge KV for distributed lookups.
231
- * Simplified version suitable for edge runtimes - stores minimal metadata.
232
- */
233
- export class KVTrustRegistry {
234
- kv;
235
- constructor(kv) {
236
- this.kv = kv;
237
- }
238
- /**
239
- * Build key: xbind:trust:{did}
240
- */
241
- buildKey(did) {
242
- return `xbind:trust:${did}`;
243
- }
244
- async register(did, publicKey, name, scopes, x25519PublicKey, mlKemPublicKey, mlDsaPublicKey, xchange, receiveScopes, sdkVersion, minEnvelopeVersion, maxEnvelopeVersion, ttlMs) {
245
- const key = this.buildKey(did);
246
- // Convert Uint8Arrays to base64 for JSON storage
247
- const toBase64 = (arr) => btoa(String.fromCharCode(...Array.from(arr)));
248
- const entry = {
249
- did,
250
- publicKey: toBase64(publicKey),
251
- name,
252
- scopes: scopes ?? [],
253
- x25519PublicKey: x25519PublicKey ? toBase64(x25519PublicKey) : undefined,
254
- mlKemPublicKey: mlKemPublicKey ? toBase64(mlKemPublicKey) : undefined,
255
- mlDsaPublicKey: mlDsaPublicKey ? toBase64(mlDsaPublicKey) : undefined,
256
- xchange: xchange ?? false,
257
- receiveScopes: receiveScopes ?? [],
258
- sdkVersion,
259
- minEnvelopeVersion,
260
- maxEnvelopeVersion,
261
- registeredAt: Date.now(),
262
- rotation_sequence: 0,
263
- };
264
- try {
265
- const ttlSeconds = ttlMs ? Math.floor(ttlMs / 1000) : undefined;
266
- await this.kv.put(key, JSON.stringify(entry), ttlSeconds);
267
- return ok(undefined);
268
- }
269
- catch (e) {
270
- return err('NETWORK_ERROR');
271
- }
272
- }
273
- async resolve(did) {
274
- const key = this.buildKey(did);
275
- try {
276
- const value = await this.kv.get(key);
277
- if (value === null) {
278
- return err('NOT_FOUND');
279
- }
280
- const entry = JSON.parse(value);
281
- // Convert base64 back to Uint8Array
282
- const fromBase64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
283
- return ok(fromBase64(entry.publicKey));
284
- }
285
- catch (e) {
286
- return err('NETWORK_ERROR');
287
- }
288
- }
289
- async hasScope(did, scope) {
290
- const key = this.buildKey(did);
291
- try {
292
- const value = await this.kv.get(key);
293
- if (value === null)
294
- return false;
295
- const entry = JSON.parse(value);
296
- return entry.scopes?.includes(scope) ?? false;
297
- }
298
- catch {
299
- return false;
300
- }
301
- }
302
- async hasReceiveScope(did, scope) {
303
- const key = this.buildKey(did);
304
- try {
305
- const value = await this.kv.get(key);
306
- if (value === null)
307
- return false;
308
- const entry = JSON.parse(value);
309
- return entry.receiveScopes?.includes(scope) ?? false;
310
- }
311
- catch {
312
- return false;
313
- }
314
- }
315
- async revoke(did) {
316
- const key = this.buildKey(did);
317
- try {
318
- await this.kv.delete(key);
319
- return ok(undefined);
320
- }
321
- catch (e) {
322
- return err('NETWORK_ERROR');
323
- }
324
- }
325
- async list() {
326
- try {
327
- const keys = await this.kv.list('xbind:trust:', 1000);
328
- return keys.map((k) => k.replace('xbind:trust:', ''));
329
- }
330
- catch {
331
- return [];
332
- }
333
- }
334
- async getEntry(did) {
335
- const key = this.buildKey(did);
336
- try {
337
- const value = await this.kv.get(key);
338
- if (value === null) {
339
- return err('NOT_FOUND');
340
- }
341
- const stored = JSON.parse(value);
342
- // Convert base64 back to Uint8Array
343
- const fromBase64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
344
- const entry = {
345
- did: stored.did,
346
- publicKey: fromBase64(stored.publicKey),
347
- name: stored.name,
348
- scopes: new Set(stored.scopes),
349
- receiveScopes: stored.receiveScopes ? new Set(stored.receiveScopes) : undefined,
350
- revoked: false,
351
- x25519PublicKey: stored.x25519PublicKey ? fromBase64(stored.x25519PublicKey) : undefined,
352
- mlKemPublicKey: stored.mlKemPublicKey ? fromBase64(stored.mlKemPublicKey) : undefined,
353
- mlDsaPublicKey: stored.mlDsaPublicKey ? fromBase64(stored.mlDsaPublicKey) : undefined,
354
- xchange: stored.xchange,
355
- rotation_sequence: stored.rotation_sequence,
356
- sdkVersion: stored.sdkVersion,
357
- minEnvelopeVersion: stored.minEnvelopeVersion,
358
- maxEnvelopeVersion: stored.maxEnvelopeVersion,
359
- };
360
- return ok(entry);
361
- }
362
- catch (e) {
363
- return err('NETWORK_ERROR');
364
- }
365
- }
366
- /** Additional methods for edge compatibility */
367
- async getFullEntry(did) {
368
- const key = this.buildKey(did);
369
- try {
370
- const value = await this.kv.get(key);
371
- if (value === null) {
372
- return err('NOT_FOUND');
373
- }
374
- const entry = JSON.parse(value);
375
- return ok(entry);
376
- }
377
- catch (e) {
378
- return err('NETWORK_ERROR');
379
- }
380
- }
381
- dispose() {
382
- // No resources to clean up
383
- }
384
- }
385
- /* ── Edge-Compatible Transport ── */
386
- /**
387
- * Edge-compatible HTTPS transport adapter.
388
- *
389
- * Uses standard fetch API (available in all edge runtimes).
390
- * Optimized for edge constraints:
391
- * - No Node.js http/https modules
392
- * - No setTimeout (uses AbortSignal.timeout)
393
- * - Minimal allocations
394
- */
395
- export class EdgeTransportAdapter {
396
- baseUrl;
397
- timeoutMs;
398
- handlers = [];
399
- constructor(opts) {
400
- this.baseUrl = opts.baseUrl.replace(/\/$/, '');
401
- this.timeoutMs = opts.timeoutMs ?? 10_000;
402
- }
403
- async send(envelope, recipientDid) {
404
- const url = `${this.baseUrl}/deliver/${encodeURIComponent(recipientDid)}`;
405
- try {
406
- // Use AbortSignal.timeout (supported in modern edge runtimes)
407
- const controller = new AbortController();
408
- const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
409
- const response = await globalThis.fetch(url, {
410
- method: 'POST',
411
- headers: { 'Content-Type': 'application/json' },
412
- body: JSON.stringify(envelope),
413
- signal: controller.signal,
414
- });
415
- clearTimeout(timeoutId);
416
- if (!response.ok) {
417
- return err(response.status === 404 ? 'RECIPIENT_UNREACHABLE' : 'SEND_FAILED');
418
- }
419
- return ok(undefined);
420
- }
421
- catch (e) {
422
- if (e instanceof DOMException && e.name === 'AbortError') {
423
- return err('TIMEOUT');
424
- }
425
- return err('NETWORK_ERROR');
426
- }
427
- }
428
- onReceive(handler) {
429
- this.handlers.push(handler);
430
- }
431
- /**
432
- * Dispatch received envelope to all handlers.
433
- * Called by edge function handler when processing incoming requests.
434
- */
435
- dispatch(envelope) {
436
- for (const handler of this.handlers) {
437
- handler(envelope);
438
- }
439
- }
440
- dispose() {
441
- this.handlers = [];
442
- }
443
- }
444
- /**
445
- * Create edge-compatible xBind components.
446
- *
447
- * Returns nonce store, trust registry, and transport adapter
448
- * configured for the edge runtime.
449
- *
450
- * @example
451
- * ```typescript
452
- * // Cloudflare Workers
453
- * const kv = new CloudflareKVAdapter(env.XBIND_KV);
454
- * const { nonceStore, trustRegistry, transport } = createEdgeAgent({
455
- * kv,
456
- * baseUrl: 'https://private.me/relay',
457
- * });
458
- *
459
- * const agent = new Agent({
460
- * identity: 'persistent',
461
- * nonceStore,
462
- * trustRegistry,
463
- * transport,
464
- * });
465
- * ```
466
- */
467
- export function createEdgeAgent(opts) {
468
- const nonceStore = new KVNonceStore(opts.kv, opts.nonceTtlMs);
469
- const trustRegistry = new KVTrustRegistry(opts.kv);
470
- const transport = new EdgeTransportAdapter({
471
- baseUrl: opts.baseUrl,
472
- timeoutMs: opts.timeoutMs,
473
- });
474
- return {
475
- nonceStore,
476
- trustRegistry,
477
- transport,
478
- };
479
- }
480
- /* ── Size Optimization Helpers ── */
481
- /**
482
- * Check if the bundled size is within edge runtime limits.
483
- *
484
- * Cloudflare Workers: 1MB compressed limit
485
- * Vercel Edge: 1MB limit
486
- * Deno Deploy: 1MB limit
487
- */
488
- export function checkBundleSize(bundleSizeBytes) {
489
- const MAX_SIZE_BYTES = 1024 * 1024; // 1MB
490
- if (bundleSizeBytes > MAX_SIZE_BYTES) {
491
- const sizeMB = (bundleSizeBytes / 1024 / 1024).toFixed(2);
492
- const limitMB = (MAX_SIZE_BYTES / 1024 / 1024).toFixed(2);
493
- return err(`Bundle size ${sizeMB}MB exceeds edge runtime limit of ${limitMB}MB. ` +
494
- `Consider using tree-shaking or dynamic imports.`);
495
- }
496
- return ok(undefined);
497
- }
498
- /**
499
- * Get edge-optimized build recommendations.
500
- */
501
- export function getOptimizationTips() {
502
- return [
503
- '1. Use tree-shaking: Import only required functions',
504
- '2. Enable minification in bundler config',
505
- '3. Use dynamic imports for large dependencies (mlkem, mldsa)',
506
- '4. Exclude Node.js polyfills (crypto, fs, process)',
507
- '5. Use Brotli compression for Cloudflare Workers',
508
- '6. Consider splitting post-quantum crypto into separate bundle',
509
- '7. Use KV storage instead of in-memory caches',
510
- ];
511
- }
1
+ import{ok,err}from"../_deps/shared/index.js";export function detectRuntime(){const e=globalThis;return void 0!==e.caches&&"string"==typeof e.EdgeRuntime?"cloudflare":"string"==typeof e.EdgeRuntime&&"undefined"!=typeof process&&"1"===process.env?.VERCEL?"vercel":void 0!==e.Deno?"deno":"undefined"!=typeof process&&"string"==typeof process.versions?.node?"node":"unknown"}export function isEdgeRuntime(){const e=detectRuntime();return"cloudflare"===e||"vercel"===e||"deno"===e}export function validateEdgeRuntime(){if(void 0===globalThis.crypto)return err("Missing globalThis.crypto");if(void 0===globalThis.crypto.subtle)return err("Missing crypto.subtle");if("function"!=typeof globalThis.crypto.getRandomValues)return err("Missing crypto.getRandomValues");const e=["generateKey","sign","verify","encrypt","decrypt","deriveBits","importKey","exportKey"];for(const t of e)if("function"!=typeof globalThis.crypto.subtle[t])return err(`Missing crypto.subtle.${t}`);return void 0===globalThis.TextEncoder?err("Missing TextEncoder"):void 0===globalThis.TextDecoder?err("Missing TextDecoder"):"function"!=typeof globalThis.fetch?err("Missing fetch API"):ok(void 0)}export class CloudflareKVAdapter{namespace;constructor(e){this.namespace=e}async get(e){return await this.namespace.get(e)}async put(e,t,r){const s=r?{expirationTtl:r}:void 0;await this.namespace.put(e,t,s)}async delete(e){await this.namespace.delete(e)}async list(e,t){return(await this.namespace.list({prefix:e,limit:t})).keys.map(e=>e.name)}}export class VercelKVAdapter{client;constructor(e){this.client=e}async get(e){return await this.client.get(e)}async put(e,t,r){const s=r?{ex:r}:void 0;await this.client.set(e,t,s)}async delete(e){await this.client.del(e)}async list(e,t){const r=e?`${e}*`:"*",s=await this.client.keys(r);return t?s.slice(0,t):s}}export class DenoKVAdapter{kv;constructor(e){this.kv=e}async get(e){return(await this.kv.get([e])).value}async put(e,t,r){const s=r?{expireIn:1e3*r}:void 0;await this.kv.set([e],t,s)}async delete(e){await this.kv.delete([e])}async list(e,t){const r={prefix:e?[e]:[]},s=[];for await(const e of this.kv.list(r))if(s.push(e.key.join("/")),t&&s.length>=t)break;return s}}export class KVNonceStore{kv;ttlSeconds;constructor(e,t=6e5){this.kv=e,this.ttlSeconds=Math.floor(t/1e3)}buildKey(e,t,r){const s=`xbind:nonce:${t}:${e}`;if(!r)return s;return`${s}:${r.shareGroupId??""}:${void 0!==r.shareIndex?String(r.shareIndex):""}`}async check(e,t,r){const s=this.buildKey(e,t,r);return null===await this.kv.get(s)&&(await this.kv.put(s,Date.now().toString(),this.ttlSeconds),!0)}cleanup(){}dispose(){}}export class KVTrustRegistry{kv;constructor(e){this.kv=e}buildKey(e){return`xbind:trust:${e}`}async register(e,t,r,s,n,i,o,c,a,l,u,d,p){const y=this.buildKey(e),h=e=>btoa(String.fromCharCode(...Array.from(e))),m={did:e,publicKey:h(t),name:r,scopes:s??[],x25519PublicKey:n?h(n):void 0,mlKemPublicKey:i?h(i):void 0,mlDsaPublicKey:o?h(o):void 0,xchange:c??!1,receiveScopes:a??[],sdkVersion:l,minEnvelopeVersion:u,maxEnvelopeVersion:d,registeredAt:Date.now(),rotation_sequence:0};try{const e=p?Math.floor(p/1e3):void 0;return await this.kv.put(y,JSON.stringify(m),e),ok(void 0)}catch{return err("NETWORK_ERROR")}}async resolve(e){const t=this.buildKey(e);try{const e=await this.kv.get(t);if(null===e)return err("NOT_FOUND");const r=JSON.parse(e);return ok((e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)))(r.publicKey))}catch{return err("NETWORK_ERROR")}}async hasScope(e,t){const r=this.buildKey(e);try{const e=await this.kv.get(r);if(null===e)return!1;const s=JSON.parse(e);return s.scopes?.includes(t)??!1}catch{return!1}}async hasReceiveScope(e,t){const r=this.buildKey(e);try{const e=await this.kv.get(r);if(null===e)return!1;const s=JSON.parse(e);return s.receiveScopes?.includes(t)??!1}catch{return!1}}async revoke(e){const t=this.buildKey(e);try{return await this.kv.delete(t),ok(void 0)}catch{return err("NETWORK_ERROR")}}async list(){try{return(await this.kv.list("xbind:trust:",1e3)).map(e=>e.replace("xbind:trust:",""))}catch{return[]}}async getEntry(e){const t=this.buildKey(e);try{const e=await this.kv.get(t);if(null===e)return err("NOT_FOUND");const r=JSON.parse(e),s=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)),n={did:r.did,publicKey:s(r.publicKey),name:r.name,scopes:new Set(r.scopes),receiveScopes:r.receiveScopes?new Set(r.receiveScopes):void 0,revoked:!1,x25519PublicKey:r.x25519PublicKey?s(r.x25519PublicKey):void 0,mlKemPublicKey:r.mlKemPublicKey?s(r.mlKemPublicKey):void 0,mlDsaPublicKey:r.mlDsaPublicKey?s(r.mlDsaPublicKey):void 0,xchange:r.xchange,rotation_sequence:r.rotation_sequence,sdkVersion:r.sdkVersion,minEnvelopeVersion:r.minEnvelopeVersion,maxEnvelopeVersion:r.maxEnvelopeVersion};return ok(n)}catch{return err("NETWORK_ERROR")}}async getFullEntry(e){const t=this.buildKey(e);try{const e=await this.kv.get(t);if(null===e)return err("NOT_FOUND");const r=JSON.parse(e);return ok(r)}catch{return err("NETWORK_ERROR")}}dispose(){}}export class EdgeTransportAdapter{baseUrl;timeoutMs;handlers=[];constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeoutMs=e.timeoutMs??1e4}async send(e,t){const r=`${this.baseUrl}/deliver/${encodeURIComponent(t)}`;try{const t=new AbortController,s=setTimeout(()=>t.abort(),this.timeoutMs),n=await globalThis.fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:t.signal});return clearTimeout(s),n.ok?ok(void 0):err(404===n.status?"RECIPIENT_UNREACHABLE":"SEND_FAILED")}catch(e){return e instanceof DOMException&&"AbortError"===e.name?err("TIMEOUT"):err("NETWORK_ERROR")}}onReceive(e){this.handlers.push(e)}dispatch(e){for(const t of this.handlers)t(e)}dispose(){this.handlers=[]}}export function createEdgeAgent(e){return{nonceStore:new KVNonceStore(e.kv,e.nonceTtlMs),trustRegistry:new KVTrustRegistry(e.kv),transport:new EdgeTransportAdapter({baseUrl:e.baseUrl,timeoutMs:e.timeoutMs})}}export function checkBundleSize(e){const t=1048576;if(e>t){const t=(e/1024/1024).toFixed(2),r=1..toFixed(2);return err(`Bundle size ${t}MB exceeds edge runtime limit of ${r}MB. Consider using tree-shaking or dynamic imports.`)}return ok(void 0)}export function getOptimizationTips(){return["1. Use tree-shaking: Import only required functions","2. Enable minification in bundler config","3. Use dynamic imports for large dependencies (mlkem, mldsa)","4. Exclude Node.js polyfills (crypto, fs, process)","5. Use Brotli compression for Cloudflare Workers","6. Consider splitting post-quantum crypto into separate bundle","7. Use KV storage instead of in-memory caches"]}
@@ -120,7 +120,7 @@ export declare function sha256(data: Uint8Array, crypto?: ReactNativeCrypto): Pr
120
120
  * Uses global Buffer if available, otherwise provides minimal implementation
121
121
  */
122
122
  export declare class BufferPolyfill {
123
- static isBuffer(obj: any): boolean;
123
+ static isBuffer(obj: unknown): boolean;
124
124
  static from(data: string | Uint8Array | number[], encoding?: string): Uint8Array;
125
125
  static toString(buffer: Uint8Array, encoding?: string): string;
126
126
  static concat(buffers: Uint8Array[]): Uint8Array;