@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,383 @@
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 +1,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 o="string"==typeof t.risk?t.risk.toLowerCase():void 0;if(o){if("critical"===o||"high"===o)return{mode:{type:"split",shares:5,threshold:3},reason:`Explicit risk tag "${o}" requires 3-of-5 threshold`,wasOverridden:!1};if("medium"===o)return{mode:{type:"split",shares:3,threshold:2},reason:'Explicit risk tag "medium" requires 2-of-3 threshold',wasOverridden:!1};if("low"===o)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}}}return!0===t.crossEntity?{mode:{type:"split",shares:3,threshold:2},reason:"Cross-organization communication requires multi-party approval (2 of 3)",wasOverridden:!1}:e.scope.includes("admin")||e.scope.includes("custody")||e.scope.includes("settlement")?{mode:{type:"split",shares:3,threshold:2},reason:`Sensitive scope "${e.scope}" 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 o={type:e.type,level:r};i&&(o.shares=i);const n=JSON.stringify(o);return{type:e.type,level:r,shares:i,formats:{multiline:t,singleline:s,json:n,markdown:a}}}
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
+ }