@private.me/xbind 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/README.md +55 -7
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.d.ts +84 -0
  174. package/dist-standalone/plugins/logging.js +163 -0
  175. package/dist-standalone/plugins/metrics.d.ts +111 -0
  176. package/dist-standalone/plugins/metrics.js +176 -0
  177. package/dist-standalone/plugins/validation.d.ts +104 -0
  178. package/dist-standalone/plugins/validation.js +297 -0
  179. package/dist-standalone/policy.js +315 -1
  180. package/dist-standalone/progress-callbacks.js +576 -1
  181. package/dist-standalone/redis-nonce-store.js +72 -1
  182. package/dist-standalone/registry-middleware.js +47 -1
  183. package/dist-standalone/retry-strategies.js +534 -1
  184. package/dist-standalone/retry-transport.js +98 -1
  185. package/dist-standalone/runtime/browser.d.ts +311 -0
  186. package/dist-standalone/runtime/browser.js +516 -0
  187. package/dist-standalone/runtime/edge.d.ts +282 -0
  188. package/dist-standalone/runtime/edge.js +511 -0
  189. package/dist-standalone/runtime/react-native.d.ts +157 -0
  190. package/dist-standalone/runtime/react-native.js +383 -0
  191. package/dist-standalone/security-policy.js +239 -1
  192. package/dist-standalone/serialization.js +1031 -1
  193. package/dist-standalone/split-channel.js +219 -1
  194. package/dist-standalone/subscription-proof.js +224 -1
  195. package/dist-standalone/succession.js +142 -1
  196. package/dist-standalone/timeouts.js +398 -1
  197. package/dist-standalone/trace-context.js +414 -1
  198. package/dist-standalone/trace-spans.js +488 -1
  199. package/dist-standalone/transport.js +59 -1
  200. package/dist-standalone/trust-registry.js +950 -1
  201. package/dist-standalone/types/error-response.d.ts +209 -0
  202. package/dist-standalone/types/error-response.js +52 -0
  203. package/dist-standalone/vault-auth.js +174 -1
  204. package/dist-standalone/vault-store-loader.js +187 -1
  205. package/dist-standalone/verify.js +16 -1
  206. package/dist-standalone/version-info.js +530 -1
  207. package/dist-standalone/xfetch.js +335 -1
  208. package/package.json +4 -10
  209. package/share1.dat +0 -0
  210. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  211. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  212. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  213. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  214. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  215. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  216. package/dist-standalone/cjs/package.json +0 -3
  217. package/dist-standalone/package.json +0 -10
