@private.me/xbind 3.0.2 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/README.md +2366 -204
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  6. package/dist-standalone/_deps/shared/errors.js +1 -244
  7. package/dist-standalone/_deps/shared/index.js +1 -72
  8. package/dist-standalone/_deps/shared/types.js +1 -86
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.d.ts +2 -2
  47. package/dist-standalone/agent-call.js +1 -659
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +2 -0
  50. package/dist-standalone/agent.js +1 -1800
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +3 -3
  53. package/dist-standalone/async-iterators.js +1 -382
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.js +1 -326
  58. package/dist-standalone/batch-operations.js +1 -388
  59. package/dist-standalone/cancellation.js +1 -477
  60. package/dist-standalone/checkpoint.js +1 -186
  61. package/dist-standalone/circuit-breaker.js +1 -468
  62. package/dist-standalone/cjs/agent-call.js +1 -701
  63. package/dist-standalone/cjs/agent-sdk.js +1 -332
  64. package/dist-standalone/cjs/agent.js +1 -1837
  65. package/dist-standalone/cjs/approval.js +1 -199
  66. package/dist-standalone/cjs/async-iterators.js +1 -392
  67. package/dist-standalone/cjs/auth.js +1 -225
  68. package/dist-standalone/cjs/auto-accept.js +1 -233
  69. package/dist-standalone/cjs/backup-config.js +1 -207
  70. package/dist-standalone/cjs/backup.js +1 -330
  71. package/dist-standalone/cjs/batch-operations.js +1 -397
  72. package/dist-standalone/cjs/cancellation.js +1 -490
  73. package/dist-standalone/cjs/checkpoint.js +1 -193
  74. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  75. package/dist-standalone/cjs/cli/init.js +1 -492
  76. package/dist-standalone/cjs/config-validation.js +1 -522
  77. package/dist-standalone/cjs/connect.js +1 -312
  78. package/dist-standalone/cjs/connection-pool.js +1 -506
  79. package/dist-standalone/cjs/correlation-id.js +1 -339
  80. package/dist-standalone/cjs/crypto-utils.js +1 -176
  81. package/dist-standalone/cjs/debug-mode.js +1 -534
  82. package/dist-standalone/cjs/did-document.js +1 -101
  83. package/dist-standalone/cjs/did-privateme.js +1 -130
  84. package/dist-standalone/cjs/did-web.js +1 -201
  85. package/dist-standalone/cjs/discovery.js +1 -462
  86. package/dist-standalone/cjs/dual-mode.js +1 -251
  87. package/dist-standalone/cjs/email-templates.js +1 -313
  88. package/dist-standalone/cjs/email-transport.js +1 -239
  89. package/dist-standalone/cjs/envelope.js +1 -538
  90. package/dist-standalone/cjs/errors.js +1 -913
  91. package/dist-standalone/cjs/event-emitter.js +1 -461
  92. package/dist-standalone/cjs/gateway-state.js +1 -55
  93. package/dist-standalone/cjs/gateway-transport.js +1 -120
  94. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  95. package/dist-standalone/cjs/guardrails.js +1 -223
  96. package/dist-standalone/cjs/health-check.js +1 -336
  97. package/dist-standalone/cjs/http-compat.js +1 -272
  98. package/dist-standalone/cjs/http-status-map.js +1 -571
  99. package/dist-standalone/cjs/identity.js +1 -645
  100. package/dist-standalone/cjs/index.js +1 -406
  101. package/dist-standalone/cjs/invitation.js +1 -421
  102. package/dist-standalone/cjs/invite.js +1 -328
  103. package/dist-standalone/cjs/key-agreement.js +1 -335
  104. package/dist-standalone/cjs/lazy-init.js +1 -300
  105. package/dist-standalone/cjs/logger.js +1 -291
  106. package/dist-standalone/cjs/loopback-transport.js +1 -0
  107. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  108. package/dist-standalone/cjs/nonce-store.js +1 -80
  109. package/dist-standalone/cjs/pairing-manager.js +1 -223
  110. package/dist-standalone/cjs/plugin-system.js +1 -264
  111. package/dist-standalone/cjs/plugins/logging.js +1 -168
  112. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  113. package/dist-standalone/cjs/plugins/validation.js +1 -302
  114. package/dist-standalone/cjs/policy.js +1 -320
  115. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  116. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  117. package/dist-standalone/cjs/registry-middleware.js +1 -50
  118. package/dist-standalone/cjs/retry-strategies.js +1 -544
  119. package/dist-standalone/cjs/retry-transport.js +1 -102
  120. package/dist-standalone/cjs/runtime/browser.js +1 -533
  121. package/dist-standalone/cjs/runtime/edge.js +1 -526
  122. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  123. package/dist-standalone/cjs/security-policy.js +1 -245
  124. package/dist-standalone/cjs/serialization.js +1 -1040
  125. package/dist-standalone/cjs/split-channel.js +1 -225
  126. package/dist-standalone/cjs/subscription-proof.js +1 -230
  127. package/dist-standalone/cjs/succession.js +1 -148
  128. package/dist-standalone/cjs/timeouts.js +1 -412
  129. package/dist-standalone/cjs/trace-context.js +1 -424
  130. package/dist-standalone/cjs/trace-spans.js +1 -495
  131. package/dist-standalone/cjs/transport.js +1 -63
  132. package/dist-standalone/cjs/trust-registry.js +1 -991
  133. package/dist-standalone/cjs/types/error-response.js +1 -56
  134. package/dist-standalone/cjs/vault-auth.js +1 -178
  135. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  136. package/dist-standalone/cjs/verify.js +1 -25
  137. package/dist-standalone/cjs/version-info.js +1 -543
  138. package/dist-standalone/cjs/xfetch.js +1 -340
  139. package/dist-standalone/cli/init.js +1 -455
  140. package/dist-standalone/cli/setup.js +1 -514
  141. package/dist-standalone/cli/types.js +1 -27
  142. package/dist-standalone/cli/xbind.js +1 -148
  143. package/dist-standalone/config-validation.js +1 -513
  144. package/dist-standalone/connect.js +1 -274
  145. package/dist-standalone/connection-pool.js +1 -500
  146. package/dist-standalone/correlation-id.js +1 -326
  147. package/dist-standalone/crypto-utils.d.ts +2 -7
  148. package/dist-standalone/crypto-utils.js +1 -157
  149. package/dist-standalone/debug-mode.js +1 -510
  150. package/dist-standalone/did-document.js +1 -96
  151. package/dist-standalone/did-privateme.js +1 -121
  152. package/dist-standalone/did-web.js +1 -196
  153. package/dist-standalone/discovery.js +1 -458
  154. package/dist-standalone/dual-mode.js +1 -247
  155. package/dist-standalone/email-templates.js +1 -309
  156. package/dist-standalone/email-transport.d.ts +2 -2
  157. package/dist-standalone/email-transport.js +1 -232
  158. package/dist-standalone/envelope.js +1 -525
  159. package/dist-standalone/errors.d.ts +13 -3
  160. package/dist-standalone/errors.js +1 -896
  161. package/dist-standalone/event-emitter.js +1 -456
  162. package/dist-standalone/gateway-state.d.ts +1 -1
  163. package/dist-standalone/gateway-state.js +1 -51
  164. package/dist-standalone/gateway-transport.js +1 -116
  165. package/dist-standalone/graceful-degradation.js +1 -396
  166. package/dist-standalone/guardrails.js +1 -216
  167. package/dist-standalone/health-check.d.ts +5 -1
  168. package/dist-standalone/health-check.js +1 -332
  169. package/dist-standalone/http-compat.d.ts +1 -1
  170. package/dist-standalone/http-compat.js +1 -267
  171. package/dist-standalone/http-status-map.js +1 -561
  172. package/dist-standalone/identity.js +1 -619
  173. package/dist-standalone/index.d.ts +15 -4
  174. package/dist-standalone/index.js +1 -78
  175. package/dist-standalone/invitation.js +1 -415
  176. package/dist-standalone/invite.js +1 -324
  177. package/dist-standalone/key-agreement.js +1 -325
  178. package/dist-standalone/lazy-init.d.ts +11 -6
  179. package/dist-standalone/lazy-init.js +1 -295
  180. package/dist-standalone/logger.js +1 -285
  181. package/dist-standalone/loopback-transport.d.ts +87 -0
  182. package/dist-standalone/loopback-transport.js +1 -0
  183. package/dist-standalone/mdns-discovery.js +1 -195
  184. package/dist-standalone/nonce-store.js +1 -76
  185. package/dist-standalone/pairing-manager.js +1 -219
  186. package/dist-standalone/plugin-system.js +1 -257
  187. package/dist-standalone/plugins/logging.js +1 -163
  188. package/dist-standalone/plugins/metrics.d.ts +4 -4
  189. package/dist-standalone/plugins/metrics.js +1 -176
  190. package/dist-standalone/plugins/validation.js +1 -297
  191. package/dist-standalone/policy.js +1 -315
  192. package/dist-standalone/progress-callbacks.js +1 -576
  193. package/dist-standalone/redis-nonce-store.js +1 -72
  194. package/dist-standalone/registry-middleware.js +1 -47
  195. package/dist-standalone/retry-strategies.js +1 -534
  196. package/dist-standalone/retry-transport.js +1 -98
  197. package/dist-standalone/runtime/browser.js +1 -516
  198. package/dist-standalone/runtime/edge.js +1 -511
  199. package/dist-standalone/runtime/react-native.d.ts +1 -1
  200. package/dist-standalone/runtime/react-native.js +1 -383
  201. package/dist-standalone/security-policy.js +1 -239
  202. package/dist-standalone/serialization.js +1 -1031
  203. package/dist-standalone/split-channel.d.ts +1 -1
  204. package/dist-standalone/split-channel.js +1 -219
  205. package/dist-standalone/subscription-proof.js +1 -224
  206. package/dist-standalone/succession.js +1 -142
  207. package/dist-standalone/timeouts.js +1 -398
  208. package/dist-standalone/trace-context.js +1 -414
  209. package/dist-standalone/trace-spans.js +1 -488
  210. package/dist-standalone/transport.d.ts +1 -1
  211. package/dist-standalone/transport.js +1 -59
  212. package/dist-standalone/trust-registry.d.ts +3 -3
  213. package/dist-standalone/trust-registry.js +1 -950
  214. package/dist-standalone/types/error-response.js +1 -52
  215. package/dist-standalone/vault-auth.js +1 -174
  216. package/dist-standalone/vault-store-loader.d.ts +9 -0
  217. package/dist-standalone/vault-store-loader.js +1 -187
  218. package/dist-standalone/verify.js +1 -16
  219. package/dist-standalone/version-info.js +1 -530
  220. package/dist-standalone/xfetch.js +1 -335
  221. package/package.json +1 -1
  222. package/share1.dat +0 -0
