@bananalink-sdk/protocol 1.2.7

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 (158) hide show
  1. package/README.md +604 -0
  2. package/dist/chunk-32OWUOZ3.js +308 -0
  3. package/dist/chunk-32OWUOZ3.js.map +1 -0
  4. package/dist/chunk-65HNHRJK.cjs +123 -0
  5. package/dist/chunk-65HNHRJK.cjs.map +1 -0
  6. package/dist/chunk-7KYDLL3B.js +480 -0
  7. package/dist/chunk-7KYDLL3B.js.map +1 -0
  8. package/dist/chunk-A6FLEJ7R.cjs +62 -0
  9. package/dist/chunk-A6FLEJ7R.cjs.map +1 -0
  10. package/dist/chunk-CUJK7ZTS.js +217 -0
  11. package/dist/chunk-CUJK7ZTS.js.map +1 -0
  12. package/dist/chunk-GI3BUPIH.cjs +236 -0
  13. package/dist/chunk-GI3BUPIH.cjs.map +1 -0
  14. package/dist/chunk-JXHV66Q4.js +106 -0
  15. package/dist/chunk-JXHV66Q4.js.map +1 -0
  16. package/dist/chunk-KNGZKGRS.cjs +552 -0
  17. package/dist/chunk-KNGZKGRS.cjs.map +1 -0
  18. package/dist/chunk-LELPCIE7.js +840 -0
  19. package/dist/chunk-LELPCIE7.js.map +1 -0
  20. package/dist/chunk-MCZG7QEM.cjs +310 -0
  21. package/dist/chunk-MCZG7QEM.cjs.map +1 -0
  22. package/dist/chunk-TCVKC227.js +56 -0
  23. package/dist/chunk-TCVKC227.js.map +1 -0
  24. package/dist/chunk-VXLUSU5B.cjs +856 -0
  25. package/dist/chunk-VXLUSU5B.cjs.map +1 -0
  26. package/dist/chunk-WCQVDF3K.js +12 -0
  27. package/dist/chunk-WCQVDF3K.js.map +1 -0
  28. package/dist/chunk-WGEGR3DF.cjs +15 -0
  29. package/dist/chunk-WGEGR3DF.cjs.map +1 -0
  30. package/dist/client-session-claim-3QF3noOr.d.ts +197 -0
  31. package/dist/client-session-claim-C4lUik3b.d.cts +197 -0
  32. package/dist/core-DMhuNfoz.d.cts +62 -0
  33. package/dist/core-DMhuNfoz.d.ts +62 -0
  34. package/dist/crypto/providers/noble-provider.cjs +14 -0
  35. package/dist/crypto/providers/noble-provider.cjs.map +1 -0
  36. package/dist/crypto/providers/noble-provider.d.cts +30 -0
  37. package/dist/crypto/providers/noble-provider.d.ts +30 -0
  38. package/dist/crypto/providers/noble-provider.js +5 -0
  39. package/dist/crypto/providers/noble-provider.js.map +1 -0
  40. package/dist/crypto/providers/node-provider.cjs +308 -0
  41. package/dist/crypto/providers/node-provider.cjs.map +1 -0
  42. package/dist/crypto/providers/node-provider.d.cts +32 -0
  43. package/dist/crypto/providers/node-provider.d.ts +32 -0
  44. package/dist/crypto/providers/node-provider.js +306 -0
  45. package/dist/crypto/providers/node-provider.js.map +1 -0
  46. package/dist/crypto/providers/quickcrypto-provider.cjs +339 -0
  47. package/dist/crypto/providers/quickcrypto-provider.cjs.map +1 -0
  48. package/dist/crypto/providers/quickcrypto-provider.d.cts +34 -0
  49. package/dist/crypto/providers/quickcrypto-provider.d.ts +34 -0
  50. package/dist/crypto/providers/quickcrypto-provider.js +337 -0
  51. package/dist/crypto/providers/quickcrypto-provider.js.map +1 -0
  52. package/dist/crypto/providers/webcrypto-provider.cjs +310 -0
  53. package/dist/crypto/providers/webcrypto-provider.cjs.map +1 -0
  54. package/dist/crypto/providers/webcrypto-provider.d.cts +30 -0
  55. package/dist/crypto/providers/webcrypto-provider.d.ts +30 -0
  56. package/dist/crypto/providers/webcrypto-provider.js +308 -0
  57. package/dist/crypto/providers/webcrypto-provider.js.map +1 -0
  58. package/dist/crypto-BUS06Qz-.d.cts +40 -0
  59. package/dist/crypto-BUS06Qz-.d.ts +40 -0
  60. package/dist/crypto-export.cjs +790 -0
  61. package/dist/crypto-export.cjs.map +1 -0
  62. package/dist/crypto-export.d.cts +257 -0
  63. package/dist/crypto-export.d.ts +257 -0
  64. package/dist/crypto-export.js +709 -0
  65. package/dist/crypto-export.js.map +1 -0
  66. package/dist/crypto-provider-deYoVIxi.d.cts +36 -0
  67. package/dist/crypto-provider-deYoVIxi.d.ts +36 -0
  68. package/dist/index.cjs +615 -0
  69. package/dist/index.cjs.map +1 -0
  70. package/dist/index.d.cts +379 -0
  71. package/dist/index.d.ts +379 -0
  72. package/dist/index.js +504 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/schemas-export.cjs +294 -0
  75. package/dist/schemas-export.cjs.map +1 -0
  76. package/dist/schemas-export.d.cts +1598 -0
  77. package/dist/schemas-export.d.ts +1598 -0
  78. package/dist/schemas-export.js +5 -0
  79. package/dist/schemas-export.js.map +1 -0
  80. package/dist/siwe-export.cjs +237 -0
  81. package/dist/siwe-export.cjs.map +1 -0
  82. package/dist/siwe-export.d.cts +27 -0
  83. package/dist/siwe-export.d.ts +27 -0
  84. package/dist/siwe-export.js +228 -0
  85. package/dist/siwe-export.js.map +1 -0
  86. package/dist/testing.cjs +54 -0
  87. package/dist/testing.cjs.map +1 -0
  88. package/dist/testing.d.cts +20 -0
  89. package/dist/testing.d.ts +20 -0
  90. package/dist/testing.js +51 -0
  91. package/dist/testing.js.map +1 -0
  92. package/dist/validation-export.cjs +359 -0
  93. package/dist/validation-export.cjs.map +1 -0
  94. package/dist/validation-export.d.cts +3 -0
  95. package/dist/validation-export.d.ts +3 -0
  96. package/dist/validation-export.js +6 -0
  97. package/dist/validation-export.js.map +1 -0
  98. package/dist/validators-export.cjs +73 -0
  99. package/dist/validators-export.cjs.map +1 -0
  100. package/dist/validators-export.d.cts +37 -0
  101. package/dist/validators-export.d.ts +37 -0
  102. package/dist/validators-export.js +4 -0
  103. package/dist/validators-export.js.map +1 -0
  104. package/package.json +140 -0
  105. package/src/constants/index.ts +205 -0
  106. package/src/crypto/context.ts +228 -0
  107. package/src/crypto/diagnostics.ts +772 -0
  108. package/src/crypto/errors.ts +114 -0
  109. package/src/crypto/index.ts +89 -0
  110. package/src/crypto/payload-handler.ts +102 -0
  111. package/src/crypto/providers/compliance-provider.ts +579 -0
  112. package/src/crypto/providers/factory.ts +204 -0
  113. package/src/crypto/providers/index.ts +44 -0
  114. package/src/crypto/providers/noble-provider.ts +392 -0
  115. package/src/crypto/providers/node-provider.ts +433 -0
  116. package/src/crypto/providers/quickcrypto-provider.ts +483 -0
  117. package/src/crypto/providers/registry.ts +129 -0
  118. package/src/crypto/providers/webcrypto-provider.ts +364 -0
  119. package/src/crypto/session-security.ts +185 -0
  120. package/src/crypto/types.ts +93 -0
  121. package/src/crypto/utils.ts +190 -0
  122. package/src/crypto-export.ts +21 -0
  123. package/src/index.ts +38 -0
  124. package/src/schemas/auth.ts +60 -0
  125. package/src/schemas/client-messages.ts +57 -0
  126. package/src/schemas/core.ts +144 -0
  127. package/src/schemas/crypto.ts +65 -0
  128. package/src/schemas/discovery.ts +79 -0
  129. package/src/schemas/index.ts +239 -0
  130. package/src/schemas/relay-messages.ts +45 -0
  131. package/src/schemas/wallet-messages.ts +177 -0
  132. package/src/schemas-export.ts +23 -0
  133. package/src/siwe-export.ts +27 -0
  134. package/src/testing.ts +71 -0
  135. package/src/types/auth.ts +60 -0
  136. package/src/types/client-messages.ts +84 -0
  137. package/src/types/core.ts +131 -0
  138. package/src/types/crypto-provider.ts +264 -0
  139. package/src/types/crypto.ts +90 -0
  140. package/src/types/discovery.ts +50 -0
  141. package/src/types/errors.ts +87 -0
  142. package/src/types/index.ts +197 -0
  143. package/src/types/post-auth-operations.ts +363 -0
  144. package/src/types/providers.ts +72 -0
  145. package/src/types/relay-messages.ts +60 -0
  146. package/src/types/request-lifecycle.ts +161 -0
  147. package/src/types/signing-operations.ts +99 -0
  148. package/src/types/wallet-messages.ts +251 -0
  149. package/src/utils/client-session-claim.ts +188 -0
  150. package/src/utils/index.ts +54 -0
  151. package/src/utils/public-keys.ts +49 -0
  152. package/src/utils/siwe.ts +362 -0
  153. package/src/utils/url-decoding.ts +126 -0
  154. package/src/utils/url-encoding.ts +144 -0
  155. package/src/utils/wallet-session-claim.ts +188 -0
  156. package/src/validation-export.ts +32 -0
  157. package/src/validators/index.ts +222 -0
  158. package/src/validators-export.ts +8 -0