@@ -0,0 +1,511 @@
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
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * React Native Runtime Support for xBind
3
+ *
4
+ * Provides compatibility layer for React Native environments:
5
+ * - Polyfills for missing Node.js APIs
6
+ * - AsyncStorage adapter for persistence
7
+ * - Native crypto module integration
8
+ * - Cross-platform crypto primitives
9
+ *
10
+ * @module runtime/react-native
11
+ */
12
+ import type { Result } from '@private.me/shared';
13
+ /**
14
+ * React Native AsyncStorage interface
15
+ */
16
+ export interface AsyncStorage {
17
+ getItem(key: string): Promise<string | null>;
18
+ setItem(key: string, value: string): Promise<void>;
19
+ removeItem(key: string): Promise<void>;
20
+ getAllKeys(): Promise<string[]>;
21
+ multiGet(keys: string[]): Promise<Array<[string, string | null]>>;
22
+ multiSet(keyValuePairs: Array<[string, string]>): Promise<void>;
23
+ multiRemove(keys: string[]): Promise<void>;
24
+ }
25
+ /**
26
+ * React Native crypto capabilities
27
+ */
28
+ export interface ReactNativeCrypto {
29
+ getRandomValues(array: Uint8Array): void;
30
+ subtle?: {
31
+ digest(algorithm: string, data: BufferSource): Promise<ArrayBuffer>;
32
+ encrypt(algorithm: AlgorithmIdentifier, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
33
+ decrypt(algorithm: AlgorithmIdentifier, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
34
+ sign(algorithm: AlgorithmIdentifier, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
35
+ verify(algorithm: AlgorithmIdentifier, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>;
36
+ generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey | CryptoKeyPair>;
37
+ importKey(format: KeyFormat, keyData: BufferSource | JsonWebKey, algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
38
+ exportKey(format: KeyFormat, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;
39
+ };
40
+ }
41
+ /**
42
+ * React Native runtime configuration
43
+ */
44
+ export interface ReactNativeConfig {
45
+ /**
46
+ * AsyncStorage instance (required for persistence)
47
+ */
48
+ storage: AsyncStorage;
49
+ /**
50
+ * Crypto implementation (defaults to global.crypto or react-native-quick-crypto)
51
+ */
52
+ crypto?: ReactNativeCrypto;
53
+ /**
54
+ * Storage key prefix (prevents collisions)
55
+ */
56
+ storagePrefix?: string;
57
+ /**
58
+ * Enable debug logging
59
+ */
60
+ debug?: boolean;
61
+ }
62
+ /**
63
+ * AsyncStorage adapter for xBind persistence
64
+ *
65
+ * Provides cross-platform storage for:
66
+ * - Agent identities (Ed25519/X25519 keys)
67
+ * - Nonce store (replay protection)
68
+ * - Trust registry cache
69
+ * - Connection metadata
70
+ */
71
+ export declare class AsyncStorageAdapter {
72
+ private readonly storage;
73
+ private readonly prefix;
74
+ private readonly debug;
75
+ constructor(config: ReactNativeConfig);
76
+ /**
77
+ * Get value by key
78
+ */
79
+ get(key: string): Promise<Result<string | null, Error>>;
80
+ /**
81
+ * Set key-value pair
82
+ */
83
+ set(key: string, value: string): Promise<Result<void, Error>>;
84
+ /**
85
+ * Remove key
86
+ */
87
+ remove(key: string): Promise<Result<void, Error>>;
88
+ /**
89
+ * Get all keys with prefix
90
+ */
91
+ keys(): Promise<Result<string[], Error>>;
92
+ /**
93
+ * Get multiple keys (batch operation)
94
+ */
95
+ multiGet(keys: string[]): Promise<Result<Array<[string, string | null]>, Error>>;
96
+ /**
97
+ * Set multiple key-value pairs (batch operation)
98
+ */
99
+ multiSet(pairs: Array<[string, string]>): Promise<Result<void, Error>>;
100
+ /**
101
+ * Clear all xBind data
102
+ */
103
+ clear(): Promise<Result<void, Error>>;
104
+ }
105
+ /**
106
+ * Detect available crypto implementation
107
+ */
108
+ export declare function detectCrypto(): ReactNativeCrypto | null;
109
+ /**
110
+ * Get random bytes (cross-platform)
111
+ */
112
+ export declare function getRandomBytes(length: number, crypto?: ReactNativeCrypto): Uint8Array;
113
+ /**
114
+ * SHA-256 hash (cross-platform)
115
+ */
116
+ export declare function sha256(data: Uint8Array, crypto?: ReactNativeCrypto): Promise<Uint8Array>;
117
+ /**
118
+ * Buffer polyfill for React Native
119
+ *
120
+ * Uses global Buffer if available, otherwise provides minimal implementation
121
+ */
122
+ export declare class BufferPolyfill {
123
+ static isBuffer(obj: any): boolean;
124
+ static from(data: string | Uint8Array | number[], encoding?: string): Uint8Array;
125
+ static toString(buffer: Uint8Array, encoding?: string): string;
126
+ static concat(buffers: Uint8Array[]): Uint8Array;
127
+ static alloc(size: number, fill?: number): Uint8Array;
128
+ private static fromBase64;
129
+ private static toBase64;
130
+ private static fromHex;
131
+ private static toHex;
132
+ }
133
+ /**
134
+ * Detect React Native runtime
135
+ */
136
+ export declare function isReactNative(): boolean;
137
+ /**
138
+ * Detect platform (iOS/Android)
139
+ */
140
+ export declare function detectPlatform(): 'ios' | 'android' | 'unknown';
141
+ /**
142
+ * Initialize React Native runtime environment
143
+ *
144
+ * Sets up polyfills and validates required dependencies
145
+ */
146
+ export declare function initializeReactNative(config: ReactNativeConfig): Result<void, Error>;
147
+ declare const _default: {
148
+ AsyncStorageAdapter: typeof AsyncStorageAdapter;
149
+ detectCrypto: typeof detectCrypto;
150
+ getRandomBytes: typeof getRandomBytes;
151
+ sha256: typeof sha256;
152
+ BufferPolyfill: typeof BufferPolyfill;
153
+ isReactNative: typeof isReactNative;
154
+ detectPlatform: typeof detectPlatform;
155
+ initializeReactNative: typeof initializeReactNative;
156
+ };
157
+ export default _default;