@@ -1,383 +1 @@
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 { ok, err } from"../_deps/shared/index.js";
13
- /* ── Storage Adapter ── */
14
- /**
15
- * AsyncStorage adapter for xBind persistence
16
- *
17
- * Provides cross-platform storage for:
18
- * - Agent identities (Ed25519/X25519 keys)
19
- * - Nonce store (replay protection)
20
- * - Trust registry cache
21
- * - Connection metadata
22
- */
23
- export class AsyncStorageAdapter {
24
- storage;
25
- prefix;
26
- debug;
27
- constructor(config) {
28
- this.storage = config.storage;
29
- this.prefix = config.storagePrefix || '@xbind:';
30
- this.debug = config.debug || false;
31
- }
32
- /**
33
- * Get value by key
34
- */
35
- async get(key) {
36
- try {
37
- const prefixedKey = this.prefix + key;
38
- const value = await this.storage.getItem(prefixedKey);
39
- if (this.debug) {
40
- console.log(`[AsyncStorage] GET ${prefixedKey}:`, value ? 'found' : 'not found');
41
- }
42
- return ok(value);
43
- }
44
- catch (error) {
45
- return err(new Error(`AsyncStorage get failed: ${error}`));
46
- }
47
- }
48
- /**
49
- * Set key-value pair
50
- */
51
- async set(key, value) {
52
- try {
53
- const prefixedKey = this.prefix + key;
54
- await this.storage.setItem(prefixedKey, value);
55
- if (this.debug) {
56
- console.log(`[AsyncStorage] SET ${prefixedKey}:`, value.length, 'bytes');
57
- }
58
- return ok(undefined);
59
- }
60
- catch (error) {
61
- return err(new Error(`AsyncStorage set failed: ${error}`));
62
- }
63
- }
64
- /**
65
- * Remove key
66
- */
67
- async remove(key) {
68
- try {
69
- const prefixedKey = this.prefix + key;
70
- await this.storage.removeItem(prefixedKey);
71
- if (this.debug) {
72
- console.log(`[AsyncStorage] REMOVE ${prefixedKey}`);
73
- }
74
- return ok(undefined);
75
- }
76
- catch (error) {
77
- return err(new Error(`AsyncStorage remove failed: ${error}`));
78
- }
79
- }
80
- /**
81
- * Get all keys with prefix
82
- */
83
- async keys() {
84
- try {
85
- const allKeys = await this.storage.getAllKeys();
86
- const filteredKeys = allKeys
87
- .filter(key => key.startsWith(this.prefix))
88
- .map(key => key.substring(this.prefix.length));
89
- if (this.debug) {
90
- console.log(`[AsyncStorage] KEYS:`, filteredKeys.length, 'items');
91
- }
92
- return ok(filteredKeys);
93
- }
94
- catch (error) {
95
- return err(new Error(`AsyncStorage keys failed: ${error}`));
96
- }
97
- }
98
- /**
99
- * Get multiple keys (batch operation)
100
- */
101
- async multiGet(keys) {
102
- try {
103
- const prefixedKeys = keys.map(key => this.prefix + key);
104
- const results = await this.storage.multiGet(prefixedKeys);
105
- // Remove prefix from results
106
- const unprefixedResults = results.map(([key, value]) => [
107
- key.substring(this.prefix.length),
108
- value
109
- ]);
110
- if (this.debug) {
111
- console.log(`[AsyncStorage] MULTI_GET:`, keys.length, 'keys');
112
- }
113
- return ok(unprefixedResults);
114
- }
115
- catch (error) {
116
- return err(new Error(`AsyncStorage multiGet failed: ${error}`));
117
- }
118
- }
119
- /**
120
- * Set multiple key-value pairs (batch operation)
121
- */
122
- async multiSet(pairs) {
123
- try {
124
- const prefixedPairs = pairs.map(([key, value]) => [
125
- this.prefix + key,
126
- value
127
- ]);
128
- await this.storage.multiSet(prefixedPairs);
129
- if (this.debug) {
130
- console.log(`[AsyncStorage] MULTI_SET:`, pairs.length, 'pairs');
131
- }
132
- return ok(undefined);
133
- }
134
- catch (error) {
135
- return err(new Error(`AsyncStorage multiSet failed: ${error}`));
136
- }
137
- }
138
- /**
139
- * Clear all xBind data
140
- */
141
- async clear() {
142
- try {
143
- const keysResult = await this.keys();
144
- if (!keysResult.ok) {
145
- return err(keysResult.error);
146
- }
147
- const prefixedKeys = keysResult.value.map((key) => this.prefix + key);
148
- if (prefixedKeys.length > 0) {
149
- await this.storage.multiRemove(prefixedKeys);
150
- }
151
- if (this.debug) {
152
- console.log(`[AsyncStorage] CLEAR:`, prefixedKeys.length, 'items removed');
153
- }
154
- return ok(undefined);
155
- }
156
- catch (error) {
157
- return err(new Error(`AsyncStorage clear failed: ${error}`));
158
- }
159
- }
160
- }
161
- /* ── Crypto Polyfills ── */
162
- /**
163
- * Detect available crypto implementation
164
- */
165
- export function detectCrypto() {
166
- // Check for global crypto (React Native 0.63+)
167
- if (typeof global !== 'undefined' && global.crypto) {
168
- return global.crypto;
169
- }
170
- // Check for react-native-quick-crypto
171
- try {
172
- // eslint-disable-next-line @typescript-eslint/no-var-requires
173
- const quickCrypto = require('react-native-quick-crypto');
174
- return quickCrypto;
175
- }
176
- catch {
177
- // Not available
178
- }
179
- // Check for expo-crypto
180
- try {
181
- // eslint-disable-next-line @typescript-eslint/no-var-requires
182
- const expoCrypto = require('expo-crypto');
183
- return {
184
- getRandomValues: (array) => {
185
- const bytes = expoCrypto.getRandomBytes(array.length);
186
- array.set(bytes);
187
- }
188
- };
189
- }
190
- catch {
191
- // Not available
192
- }
193
- return null;
194
- }
195
- /**
196
- * Get random bytes (cross-platform)
197
- */
198
- export function getRandomBytes(length, crypto) {
199
- const cryptoImpl = crypto || detectCrypto();
200
- if (!cryptoImpl) {
201
- throw new Error('No crypto implementation available. Install react-native-quick-crypto or expo-crypto.');
202
- }
203
- const array = new Uint8Array(length);
204
- cryptoImpl.getRandomValues(array);
205
- return array;
206
- }
207
- /**
208
- * SHA-256 hash (cross-platform)
209
- */
210
- export async function sha256(data, crypto) {
211
- const cryptoImpl = crypto || detectCrypto();
212
- if (!cryptoImpl?.subtle) {
213
- throw new Error('No SubtleCrypto implementation available. Install react-native-quick-crypto.');
214
- }
215
- // SAFETY: Create clean ArrayBuffer for Web Crypto API compatibility
216
- const cleanBuffer = new Uint8Array(data).buffer;
217
- const hash = await cryptoImpl.subtle.digest('SHA-256', cleanBuffer);
218
- return new Uint8Array(hash);
219
- }
220
- /* ── Buffer Polyfill ── */
221
- /**
222
- * Buffer polyfill for React Native
223
- *
224
- * Uses global Buffer if available, otherwise provides minimal implementation
225
- */
226
- export class BufferPolyfill {
227
- static isBuffer(obj) {
228
- return obj instanceof Uint8Array;
229
- }
230
- static from(data, encoding) {
231
- if (typeof data === 'string') {
232
- if (encoding === 'base64') {
233
- return this.fromBase64(data);
234
- }
235
- else if (encoding === 'hex') {
236
- return this.fromHex(data);
237
- }
238
- else {
239
- // Default to UTF-8
240
- const encoder = new TextEncoder();
241
- return encoder.encode(data);
242
- }
243
- }
244
- if (Array.isArray(data)) {
245
- return new Uint8Array(data);
246
- }
247
- return new Uint8Array(data);
248
- }
249
- static toString(buffer, encoding) {
250
- if (encoding === 'base64') {
251
- return this.toBase64(buffer);
252
- }
253
- else if (encoding === 'hex') {
254
- return this.toHex(buffer);
255
- }
256
- else {
257
- // Default to UTF-8
258
- const decoder = new TextDecoder();
259
- return decoder.decode(buffer);
260
- }
261
- }
262
- static concat(buffers) {
263
- const totalLength = buffers.reduce((sum, buf) => sum + buf.length, 0);
264
- const result = new Uint8Array(totalLength);
265
- let offset = 0;
266
- for (const buf of buffers) {
267
- result.set(buf, offset);
268
- offset += buf.length;
269
- }
270
- return result;
271
- }
272
- static alloc(size, fill) {
273
- const buffer = new Uint8Array(size);
274
- if (fill !== undefined) {
275
- buffer.fill(fill);
276
- }
277
- return buffer;
278
- }
279
- static fromBase64(str) {
280
- const binaryString = atob(str);
281
- const bytes = new Uint8Array(binaryString.length);
282
- for (let i = 0; i < binaryString.length; i++) {
283
- bytes[i] = binaryString.charCodeAt(i);
284
- }
285
- return bytes;
286
- }
287
- static toBase64(buffer) {
288
- let binaryString = '';
289
- for (let i = 0; i < buffer.length; i++) {
290
- const byte = buffer[i];
291
- if (byte !== undefined) {
292
- binaryString += String.fromCharCode(byte);
293
- }
294
- }
295
- return btoa(binaryString);
296
- }
297
- static fromHex(str) {
298
- const bytes = new Uint8Array(str.length / 2);
299
- for (let i = 0; i < bytes.length; i++) {
300
- bytes[i] = parseInt(str.substr(i * 2, 2), 16);
301
- }
302
- return bytes;
303
- }
304
- static toHex(buffer) {
305
- return Array.from(buffer)
306
- .map(b => b.toString(16).padStart(2, '0'))
307
- .join('');
308
- }
309
- }
310
- /* ── Platform Detection ── */
311
- /**
312
- * Detect React Native runtime
313
- */
314
- export function isReactNative() {
315
- return (typeof navigator !== 'undefined' &&
316
- navigator.product === 'ReactNative');
317
- }
318
- /**
319
- * Detect platform (iOS/Android)
320
- */
321
- export function detectPlatform() {
322
- if (typeof navigator === 'undefined') {
323
- return 'unknown';
324
- }
325
- const userAgent = navigator.userAgent || '';
326
- if (/iPhone|iPad|iPod/.test(userAgent)) {
327
- return 'ios';
328
- }
329
- if (/Android/.test(userAgent)) {
330
- return 'android';
331
- }
332
- return 'unknown';
333
- }
334
- /* ── Module Initialization ── */
335
- /**
336
- * Initialize React Native runtime environment
337
- *
338
- * Sets up polyfills and validates required dependencies
339
- */
340
- export function initializeReactNative(config) {
341
- try {
342
- // Validate storage
343
- if (!config.storage) {
344
- return err(new Error('AsyncStorage is required for React Native runtime'));
345
- }
346
- // Validate crypto
347
- const crypto = config.crypto || detectCrypto();
348
- if (!crypto) {
349
- return err(new Error('No crypto implementation found. Install react-native-quick-crypto or expo-crypto.'));
350
- }
351
- // Ensure global.crypto is available
352
- if (!global.crypto) {
353
- global.crypto = crypto;
354
- }
355
- // Ensure global.Buffer is available
356
- if (!global.Buffer) {
357
- global.Buffer = BufferPolyfill;
358
- }
359
- if (config.debug) {
360
- console.log('[xBind] React Native runtime initialized:', {
361
- platform: detectPlatform(),
362
- crypto: !!crypto.subtle ? 'full' : 'basic',
363
- storage: 'AsyncStorage',
364
- prefix: config.storagePrefix || '@xbind:'
365
- });
366
- }
367
- return ok(undefined);
368
- }
369
- catch (error) {
370
- return err(new Error(`React Native initialization failed: ${error}`));
371
- }
372
- }
373
- /* ── Exports ── */
374
- export default {
375
- AsyncStorageAdapter,
376
- detectCrypto,
377
- getRandomBytes,
378
- sha256,
379
- BufferPolyfill,
380
- isReactNative,
381
- detectPlatform,
382
- initializeReactNative
383
- };
1
+ import{ok,err}from"../_deps/shared/index.js";export class AsyncStorageAdapter{storage;prefix;debug;constructor(t){this.storage=t.storage,this.prefix=t.storagePrefix||"@xbind:",this.debug=t.debug||!1}async get(t){try{const e=this.prefix+t,r=await this.storage.getItem(e);return this.debug&&console.log(`[AsyncStorage] GET ${e}:`,r?"found":"not found"),ok(r)}catch(t){return err(new Error(`AsyncStorage get failed: ${t}`))}}async set(t,e){try{const r=this.prefix+t;return await this.storage.setItem(r,e),this.debug&&console.log(`[AsyncStorage] SET ${r}:`,e.length,"bytes"),ok(void 0)}catch(t){return err(new Error(`AsyncStorage set failed: ${t}`))}}async remove(t){try{const e=this.prefix+t;return await this.storage.removeItem(e),this.debug&&console.log(`[AsyncStorage] REMOVE ${e}`),ok(void 0)}catch(t){return err(new Error(`AsyncStorage remove failed: ${t}`))}}async keys(){try{const t=(await this.storage.getAllKeys()).filter(t=>t.startsWith(this.prefix)).map(t=>t.substring(this.prefix.length));return this.debug&&console.log("[AsyncStorage] KEYS:",t.length,"items"),ok(t)}catch(t){return err(new Error(`AsyncStorage keys failed: ${t}`))}}async multiGet(t){try{const e=t.map(t=>this.prefix+t),r=(await this.storage.multiGet(e)).map(([t,e])=>[t.substring(this.prefix.length),e]);return this.debug&&console.log("[AsyncStorage] MULTI_GET:",t.length,"keys"),ok(r)}catch(t){return err(new Error(`AsyncStorage multiGet failed: ${t}`))}}async multiSet(t){try{const e=t.map(([t,e])=>[this.prefix+t,e]);return await this.storage.multiSet(e),this.debug&&console.log("[AsyncStorage] MULTI_SET:",t.length,"pairs"),ok(void 0)}catch(t){return err(new Error(`AsyncStorage multiSet failed: ${t}`))}}async clear(){try{const t=await this.keys();if(!t.ok)return err(t.error);const e=t.value.map(t=>this.prefix+t);return e.length>0&&await this.storage.multiRemove(e),this.debug&&console.log("[AsyncStorage] CLEAR:",e.length,"items removed"),ok(void 0)}catch(t){return err(new Error(`AsyncStorage clear failed: ${t}`))}}}export function detectCrypto(){if("undefined"!=typeof global&&global.crypto)return global.crypto;try{return require("react-native-quick-crypto")}catch{}try{const t=require("expo-crypto");return{getRandomValues:e=>{const r=t.getRandomBytes(e.length);e.set(r)}}}catch{}return null}export function getRandomBytes(t,e){const r=e||detectCrypto();if(!r)throw new Error("No crypto implementation available. Install react-native-quick-crypto or expo-crypto.");const o=new Uint8Array(t);return r.getRandomValues(o),o}export async function sha256(t,e){const r=e||detectCrypto();if(!r?.subtle)throw new Error("No SubtleCrypto implementation available. Install react-native-quick-crypto.");const o=new Uint8Array(t).buffer,n=await r.subtle.digest("SHA-256",o);return new Uint8Array(n)}export class BufferPolyfill{static isBuffer(t){return t instanceof Uint8Array}static from(t,e){if("string"==typeof t){if("base64"===e)return this.fromBase64(t);if("hex"===e)return this.fromHex(t);return(new TextEncoder).encode(t)}return Array.isArray(t),new Uint8Array(t)}static toString(t,e){if("base64"===e)return this.toBase64(t);if("hex"===e)return this.toHex(t);return(new TextDecoder).decode(t)}static concat(t){const e=t.reduce((t,e)=>t+e.length,0),r=new Uint8Array(e);let o=0;for(const e of t)r.set(e,o),o+=e.length;return r}static alloc(t,e){const r=new Uint8Array(t);return void 0!==e&&r.fill(e),r}static fromBase64(t){const e=atob(t),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r}static toBase64(t){let e="";for(let r=0;r<t.length;r++){const o=t[r];void 0!==o&&(e+=String.fromCharCode(o))}return btoa(e)}static fromHex(t){const e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(t.substr(2*r,2),16);return e}static toHex(t){return Array.from(t).map(t=>t.toString(16).padStart(2,"0")).join("")}}export function isReactNative(){return"undefined"!=typeof navigator&&"ReactNative"===navigator.product}export function detectPlatform(){if("undefined"==typeof navigator)return"unknown";const t=navigator.userAgent||"";return/iPhone|iPad|iPod/.test(t)?"ios":/Android/.test(t)?"android":"unknown"}export function initializeReactNative(t){try{if(!t.storage)return err(new Error("AsyncStorage is required for React Native runtime"));const e=t.crypto||detectCrypto();return e?(global.crypto||(global.crypto=e),global.Buffer||(global.Buffer=BufferPolyfill),t.debug&&console.log("[xBind] React Native runtime initialized:",{platform:detectPlatform(),crypto:e.subtle?"full":"basic",storage:"AsyncStorage",prefix:t.storagePrefix||"@xbind:"}),ok(void 0)):err(new Error("No crypto implementation found. Install react-native-quick-crypto or expo-crypto."))}catch(t){return err(new Error(`React Native initialization failed: ${t}`))}}export default{AsyncStorageAdapter:AsyncStorageAdapter,detectCrypto:detectCrypto,getRandomBytes:getRandomBytes,sha256:sha256,BufferPolyfill:BufferPolyfill,isReactNative:isReactNative,detectPlatform:detectPlatform,initializeReactNative:initializeReactNative};
@@ -1,239 +1 @@
1
- /**
2
- * Security policy interface for automatic risk-based Xorida activation.
3
- *
4
- * Determines when to apply information-theoretic security (XorIDA split-channel)
5
- * vs standard encrypted transport based on action semantics and parameters.
6
- *
7
- * Design principle: Security should be invisible to users. The policy classifies
8
- * risk automatically so developers don't need to understand threshold cryptography.
9
- */
10
- /**
11
- * Default security policy for basic XBind.
12
- *
13
- * Rules:
14
- * - Explicit risk tags: low → 2-of-2, medium → 2-of-3, high/critical → 3-of-5
15
- * - Fiat transfers: USD/EUR/GBP >$100k → 2-of-3, >$1M → 3-of-5
16
- * - Crypto transfers: Require explicit risk tag (no numeric auto-detection)
17
- * - Sensitive scopes: custody/admin/settlement → 2-of-3
18
- * - Cross-entity communication: 2-of-3
19
- * - Explicit 'high' override: 2-of-3, 'critical' override: 3-of-5
20
- * - Everything else: Standard encrypted transport (V3 hybrid PQ)
21
- *
22
- * Enterprise and Government variants extend this with custom rules.
23
- */
24
- export class DefaultSecurityPolicy {
25
- options;
26
- /**
27
- * Create a default security policy.
28
- *
29
- * @param options - Optional configuration
30
- * @param options.highValueThreshold - Amount threshold for high security (default: 100000)
31
- * @param options.criticalValueThreshold - Amount threshold for critical security (default: 1000000)
32
- * @param options.enableXchange - Allow Xchange mode for performance (default: false)
33
- */
34
- constructor(options = {}) {
35
- this.options = options;
36
- }
37
- classify(context) {
38
- const { action, params, securityOverride } = context;
39
- const highThreshold = this.options.highValueThreshold ?? 100_000;
40
- const criticalThreshold = this.options.criticalValueThreshold ?? 1_000_000;
41
- // Explicit override: critical
42
- if (securityOverride === 'critical') {
43
- return {
44
- mode: { type: 'split', shares: 5, threshold: 3 },
45
- reason: 'User requested critical security level (5 shares, 3-of-5 threshold)',
46
- wasOverridden: true,
47
- };
48
- }
49
- // Explicit override: high
50
- if (securityOverride === 'high') {
51
- return {
52
- mode: { type: 'split', shares: 3, threshold: 2 },
53
- reason: 'User requested high security level (3 shares, 2-of-3 threshold)',
54
- wasOverridden: true,
55
- };
56
- }
57
- // Explicit override: standard
58
- if (securityOverride === 'standard') {
59
- return {
60
- mode: { type: 'standard' },
61
- reason: 'User requested standard security level (encrypted transport)',
62
- wasOverridden: true,
63
- };
64
- }
65
- // Risk tag detection (preferred for crypto: BTC, ETH, etc.)
66
- const riskTag = typeof params.risk === 'string' ? params.risk.toLowerCase() : undefined;
67
- if (riskTag) {
68
- if (riskTag === 'critical' || riskTag === 'high') {
69
- return {
70
- mode: { type: 'split', shares: 5, threshold: 3 },
71
- reason: `Explicit risk tag "${riskTag}" requires 3-of-5 threshold`,
72
- wasOverridden: false,
73
- };
74
- }
75
- else if (riskTag === 'medium') {
76
- return {
77
- mode: { type: 'split', shares: 3, threshold: 2 },
78
- reason: `Explicit risk tag "medium" requires 2-of-3 threshold`,
79
- wasOverridden: false,
80
- };
81
- }
82
- else if (riskTag === 'low') {
83
- return {
84
- mode: { type: 'split', shares: 2, threshold: 2 },
85
- reason: `Explicit risk tag "low" requires 2-of-2 threshold`,
86
- wasOverridden: false,
87
- };
88
- }
89
- }
90
- // Numeric thresholds ONLY for fiat currencies (USD, EUR, GBP)
91
- // Crypto (BTC, ETH) should use risk tags instead
92
- if ((action === 'transfer' || action === 'execute') && typeof params.amount === 'number') {
93
- const currency = typeof params.currency === 'string' ? params.currency.toUpperCase() : 'USD';
94
- const isFiat = ['USD', 'EUR', 'GBP'].includes(currency);
95
- if (isFiat) {
96
- if (params.amount >= criticalThreshold) {
97
- return {
98
- mode: { type: 'split', shares: 5, threshold: 3 },
99
- reason: `Critical-value transfer (${currency} ${params.amount.toLocaleString()}) requires 3-of-5 threshold`,
100
- wasOverridden: false,
101
- };
102
- }
103
- else if (params.amount >= highThreshold) {
104
- return {
105
- mode: { type: 'split', shares: 3, threshold: 2 },
106
- reason: `High-value transfer (${currency} ${params.amount.toLocaleString()}) requires 2-of-3 threshold`,
107
- wasOverridden: false,
108
- };
109
- }
110
- }
111
- }
112
- // Auto-detection: Cross-entity communication
113
- if (params.crossEntity === true) {
114
- return {
115
- mode: { type: 'split', shares: 3, threshold: 2 },
116
- reason: 'Cross-organization communication requires multi-party approval (2 of 3)',
117
- wasOverridden: false,
118
- };
119
- }
120
- // Auto-detection: Sensitive scopes
121
- if (context.scope.includes('admin') ||
122
- context.scope.includes('custody') ||
123
- context.scope.includes('settlement')) {
124
- return {
125
- mode: { type: 'split', shares: 3, threshold: 2 },
126
- reason: `Sensitive scope "${context.scope}" requires multi-party approval (2 of 3)`,
127
- wasOverridden: false,
128
- };
129
- }
130
- // Xchange mode: opt-in performance mode (if enabled)
131
- if (this.options.enableXchange && params.xchange === true) {
132
- return {
133
- mode: { type: 'xchange' },
134
- reason: 'Xchange mode enabled for performance (~180x faster)',
135
- wasOverridden: false,
136
- };
137
- }
138
- // Default: Standard encrypted transport
139
- return {
140
- mode: { type: 'standard' },
141
- reason: 'Standard encrypted transport (hybrid post-quantum)',
142
- wasOverridden: false,
143
- };
144
- }
145
- }
146
- /**
147
- * Get a human-readable security mode description.
148
- *
149
- * Used for logging and user feedback.
150
- *
151
- * @param mode - Security mode
152
- * @returns User-friendly description
153
- *
154
- * @deprecated Use describeSecurityModeStructured() for new code. This function remains for backward compatibility.
155
- */
156
- export function describeSecurityMode(mode) {
157
- switch (mode.type) {
158
- case 'standard':
159
- return 'Standard (encrypted)';
160
- case 'split':
161
- return `Multi-party approval (${mode.threshold} of ${mode.shares})`;
162
- case 'xchange':
163
- return 'Xchange (fast mode)';
164
- }
165
- }
166
- /**
167
- * Get a structured security mode description with multiple formats.
168
- *
169
- * Returns an object with the security classification and formatted descriptions
170
- * optimized for different use cases (display, logging, APIs, docs).
171
- *
172
- * @param mode - Security mode
173
- * @returns Security mode description with formats
174
- *
175
- * @example
176
- * ```typescript
177
- * const mode: SecurityMode = { type: 'split', shares: 3, threshold: 2 };
178
- * const description = describeSecurityModeStructured(mode);
179
- *
180
- * console.log(description.formats.singleline);
181
- * // "high | split | 2-of-3"
182
- *
183
- * console.log(description.formats.multiline);
184
- * // "Security Level: High
185
- * // Mode: Split-channel (XorIDA)
186
- * // Shares: 3 total, 2 required"
187
- *
188
- * console.log(description.shares);
189
- * // { total: 3, threshold: 2 }
190
- * ```
191
- */
192
- export function describeSecurityModeStructured(mode) {
193
- let level;
194
- let multiline;
195
- let singleline;
196
- let markdown;
197
- let shares;
198
- switch (mode.type) {
199
- case 'standard':
200
- level = 'standard';
201
- multiline = 'Security Level: Standard\nMode: Encrypted transport (hybrid post-quantum)';
202
- singleline = 'standard | encrypted';
203
- markdown = '**Security Level:** Standard\n\n**Mode:** Encrypted transport (hybrid post-quantum)';
204
- break;
205
- case 'split':
206
- // Classify split mode as high or critical based on threshold
207
- level = mode.shares >= 5 ? 'critical' : 'high';
208
- shares = { total: mode.shares, threshold: mode.threshold };
209
- multiline = `Security Level: ${level === 'critical' ? 'Critical' : 'High'}\nMode: Split-channel (XorIDA)\nShares: ${mode.shares} total, ${mode.threshold} required`;
210
- singleline = `${level} | split | ${mode.threshold}-of-${mode.shares}`;
211
- markdown = `**Security Level:** ${level === 'critical' ? 'Critical' : 'High'}\n\n**Mode:** Split-channel (XorIDA)\n\n**Shares:** ${mode.shares} total, ${mode.threshold} required`;
212
- break;
213
- case 'xchange':
214
- level = 'performance';
215
- multiline = 'Security Level: Performance\nMode: Xchange (single IT layer, ~180x faster)';
216
- singleline = 'performance | xchange';
217
- markdown = '**Security Level:** Performance\n\n**Mode:** Xchange (single IT layer, ~180x faster)';
218
- break;
219
- }
220
- const jsonObj = {
221
- type: mode.type,
222
- level,
223
- };
224
- if (shares) {
225
- jsonObj.shares = shares;
226
- }
227
- const json = JSON.stringify(jsonObj);
228
- return {
229
- type: mode.type,
230
- level,
231
- shares,
232
- formats: {
233
- multiline,
234
- singleline,
235
- json,
236
- markdown,
237
- },
238
- };
239
- }
1
+ export class DefaultSecurityPolicy{options;constructor(e={}){this.options=e}classify(e){const{action:r,params:t,securityOverride:s}=e,a=this.options.highValueThreshold??1e5,i=this.options.criticalValueThreshold??1e6;if("critical"===s)return{mode:{type:"split",shares:5,threshold:3},reason:"User requested critical security level (5 shares, 3-of-5 threshold)",wasOverridden:!0};if("high"===s)return{mode:{type:"split",shares:3,threshold:2},reason:"User requested high security level (3 shares, 2-of-3 threshold)",wasOverridden:!0};if("standard"===s)return{mode:{type:"standard"},reason:"User requested standard security level (encrypted transport)",wasOverridden:!0};const n="string"==typeof t.risk?t.risk.toLowerCase():void 0;if(n){if("critical"===n||"high"===n)return{mode:{type:"split",shares:5,threshold:3},reason:`Explicit risk tag "${n}" requires 3-of-5 threshold`,wasOverridden:!1};if("medium"===n)return{mode:{type:"split",shares:3,threshold:2},reason:'Explicit risk tag "medium" requires 2-of-3 threshold',wasOverridden:!1};if("low"===n)return{mode:{type:"split",shares:2,threshold:2},reason:'Explicit risk tag "low" requires 2-of-2 threshold',wasOverridden:!1}}if(("transfer"===r||"execute"===r)&&"number"==typeof t.amount){const e="string"==typeof t.currency?t.currency.toUpperCase():"USD";if(["USD","EUR","GBP"].includes(e)){if(t.amount>=i)return{mode:{type:"split",shares:5,threshold:3},reason:`Critical-value transfer (${e} ${t.amount.toLocaleString()}) requires 3-of-5 threshold`,wasOverridden:!1};if(t.amount>=a)return{mode:{type:"split",shares:3,threshold:2},reason:`High-value transfer (${e} ${t.amount.toLocaleString()}) requires 2-of-3 threshold`,wasOverridden:!1}}}if(!0===t.crossEntity)return{mode:{type:"split",shares:3,threshold:2},reason:"Cross-organization communication requires multi-party approval (2 of 3)",wasOverridden:!1};const o=e.scope??"default";return o.includes("admin")||o.includes("custody")||o.includes("settlement")?{mode:{type:"split",shares:3,threshold:2},reason:`Sensitive scope "${o}" requires multi-party approval (2 of 3)`,wasOverridden:!1}:this.options.enableXchange&&!0===t.xchange?{mode:{type:"xchange"},reason:"Xchange mode enabled for performance (~180x faster)",wasOverridden:!1}:{mode:{type:"standard"},reason:"Standard encrypted transport (hybrid post-quantum)",wasOverridden:!1}}}export function describeSecurityMode(e){switch(e.type){case"standard":return"Standard (encrypted)";case"split":return`Multi-party approval (${e.threshold} of ${e.shares})`;case"xchange":return"Xchange (fast mode)"}}export function describeSecurityModeStructured(e){let r,t,s,a,i;switch(e.type){case"standard":r="standard",t="Security Level: Standard\nMode: Encrypted transport (hybrid post-quantum)",s="standard | encrypted",a="**Security Level:** Standard\n\n**Mode:** Encrypted transport (hybrid post-quantum)";break;case"split":r=e.shares>=5?"critical":"high",i={total:e.shares,threshold:e.threshold},t=`Security Level: ${"critical"===r?"Critical":"High"}\nMode: Split-channel (XorIDA)\nShares: ${e.shares} total, ${e.threshold} required`,s=`${r} | split | ${e.threshold}-of-${e.shares}`,a=`**Security Level:** ${"critical"===r?"Critical":"High"}\n\n**Mode:** Split-channel (XorIDA)\n\n**Shares:** ${e.shares} total, ${e.threshold} required`;break;case"xchange":r="performance",t="Security Level: Performance\nMode: Xchange (single IT layer, ~180x faster)",s="performance | xchange",a="**Security Level:** Performance\n\n**Mode:** Xchange (single IT layer, ~180x faster)"}const n={type:e.type,level:r};i&&(n.shares=i);const o=JSON.stringify(n);return{type:e.type,level:r,shares:i,formats:{multiline:t,singleline:s,json:o,markdown:a}}}