@@ -0,0 +1,840 @@
1
+ import { getRegisteredCryptoProviders, getCryptoProviderFactory } from './chunk-TCVKC227.js';
2
+ import { __name } from './chunk-WCQVDF3K.js';
3
+
4
+ // src/crypto/errors.ts
5
+ var _CryptoError = class _CryptoError extends Error {
6
+ constructor(message, code, context) {
7
+ super(message);
8
+ this.code = code;
9
+ this.context = context;
10
+ this.name = "CryptoError";
11
+ if (Error.captureStackTrace) {
12
+ Error.captureStackTrace(this, this.constructor);
13
+ }
14
+ }
15
+ };
16
+ __name(_CryptoError, "CryptoError");
17
+ var CryptoError = _CryptoError;
18
+ var _CryptoProviderUnavailableError = class _CryptoProviderUnavailableError extends CryptoError {
19
+ constructor(message, context) {
20
+ super(message, "PROVIDER_UNAVAILABLE", context);
21
+ this.name = "CryptoProviderUnavailableError";
22
+ }
23
+ /**
24
+ * Format a developer-friendly error message with context
25
+ * Includes available alternatives and actionable recommendations
26
+ */
27
+ toDevMessage() {
28
+ if (!this.context) {
29
+ return this.message;
30
+ }
31
+ const ctx = this.context;
32
+ const lines = [
33
+ this.message,
34
+ "",
35
+ "Available providers:",
36
+ ...ctx.availableProviders.map((p) => ` - ${p}`)
37
+ ];
38
+ if (ctx.recommendations.length > 0) {
39
+ lines.push("", "Recommendations:");
40
+ lines.push(...ctx.recommendations.map((r) => ` - ${r}`));
41
+ }
42
+ if (ctx.platform) {
43
+ const platformType = ctx.platform.isNode ? "Node.js" : ctx.platform.isBrowser ? "Browser" : ctx.platform.isReactNative ? "React Native" : "Unknown";
44
+ lines.push("", `Platform: ${platformType}`);
45
+ if (ctx.platform.platform) {
46
+ lines.push(`OS: ${ctx.platform.platform}`);
47
+ }
48
+ if (ctx.platform.userAgent) {
49
+ const ua = ctx.platform.userAgent;
50
+ const truncated = ua.length > 100 ? `${ua.substring(0, 100)}...` : ua;
51
+ lines.push(`User Agent: ${truncated}`);
52
+ }
53
+ }
54
+ return lines.join("\n");
55
+ }
56
+ };
57
+ __name(_CryptoProviderUnavailableError, "CryptoProviderUnavailableError");
58
+ var CryptoProviderUnavailableError = _CryptoProviderUnavailableError;
59
+ var _CryptoCapabilityMissingError = class _CryptoCapabilityMissingError extends CryptoError {
60
+ constructor(operation, provider, reason) {
61
+ super(
62
+ `Crypto operation '${operation}' is not available in provider '${provider}': ${reason}`,
63
+ "CAPABILITY_MISSING",
64
+ { operation, provider, reason }
65
+ );
66
+ this.name = "CryptoCapabilityMissingError";
67
+ }
68
+ };
69
+ __name(_CryptoCapabilityMissingError, "CryptoCapabilityMissingError");
70
+ var CryptoCapabilityMissingError = _CryptoCapabilityMissingError;
71
+
72
+ // src/crypto/providers/compliance-provider.ts
73
+ var _DefaultComplianceAuditor = class _DefaultComplianceAuditor {
74
+ constructor(logger) {
75
+ this.auditLog = [];
76
+ this.logger = logger?.child({ component: "ComplianceAuditor" });
77
+ }
78
+ logEvent(event) {
79
+ this.auditLog.push(event);
80
+ this.logger?.info("Compliance audit event", {
81
+ eventType: event.eventType,
82
+ success: event.success,
83
+ sessionId: event.sessionId,
84
+ timestamp: event.timestamp
85
+ });
86
+ }
87
+ getAuditLog() {
88
+ return [...this.auditLog];
89
+ }
90
+ clearAuditLog() {
91
+ this.auditLog = [];
92
+ this.logger?.debug("Compliance audit log cleared");
93
+ }
94
+ };
95
+ __name(_DefaultComplianceAuditor, "DefaultComplianceAuditor");
96
+ var DefaultComplianceAuditor = _DefaultComplianceAuditor;
97
+ var _ComplianceCryptoProvider = class _ComplianceCryptoProvider {
98
+ constructor(underlyingProvider, config = {}, logger) {
99
+ this.underlyingProvider = underlyingProvider;
100
+ this.config = config;
101
+ this.auditor = config.auditor || new DefaultComplianceAuditor(logger);
102
+ this.logger = logger?.child({
103
+ component: "ComplianceCryptoProvider",
104
+ underlyingProvider: underlyingProvider.name
105
+ });
106
+ this.name = `Compliance(${underlyingProvider.name})`;
107
+ this.isAvailable = underlyingProvider.isAvailable;
108
+ }
109
+ /**
110
+ * Create compliance audit event
111
+ */
112
+ createAuditEvent(eventType, success, metadata = {}, error) {
113
+ return {
114
+ eventType,
115
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
116
+ sessionId: this.config.sessionId,
117
+ success,
118
+ error,
119
+ metadata,
120
+ ...metadata
121
+ };
122
+ }
123
+ /**
124
+ * Validate key usage restrictions
125
+ */
126
+ validateKeyUsage(operation, keyUsages, dataSize) {
127
+ const restrictions = this.config.keyRestrictions;
128
+ if (!restrictions) return;
129
+ if (restrictions.requireSessionId && !this.config.sessionId) {
130
+ throw new Error("Session ID required for compliance but not provided");
131
+ }
132
+ if (restrictions.maxDataSize && dataSize && dataSize > restrictions.maxDataSize) {
133
+ throw new Error(`Data size ${dataSize} exceeds maximum allowed ${restrictions.maxDataSize} bytes`);
134
+ }
135
+ if (keyUsages && restrictions.requiredKeyUsages) {
136
+ const hasRequiredUsage = restrictions.requiredKeyUsages.some((usage) => keyUsages.includes(usage));
137
+ if (!hasRequiredUsage) {
138
+ throw new Error(`Key must have one of required usages: ${restrictions.requiredKeyUsages.join(", ")}`);
139
+ }
140
+ }
141
+ if (keyUsages && restrictions.forbiddenKeyUsages) {
142
+ const hasForbiddenUsage = restrictions.forbiddenKeyUsages.some((usage) => keyUsages.includes(usage));
143
+ if (hasForbiddenUsage) {
144
+ throw new Error(`Key has forbidden usage. Forbidden: ${restrictions.forbiddenKeyUsages.join(", ")}`);
145
+ }
146
+ }
147
+ if (operation === "export" && restrictions.allowKeyExport === false) {
148
+ throw new Error("Key export is forbidden by compliance policy");
149
+ }
150
+ if (operation === "import" && restrictions.allowKeyImport === false) {
151
+ throw new Error("Key import is forbidden by compliance policy");
152
+ }
153
+ }
154
+ /**
155
+ * Generate ECDH P-256 key pair with compliance audit
156
+ */
157
+ async generateKeyPair() {
158
+ const startTime = Date.now();
159
+ try {
160
+ this.logger?.debug("Generating key pair with compliance audit");
161
+ const keyPair = await this.underlyingProvider.generateKeyPair();
162
+ this.validateKeyUsage("generation", keyPair.privateKey.usages);
163
+ this.auditor.logEvent(this.createAuditEvent("key_generation", true, {
164
+ algorithm: keyPair.privateKey.algorithm,
165
+ keyUsage: keyPair.privateKey.usages,
166
+ duration: Date.now() - startTime
167
+ }));
168
+ return keyPair;
169
+ } catch (error) {
170
+ this.auditor.logEvent(this.createAuditEvent("key_generation", false, {
171
+ duration: Date.now() - startTime
172
+ }, error instanceof Error ? error.message : String(error)));
173
+ throw error;
174
+ }
175
+ }
176
+ /**
177
+ * Export public key with compliance audit
178
+ */
179
+ async exportPublicKey(publicKey) {
180
+ const startTime = Date.now();
181
+ try {
182
+ this.validateKeyUsage("export", publicKey.usages);
183
+ const keyData = await this.underlyingProvider.exportPublicKey(publicKey);
184
+ this.auditor.logEvent(this.createAuditEvent("key_export", true, {
185
+ keyType: "public",
186
+ algorithm: publicKey.algorithm,
187
+ keySize: keyData.byteLength,
188
+ duration: Date.now() - startTime
189
+ }));
190
+ return keyData;
191
+ } catch (error) {
192
+ this.auditor.logEvent(this.createAuditEvent("key_export", false, {
193
+ keyType: "public",
194
+ algorithm: publicKey.algorithm,
195
+ duration: Date.now() - startTime
196
+ }, error instanceof Error ? error.message : String(error)));
197
+ throw error;
198
+ }
199
+ }
200
+ /**
201
+ * Export private key with compliance audit
202
+ */
203
+ async exportPrivateKey(privateKey) {
204
+ const startTime = Date.now();
205
+ try {
206
+ this.validateKeyUsage("export", privateKey.usages);
207
+ if (this.config.enableStrictMode) {
208
+ this.logger?.warn("Private key export in strict compliance mode", {
209
+ sessionId: this.config.sessionId,
210
+ algorithm: privateKey.algorithm
211
+ });
212
+ }
213
+ const keyData = await this.underlyingProvider.exportPrivateKey(privateKey);
214
+ this.auditor.logEvent(this.createAuditEvent("key_export", true, {
215
+ keyType: "private",
216
+ algorithm: privateKey.algorithm,
217
+ keySize: keyData.byteLength,
218
+ strictMode: this.config.enableStrictMode,
219
+ duration: Date.now() - startTime
220
+ }));
221
+ return keyData;
222
+ } catch (error) {
223
+ this.auditor.logEvent(this.createAuditEvent("key_export", false, {
224
+ keyType: "private",
225
+ algorithm: privateKey.algorithm,
226
+ strictMode: this.config.enableStrictMode,
227
+ duration: Date.now() - startTime
228
+ }, error instanceof Error ? error.message : String(error)));
229
+ throw error;
230
+ }
231
+ }
232
+ /**
233
+ * Import public key with compliance audit
234
+ */
235
+ async importPublicKey(keyData) {
236
+ const startTime = Date.now();
237
+ try {
238
+ this.validateKeyUsage("import");
239
+ const key = await this.underlyingProvider.importPublicKey(keyData);
240
+ this.auditor.logEvent(this.createAuditEvent("key_import", true, {
241
+ keyType: "public",
242
+ algorithm: key.algorithm,
243
+ keySize: keyData.byteLength,
244
+ keyUsage: key.usages,
245
+ duration: Date.now() - startTime
246
+ }));
247
+ return key;
248
+ } catch (error) {
249
+ this.auditor.logEvent(this.createAuditEvent("key_import", false, {
250
+ keyType: "public",
251
+ keySize: keyData.byteLength,
252
+ duration: Date.now() - startTime
253
+ }, error instanceof Error ? error.message : String(error)));
254
+ throw error;
255
+ }
256
+ }
257
+ /**
258
+ * Import private key with compliance audit
259
+ */
260
+ async importPrivateKey(keyData) {
261
+ const startTime = Date.now();
262
+ try {
263
+ this.validateKeyUsage("import");
264
+ const key = await this.underlyingProvider.importPrivateKey(keyData);
265
+ this.auditor.logEvent(this.createAuditEvent("key_import", true, {
266
+ keyType: "private",
267
+ algorithm: key.algorithm,
268
+ keySize: keyData.byteLength,
269
+ keyUsage: key.usages,
270
+ duration: Date.now() - startTime
271
+ }));
272
+ return key;
273
+ } catch (error) {
274
+ this.auditor.logEvent(this.createAuditEvent("key_import", false, {
275
+ keyType: "private",
276
+ keySize: keyData.byteLength,
277
+ duration: Date.now() - startTime
278
+ }, error instanceof Error ? error.message : String(error)));
279
+ throw error;
280
+ }
281
+ }
282
+ /**
283
+ * Derive shared secret with compliance audit
284
+ */
285
+ async deriveSharedSecret(privateKey, publicKey) {
286
+ const startTime = Date.now();
287
+ try {
288
+ this.validateKeyUsage("derivation", privateKey.usages);
289
+ const sharedSecret = await this.underlyingProvider.deriveSharedSecret(privateKey, publicKey);
290
+ this.auditor.logEvent(this.createAuditEvent("key_derivation", true, {
291
+ operation: "ECDH",
292
+ algorithm: privateKey.algorithm,
293
+ duration: Date.now() - startTime
294
+ }));
295
+ return sharedSecret;
296
+ } catch (error) {
297
+ this.auditor.logEvent(this.createAuditEvent("key_derivation", false, {
298
+ operation: "ECDH",
299
+ algorithm: privateKey.algorithm,
300
+ duration: Date.now() - startTime
301
+ }, error instanceof Error ? error.message : String(error)));
302
+ throw error;
303
+ }
304
+ }
305
+ /**
306
+ * Derive encryption key with compliance audit
307
+ */
308
+ async deriveEncryptionKey(sharedSecret, salt, info) {
309
+ const startTime = Date.now();
310
+ try {
311
+ const encryptionKey = await this.underlyingProvider.deriveEncryptionKey(sharedSecret, salt, info);
312
+ this.auditor.logEvent(this.createAuditEvent("key_derivation", true, {
313
+ operation: "HKDF",
314
+ algorithm: "HKDF-SHA256",
315
+ saltSize: salt.byteLength,
316
+ infoSize: info.byteLength,
317
+ duration: Date.now() - startTime
318
+ }));
319
+ return encryptionKey;
320
+ } catch (error) {
321
+ this.auditor.logEvent(this.createAuditEvent("key_derivation", false, {
322
+ operation: "HKDF",
323
+ algorithm: "HKDF-SHA256",
324
+ saltSize: salt.byteLength,
325
+ infoSize: info.byteLength,
326
+ duration: Date.now() - startTime
327
+ }, error instanceof Error ? error.message : String(error)));
328
+ throw error;
329
+ }
330
+ }
331
+ /**
332
+ * Generate random bytes with compliance audit
333
+ */
334
+ randomBytes(length) {
335
+ const startTime = Date.now();
336
+ try {
337
+ const randomData = this.underlyingProvider.randomBytes(length);
338
+ this.auditor.logEvent(this.createAuditEvent("random_generation", true, {
339
+ length,
340
+ duration: Date.now() - startTime
341
+ }));
342
+ return randomData;
343
+ } catch (error) {
344
+ this.auditor.logEvent(this.createAuditEvent("random_generation", false, {
345
+ length,
346
+ duration: Date.now() - startTime
347
+ }, error instanceof Error ? error.message : String(error)));
348
+ throw error;
349
+ }
350
+ }
351
+ /**
352
+ * Encrypt data with compliance audit
353
+ */
354
+ async encrypt(key, data, iv) {
355
+ const startTime = Date.now();
356
+ try {
357
+ this.validateKeyUsage("encryption", key.usages, data.byteLength);
358
+ const ciphertext = await this.underlyingProvider.encrypt(key, data, iv);
359
+ this.auditor.logEvent(this.createAuditEvent("encryption", true, {
360
+ algorithm: key.algorithm,
361
+ dataSize: data.byteLength,
362
+ ivSize: iv.byteLength,
363
+ ciphertextSize: ciphertext.byteLength,
364
+ duration: Date.now() - startTime
365
+ }));
366
+ return ciphertext;
367
+ } catch (error) {
368
+ this.auditor.logEvent(this.createAuditEvent("encryption", false, {
369
+ algorithm: key.algorithm,
370
+ dataSize: data.byteLength,
371
+ ivSize: iv.byteLength,
372
+ duration: Date.now() - startTime
373
+ }, error instanceof Error ? error.message : String(error)));
374
+ throw error;
375
+ }
376
+ }
377
+ /**
378
+ * Decrypt data with compliance audit
379
+ */
380
+ async decrypt(key, data, iv) {
381
+ const startTime = Date.now();
382
+ try {
383
+ this.validateKeyUsage("decryption", key.usages, data.byteLength);
384
+ const plaintext = await this.underlyingProvider.decrypt(key, data, iv);
385
+ this.auditor.logEvent(this.createAuditEvent("decryption", true, {
386
+ algorithm: key.algorithm,
387
+ dataSize: data.byteLength,
388
+ ivSize: iv.byteLength,
389
+ plaintextSize: plaintext.byteLength,
390
+ duration: Date.now() - startTime
391
+ }));
392
+ return plaintext;
393
+ } catch (error) {
394
+ this.auditor.logEvent(this.createAuditEvent("decryption", false, {
395
+ algorithm: key.algorithm,
396
+ dataSize: data.byteLength,
397
+ ivSize: iv.byteLength,
398
+ duration: Date.now() - startTime
399
+ }, error instanceof Error ? error.message : String(error)));
400
+ throw error;
401
+ }
402
+ }
403
+ /**
404
+ * Generate HMAC with compliance audit
405
+ */
406
+ async generateHMAC(key, data) {
407
+ const startTime = Date.now();
408
+ try {
409
+ this.validateKeyUsage("hmac", key.usages, data.byteLength);
410
+ const mac = await this.underlyingProvider.generateHMAC(key, data);
411
+ this.auditor.logEvent(this.createAuditEvent("hmac_generation", true, {
412
+ algorithm: "HMAC-SHA256",
413
+ dataSize: data.byteLength,
414
+ macSize: mac.byteLength,
415
+ duration: Date.now() - startTime
416
+ }));
417
+ return mac;
418
+ } catch (error) {
419
+ this.auditor.logEvent(this.createAuditEvent("hmac_generation", false, {
420
+ algorithm: "HMAC-SHA256",
421
+ dataSize: data.byteLength,
422
+ duration: Date.now() - startTime
423
+ }, error instanceof Error ? error.message : String(error)));
424
+ throw error;
425
+ }
426
+ }
427
+ /**
428
+ * Verify HMAC with compliance audit
429
+ */
430
+ async verifyHMAC(key, data, mac) {
431
+ const startTime = Date.now();
432
+ try {
433
+ this.validateKeyUsage("hmac", key.usages, data.byteLength);
434
+ const isValid = await this.underlyingProvider.verifyHMAC(key, data, mac);
435
+ this.auditor.logEvent(this.createAuditEvent("hmac_verification", true, {
436
+ algorithm: "HMAC-SHA256",
437
+ dataSize: data.byteLength,
438
+ macSize: mac.byteLength,
439
+ verified: isValid,
440
+ duration: Date.now() - startTime
441
+ }));
442
+ return isValid;
443
+ } catch (error) {
444
+ this.auditor.logEvent(this.createAuditEvent("hmac_verification", false, {
445
+ algorithm: "HMAC-SHA256",
446
+ dataSize: data.byteLength,
447
+ macSize: mac.byteLength,
448
+ duration: Date.now() - startTime
449
+ }, error instanceof Error ? error.message : String(error)));
450
+ throw error;
451
+ }
452
+ }
453
+ /**
454
+ * Get compliance auditor for external access
455
+ */
456
+ getAuditor() {
457
+ return this.auditor;
458
+ }
459
+ /**
460
+ * Update compliance configuration
461
+ */
462
+ updateConfig(newConfig) {
463
+ Object.assign(this.config, newConfig);
464
+ this.logger?.debug("Compliance configuration updated", newConfig);
465
+ }
466
+ /**
467
+ * Get underlying provider (for debugging/testing)
468
+ */
469
+ getUnderlyingProvider() {
470
+ return this.underlyingProvider;
471
+ }
472
+ };
473
+ __name(_ComplianceCryptoProvider, "ComplianceCryptoProvider");
474
+ var ComplianceCryptoProvider = _ComplianceCryptoProvider;
475
+
476
+ // src/crypto/context.ts
477
+ var _CryptoContextManager = class _CryptoContextManager {
478
+ constructor() {
479
+ this.provider = null;
480
+ this.config = null;
481
+ this.initialized = false;
482
+ this.initializing = false;
483
+ }
484
+ /**
485
+ * Initialize the crypto context with specific configuration
486
+ *
487
+ * @param config - Provider configuration options
488
+ * @throws Error if already initialized (call reset() first)
489
+ * @throws CryptoProviderUnavailableError if strict mode enabled and provider unavailable
490
+ */
491
+ initialize(config = {}) {
492
+ if (this.initialized && this.provider) {
493
+ throw new Error(
494
+ "CryptoContext already initialized. Call CryptoContext.reset() first to reconfigure."
495
+ );
496
+ }
497
+ if (config.strict && config.type) {
498
+ const availableProviders = getRegisteredCryptoProviders();
499
+ if (!availableProviders.includes(config.type)) {
500
+ const platform = detectPlatform();
501
+ const recommendations = [
502
+ `Import the provider: import '@bananalink-sdk/protocol/crypto/provider/${config.type}'`,
503
+ "Ensure the provider package is installed"
504
+ ];
505
+ if (config.type === "quickcrypto" && !platform.isReactNative) {
506
+ recommendations.push("QuickCrypto requires React Native environment");
507
+ if (platform.isNode) {
508
+ recommendations.push("Try 'node' provider for Node.js");
509
+ } else if (platform.isBrowser) {
510
+ recommendations.push("Try 'webcrypto' provider for browsers");
511
+ }
512
+ }
513
+ if (availableProviders.includes("noble")) {
514
+ recommendations.push("'noble' provider works in all environments as a fallback");
515
+ }
516
+ throw new CryptoProviderUnavailableError(
517
+ `Strict mode: Crypto provider '${config.type}' is not registered. Did you forget to import it?`,
518
+ {
519
+ requestedProvider: config.type,
520
+ availableProviders,
521
+ platform,
522
+ recommendations
523
+ }
524
+ );
525
+ }
526
+ }
527
+ this.config = config;
528
+ this.provider = this.createProvider(config);
529
+ this.initialized = true;
530
+ }
531
+ /**
532
+ * Get the active crypto provider
533
+ * Automatically initializes with default config if not already initialized
534
+ *
535
+ * @returns The active crypto provider instance
536
+ * @throws Error if called concurrently during initialization
537
+ *
538
+ * @remarks
539
+ * This method performs lazy initialization on first call. It is NOT safe to call
540
+ * concurrently from multiple contexts before initialization completes (e.g., from
541
+ * Worker threads or Promise.all). For concurrent access scenarios, explicitly call
542
+ * initialize() first to ensure the provider is ready before concurrent operations begin.
543
+ *
544
+ * @example
545
+ * ```typescript
546
+ * // Safe: Single-threaded lazy initialization
547
+ * const provider = CryptoContext.getProvider();
548
+ *
549
+ * // Safe: Pre-initialize for concurrent access
550
+ * CryptoContext.initialize({ type: 'noble' });
551
+ * await Promise.all([
552
+ * operation1(CryptoContext.getProvider()),
553
+ * operation2(CryptoContext.getProvider())
554
+ * ]);
555
+ *
556
+ * // Unsafe: Concurrent calls during lazy initialization
557
+ * await Promise.all([
558
+ * operation1(CryptoContext.getProvider()), // May throw if not initialized yet
559
+ * operation2(CryptoContext.getProvider())
560
+ * ]);
561
+ * ```
562
+ */
563
+ getProvider() {
564
+ if (this.provider) {
565
+ return this.provider;
566
+ }
567
+ if (this.initializing) {
568
+ throw new Error(
569
+ "CryptoContext initialization in progress. Avoid concurrent calls to getProvider() during initialization."
570
+ );
571
+ }
572
+ this.initializing = true;
573
+ try {
574
+ this.initialize();
575
+ if (!this.provider) {
576
+ throw new Error("CryptoContext initialization failed: provider is null");
577
+ }
578
+ return this.provider;
579
+ } finally {
580
+ this.initializing = false;
581
+ }
582
+ }
583
+ /**
584
+ * Set a custom provider instance
585
+ * Useful for testing or advanced use cases
586
+ *
587
+ * @param provider - Custom provider instance
588
+ */
589
+ setProvider(provider) {
590
+ this.provider = provider;
591
+ this.initialized = true;
592
+ }
593
+ /**
594
+ * Check if context has been explicitly initialized
595
+ */
596
+ isInitialized() {
597
+ return this.initialized;
598
+ }
599
+ /**
600
+ * Get current configuration
601
+ */
602
+ getConfig() {
603
+ return this.config;
604
+ }
605
+ /**
606
+ * Reset the context (for testing or reconfiguration)
607
+ */
608
+ reset() {
609
+ this.provider = null;
610
+ this.config = null;
611
+ this.initialized = false;
612
+ this.initializing = false;
613
+ }
614
+ /**
615
+ * Create a provider instance from configuration
616
+ */
617
+ createProvider(config) {
618
+ const baseProvider = createCryptoProvider(config.type, config.logger, config.strict);
619
+ if (config.compliance?.enabled) {
620
+ return new ComplianceCryptoProvider(baseProvider, config.compliance);
621
+ }
622
+ return baseProvider;
623
+ }
624
+ };
625
+ __name(_CryptoContextManager, "CryptoContextManager");
626
+ var CryptoContextManager = _CryptoContextManager;
627
+ var CryptoContext = new CryptoContextManager();
628
+
629
+ // src/crypto/utils.ts
630
+ function randomBytes(length, provider) {
631
+ const activeProvider = provider || CryptoContext.getProvider();
632
+ const buffer = activeProvider.randomBytes(length);
633
+ return new Uint8Array(buffer);
634
+ }
635
+ __name(randomBytes, "randomBytes");
636
+ function arrayBufferToBase64(buffer) {
637
+ const bytes = new Uint8Array(buffer);
638
+ let binary = "";
639
+ for (let i = 0; i < bytes.byteLength; i++) {
640
+ binary += String.fromCharCode(bytes[i]);
641
+ }
642
+ return btoa(binary);
643
+ }
644
+ __name(arrayBufferToBase64, "arrayBufferToBase64");
645
+ function base64ToArrayBuffer(base64) {
646
+ const cleanBase64 = base64.replace(/[^A-Za-z0-9+/=]/g, "");
647
+ let paddedBase64 = cleanBase64;
648
+ while (paddedBase64.length % 4 !== 0) {
649
+ paddedBase64 += "=";
650
+ }
651
+ try {
652
+ const binary = atob(paddedBase64);
653
+ const bytes = new Uint8Array(binary.length);
654
+ for (let i = 0; i < binary.length; i++) {
655
+ bytes[i] = binary.charCodeAt(i);
656
+ }
657
+ return bytes.buffer;
658
+ } catch (error) {
659
+ throw new Error(`Failed to decode base64 string: ${error instanceof Error ? error.message : "Invalid base64 format"}. Original string: ${base64.substring(0, 50)}...`);
660
+ }
661
+ }
662
+ __name(base64ToArrayBuffer, "base64ToArrayBuffer");
663
+ function stringToArrayBuffer(str) {
664
+ return new TextEncoder().encode(str).buffer;
665
+ }
666
+ __name(stringToArrayBuffer, "stringToArrayBuffer");
667
+ function arrayBufferToString(buffer) {
668
+ return new TextDecoder().decode(buffer);
669
+ }
670
+ __name(arrayBufferToString, "arrayBufferToString");
671
+ function generateNonce(length = 32, provider) {
672
+ const bytes = randomBytes(length, provider);
673
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
674
+ }
675
+ __name(generateNonce, "generateNonce");
676
+ function generateUUID(provider) {
677
+ const bytes = randomBytes(16, provider);
678
+ bytes[6] = bytes[6] & 15 | 64;
679
+ bytes[8] = bytes[8] & 63 | 128;
680
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
681
+ return [
682
+ hex.slice(0, 8),
683
+ hex.slice(8, 12),
684
+ hex.slice(12, 16),
685
+ hex.slice(16, 20),
686
+ hex.slice(20, 32)
687
+ ].join("-");
688
+ }
689
+ __name(generateUUID, "generateUUID");
690
+ function detectPlatform() {
691
+ const isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
692
+ const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
693
+ const isReactNative = typeof navigator !== "undefined" && navigator.product === "ReactNative";
694
+ let platform;
695
+ if (isNode && typeof process.platform === "string") {
696
+ platform = process.platform;
697
+ }
698
+ let userAgent;
699
+ if (typeof navigator !== "undefined" && typeof navigator.userAgent === "string") {
700
+ userAgent = navigator.userAgent;
701
+ }
702
+ return {
703
+ isNode,
704
+ isBrowser,
705
+ isReactNative,
706
+ platform,
707
+ userAgent
708
+ };
709
+ }
710
+ __name(detectPlatform, "detectPlatform");
711
+
712
+ // src/crypto/providers/factory.ts
713
+ function generateRecommendations(requestedProvider, platform) {
714
+ const recommendations = [];
715
+ if (requestedProvider === "webcrypto") {
716
+ recommendations.push("WebCrypto requires a browser or Node.js 15+ environment");
717
+ if (platform.isNode) {
718
+ recommendations.push("Try 'node' provider for Node.js");
719
+ }
720
+ } else if (requestedProvider === "node") {
721
+ recommendations.push("Node crypto requires Node.js environment");
722
+ if (platform.isBrowser) {
723
+ recommendations.push("Try 'webcrypto' provider for browsers");
724
+ }
725
+ } else if (requestedProvider === "quickcrypto") {
726
+ recommendations.push("QuickCrypto requires React Native environment");
727
+ if (!platform.isReactNative) {
728
+ if (platform.isNode) {
729
+ recommendations.push("Try 'node' provider for Node.js");
730
+ } else if (platform.isBrowser) {
731
+ recommendations.push("Try 'webcrypto' provider for browsers");
732
+ }
733
+ }
734
+ }
735
+ recommendations.push("'noble' provider works in all environments as a fallback");
736
+ recommendations.push(`Import the provider: import '@bananalink-sdk/protocol/crypto/provider/${requestedProvider}'`);
737
+ return recommendations;
738
+ }
739
+ __name(generateRecommendations, "generateRecommendations");
740
+ function createCryptoProvider(preferredProvider, logger, strict) {
741
+ const registeredProviders = getRegisteredCryptoProviders();
742
+ logger?.debug("Creating crypto provider", {
743
+ preferredProvider,
744
+ strict,
745
+ registeredProviders
746
+ });
747
+ let providerType = preferredProvider;
748
+ if (!providerType) {
749
+ if (registeredProviders.length === 0) {
750
+ throw new CryptoProviderUnavailableError(
751
+ "No crypto providers are registered. Did you forget to import a provider?",
752
+ {
753
+ availableProviders: [],
754
+ recommendations: [
755
+ "Import at least one crypto provider, e.g.: import '@bananalink-sdk/protocol/crypto/provider/noble'",
756
+ "Noble provider is recommended as a universal fallback"
757
+ ]
758
+ }
759
+ );
760
+ } else if (registeredProviders.length === 1) {
761
+ providerType = registeredProviders[0];
762
+ logger?.debug(`Auto-selected '${providerType}' provider (only one registered)`);
763
+ } else {
764
+ throw new CryptoProviderUnavailableError(
765
+ `Multiple crypto providers registered: ${registeredProviders.join(", ")}. Either import only one provider OR explicitly set cryptoProvider.type. Example: cryptoProvider: { type: '${registeredProviders[0]}' }`,
766
+ {
767
+ availableProviders: registeredProviders,
768
+ recommendations: [
769
+ `Import only one crypto provider, or specify which one to use`,
770
+ `Registered providers: ${registeredProviders.join(", ")}`,
771
+ `Set cryptoProvider.type to one of the registered providers`
772
+ ]
773
+ }
774
+ );
775
+ }
776
+ }
777
+ try {
778
+ const factory = getCryptoProviderFactory(providerType);
779
+ const provider = factory(logger);
780
+ logger?.info(`Using ${provider.name} crypto provider`, {
781
+ providerType,
782
+ isAvailable: provider.isAvailable
783
+ });
784
+ return provider;
785
+ } catch (error) {
786
+ const userRequestedSpecificProvider = preferredProvider !== void 0;
787
+ if (strict && userRequestedSpecificProvider) {
788
+ if (error instanceof CryptoProviderUnavailableError) {
789
+ throw error;
790
+ }
791
+ const platform2 = detectPlatform();
792
+ const availableProviders = getRegisteredCryptoProviders();
793
+ const recommendations2 = generateRecommendations(providerType, platform2);
794
+ throw new CryptoProviderUnavailableError(
795
+ `Strict mode: Crypto provider '${providerType}' failed to initialize: ${error instanceof Error ? error.message : String(error)}`,
796
+ {
797
+ requestedProvider: providerType,
798
+ availableProviders,
799
+ platform: platform2,
800
+ recommendations: recommendations2
801
+ }
802
+ );
803
+ }
804
+ logger?.warn(`Failed to create '${providerType}' provider, trying fallback`, {
805
+ error: error instanceof Error ? { message: error.message } : { message: String(error) }
806
+ });
807
+ for (const fallbackType of registeredProviders) {
808
+ if (fallbackType === providerType) continue;
809
+ try {
810
+ const factory = getCryptoProviderFactory(fallbackType);
811
+ const provider = factory(logger);
812
+ logger?.info(`Using ${provider.name} crypto provider (fallback)`, {
813
+ originalType: providerType,
814
+ fallbackType
815
+ });
816
+ return provider;
817
+ } catch (fallbackError) {
818
+ logger?.debug(`Fallback to '${fallbackType}' failed`, {
819
+ error: fallbackError instanceof Error ? { message: fallbackError.message } : { message: String(fallbackError) }
820
+ });
821
+ }
822
+ }
823
+ const platform = detectPlatform();
824
+ const recommendations = generateRecommendations(providerType, platform);
825
+ throw new CryptoProviderUnavailableError(
826
+ `Failed to create any crypto provider. Requested: '${providerType}'`,
827
+ {
828
+ requestedProvider: providerType,
829
+ availableProviders: registeredProviders,
830
+ platform,
831
+ recommendations
832
+ }
833
+ );
834
+ }
835
+ }
836
+ __name(createCryptoProvider, "createCryptoProvider");
837
+
838
+ export { ComplianceCryptoProvider, CryptoCapabilityMissingError, CryptoContext, CryptoError, CryptoProviderUnavailableError, DefaultComplianceAuditor, arrayBufferToBase64, arrayBufferToString, base64ToArrayBuffer, createCryptoProvider, detectPlatform, generateNonce, generateUUID, randomBytes, stringToArrayBuffer };
839
+ //# sourceMappingURL=chunk-LELPCIE7.js.map
840
+ //# sourceMappingURL=chunk-LELPCIE7.js.map