@veridex/sdk 1.0.0-beta.8 → 1.0.1

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 (130) hide show
  1. package/LICENSE +170 -21
  2. package/README.md +574 -117
  3. package/dist/EVMClient-DtqvdfUP.d.mts +376 -0
  4. package/dist/auth/prepareAuth.d.mts +25 -0
  5. package/dist/auth/prepareAuth.js +2406 -0
  6. package/dist/auth/prepareAuth.js.map +1 -0
  7. package/dist/auth/prepareAuth.mjs +151 -0
  8. package/dist/auth/prepareAuth.mjs.map +1 -0
  9. package/dist/chains/aptos/index.d.mts +6 -5
  10. package/dist/chains/aptos/index.js +66 -39
  11. package/dist/chains/aptos/index.js.map +1 -1
  12. package/dist/chains/aptos/index.mjs +5 -547
  13. package/dist/chains/aptos/index.mjs.map +1 -1
  14. package/dist/chains/avalanche/index.d.mts +137 -0
  15. package/dist/chains/avalanche/index.js +1555 -0
  16. package/dist/chains/avalanche/index.js.map +1 -0
  17. package/dist/chains/avalanche/index.mjs +10 -0
  18. package/dist/chains/avalanche/index.mjs.map +1 -0
  19. package/dist/chains/evm/index.d.mts +5 -3
  20. package/dist/chains/evm/index.js +165 -3
  21. package/dist/chains/evm/index.js.map +1 -1
  22. package/dist/chains/evm/index.mjs +8 -1200
  23. package/dist/chains/evm/index.mjs.map +1 -1
  24. package/dist/chains/solana/index.d.mts +1 -1
  25. package/dist/chains/solana/index.js.map +1 -1
  26. package/dist/chains/solana/index.mjs +4 -486
  27. package/dist/chains/solana/index.mjs.map +1 -1
  28. package/dist/chains/stacks/index.d.mts +559 -0
  29. package/dist/chains/stacks/index.js +1207 -0
  30. package/dist/chains/stacks/index.js.map +1 -0
  31. package/dist/chains/stacks/index.mjs +71 -0
  32. package/dist/chains/stacks/index.mjs.map +1 -0
  33. package/dist/chains/starknet/index.d.mts +3 -3
  34. package/dist/chains/starknet/index.js.map +1 -1
  35. package/dist/chains/starknet/index.mjs +5 -503
  36. package/dist/chains/starknet/index.mjs.map +1 -1
  37. package/dist/chains/sui/index.d.mts +2 -2
  38. package/dist/chains/sui/index.js.map +1 -1
  39. package/dist/chains/sui/index.mjs +5 -529
  40. package/dist/chains/sui/index.mjs.map +1 -1
  41. package/dist/chunk-5T6KPH7A.mjs +1082 -0
  42. package/dist/chunk-5T6KPH7A.mjs.map +1 -0
  43. package/dist/chunk-72ZA3OYQ.mjs +20 -0
  44. package/dist/chunk-72ZA3OYQ.mjs.map +1 -0
  45. package/dist/chunk-EFIURACP.mjs +438 -0
  46. package/dist/chunk-EFIURACP.mjs.map +1 -0
  47. package/dist/chunk-F3YAGZSW.mjs +269 -0
  48. package/dist/chunk-F3YAGZSW.mjs.map +1 -0
  49. package/dist/chunk-GWJRKDSA.mjs +549 -0
  50. package/dist/chunk-GWJRKDSA.mjs.map +1 -0
  51. package/dist/chunk-M3MM4YMF.mjs +417 -0
  52. package/dist/chunk-M3MM4YMF.mjs.map +1 -0
  53. package/dist/chunk-N4A2RMUN.mjs +216 -0
  54. package/dist/chunk-N4A2RMUN.mjs.map +1 -0
  55. package/dist/chunk-NUWSMJFJ.mjs +179 -0
  56. package/dist/chunk-NUWSMJFJ.mjs.map +1 -0
  57. package/dist/chunk-OVMMTL6H.mjs +330 -0
  58. package/dist/chunk-OVMMTL6H.mjs.map +1 -0
  59. package/dist/chunk-PDHZ5X5O.mjs +565 -0
  60. package/dist/chunk-PDHZ5X5O.mjs.map +1 -0
  61. package/dist/chunk-PRHNGA4G.mjs +464 -0
  62. package/dist/chunk-PRHNGA4G.mjs.map +1 -0
  63. package/dist/chunk-Q5O3M5LP.mjs +422 -0
  64. package/dist/chunk-Q5O3M5LP.mjs.map +1 -0
  65. package/dist/chunk-QDO6NQ7P.mjs +840 -0
  66. package/dist/chunk-QDO6NQ7P.mjs.map +1 -0
  67. package/dist/chunk-QT4ZZ4GM.mjs +509 -0
  68. package/dist/chunk-QT4ZZ4GM.mjs.map +1 -0
  69. package/dist/chunk-USDA5JTN.mjs +1249 -0
  70. package/dist/chunk-USDA5JTN.mjs.map +1 -0
  71. package/dist/chunk-V636MIV3.mjs +52 -0
  72. package/dist/chunk-V636MIV3.mjs.map +1 -0
  73. package/dist/chunk-X7BZMSPQ.mjs +407 -0
  74. package/dist/chunk-X7BZMSPQ.mjs.map +1 -0
  75. package/dist/chunk-YCUJZ6Z7.mjs +829 -0
  76. package/dist/chunk-YCUJZ6Z7.mjs.map +1 -0
  77. package/dist/constants.d.mts +1 -1
  78. package/dist/constants.js +26 -12
  79. package/dist/constants.js.map +1 -1
  80. package/dist/constants.mjs +16 -375
  81. package/dist/constants.mjs.map +1 -1
  82. package/dist/index-DDalBhAm.d.mts +243 -0
  83. package/dist/index.d.mts +2508 -556
  84. package/dist/index.js +14576 -9628
  85. package/dist/index.js.map +1 -1
  86. package/dist/index.mjs +4108 -7840
  87. package/dist/index.mjs.map +1 -1
  88. package/dist/passkey.d.mts +182 -0
  89. package/dist/passkey.js +914 -0
  90. package/dist/passkey.js.map +1 -0
  91. package/dist/passkey.mjs +15 -0
  92. package/dist/passkey.mjs.map +1 -0
  93. package/dist/payload.js.map +1 -1
  94. package/dist/payload.mjs +25 -244
  95. package/dist/payload.mjs.map +1 -1
  96. package/dist/portfolio-V347KZOL.mjs +13 -0
  97. package/dist/portfolio-V347KZOL.mjs.map +1 -0
  98. package/dist/queries/index.js +145 -12
  99. package/dist/queries/index.js.map +1 -1
  100. package/dist/queries/index.mjs +14 -1496
  101. package/dist/queries/index.mjs.map +1 -1
  102. package/dist/{types-FJL7j6gQ.d.ts → types-B7V5VNbO.d.mts} +6 -2
  103. package/dist/{types-ChIsqCiw.d.mts → types-DP2CQT8p.d.mts} +12 -1
  104. package/dist/types.d.mts +16 -0
  105. package/dist/types.js.map +1 -1
  106. package/dist/utils.js +25 -11
  107. package/dist/utils.js.map +1 -1
  108. package/dist/utils.mjs +19 -371
  109. package/dist/utils.mjs.map +1 -1
  110. package/dist/wormhole.js.map +1 -1
  111. package/dist/wormhole.mjs +25 -397
  112. package/dist/wormhole.mjs.map +1 -1
  113. package/package.json +28 -3
  114. package/scripts/patch-noble-curves.js +78 -0
  115. package/dist/chains/aptos/index.d.ts +0 -145
  116. package/dist/chains/evm/index.d.ts +0 -5
  117. package/dist/chains/solana/index.d.ts +0 -116
  118. package/dist/chains/starknet/index.d.ts +0 -172
  119. package/dist/chains/sui/index.d.ts +0 -182
  120. package/dist/constants.d.ts +0 -150
  121. package/dist/index-0NXfbk0z.d.ts +0 -637
  122. package/dist/index-D0dLVjTA.d.mts +0 -637
  123. package/dist/index.d.ts +0 -3123
  124. package/dist/payload.d.ts +0 -125
  125. package/dist/queries/index.d.ts +0 -148
  126. package/dist/types-ChIsqCiw.d.ts +0 -565
  127. package/dist/types-FJL7j6gQ.d.mts +0 -172
  128. package/dist/types.d.ts +0 -407
  129. package/dist/utils.d.ts +0 -81
  130. package/dist/wormhole.d.ts +0 -167
@@ -0,0 +1,829 @@
1
+ import {
2
+ base64URLDecode,
3
+ base64URLEncode,
4
+ computeKeyHash,
5
+ parseDERSignature
6
+ } from "./chunk-NUWSMJFJ.mjs";
7
+
8
+ // src/core/PasskeyManager.ts
9
+ import {
10
+ startRegistration,
11
+ startAuthentication,
12
+ browserSupportsWebAuthn
13
+ } from "@simplewebauthn/browser";
14
+ import { ethers } from "ethers";
15
+ var VERIDEX_RP_ID = "veridex.network";
16
+ function detectRpId(forceLocal) {
17
+ if (typeof window === "undefined") return "localhost";
18
+ const hostname = window.location.hostname;
19
+ if (hostname === "localhost" || hostname === "127.0.0.1" || /^\d+\.\d+\.\d+\.\d+$/.test(hostname)) {
20
+ return hostname;
21
+ }
22
+ if (forceLocal) {
23
+ const parts = hostname.split(".");
24
+ if (parts.length <= 2) {
25
+ return hostname;
26
+ }
27
+ return parts.slice(-2).join(".");
28
+ }
29
+ return VERIDEX_RP_ID;
30
+ }
31
+ async function supportsRelatedOrigins() {
32
+ if (typeof window === "undefined" || !window.PublicKeyCredential) {
33
+ return false;
34
+ }
35
+ if ("getClientCapabilities" in PublicKeyCredential) {
36
+ try {
37
+ const getCapabilities = PublicKeyCredential.getClientCapabilities;
38
+ const capabilities = await getCapabilities();
39
+ return capabilities?.relatedOrigins === true;
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+ return false;
45
+ }
46
+ var PasskeyManager = class _PasskeyManager {
47
+ config;
48
+ credential = null;
49
+ constructor(config = {}) {
50
+ this.config = {
51
+ rpName: config.rpName ?? "Veridex Protocol",
52
+ rpId: config.rpId ?? detectRpId(),
53
+ timeout: config.timeout ?? 6e4,
54
+ userVerification: config.userVerification ?? "required",
55
+ authenticatorAttachment: config.authenticatorAttachment ?? "platform",
56
+ relayerUrl: config.relayerUrl ?? ""
57
+ };
58
+ }
59
+ static isSupported() {
60
+ return browserSupportsWebAuthn();
61
+ }
62
+ static async isPlatformAuthenticatorAvailable() {
63
+ if (typeof window === "undefined" || !window.PublicKeyCredential) {
64
+ return false;
65
+ }
66
+ return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
67
+ }
68
+ async register(username, displayName) {
69
+ if (!_PasskeyManager.isSupported()) {
70
+ throw new Error("WebAuthn is not supported in this browser");
71
+ }
72
+ const challenge = ethers.randomBytes(32);
73
+ const challengeBase64 = base64URLEncode(challenge);
74
+ const options = {
75
+ challenge: challengeBase64,
76
+ rp: {
77
+ name: this.config.rpName,
78
+ id: this.config.rpId
79
+ },
80
+ user: {
81
+ id: base64URLEncode(ethers.toUtf8Bytes(username)),
82
+ name: username,
83
+ displayName
84
+ },
85
+ pubKeyCredParams: [
86
+ { alg: -7, type: "public-key" },
87
+ // ES256 (P-256) - WebAuthn default
88
+ { alg: -257, type: "public-key" },
89
+ // RS256 - Widely supported
90
+ { alg: -8, type: "public-key" },
91
+ // EdDSA - Modern, efficient
92
+ { alg: -35, type: "public-key" },
93
+ // ES384 (P-384)
94
+ { alg: -36, type: "public-key" },
95
+ // ES512 (P-521)
96
+ { alg: -37, type: "public-key" }
97
+ // PS256 - RSA PSS
98
+ ],
99
+ authenticatorSelection: {
100
+ authenticatorAttachment: this.config.authenticatorAttachment,
101
+ userVerification: this.config.userVerification,
102
+ residentKey: "required",
103
+ requireResidentKey: true
104
+ },
105
+ timeout: this.config.timeout,
106
+ attestation: "none"
107
+ };
108
+ const response = await startRegistration(options);
109
+ const publicKey = this.extractPublicKeyFromAttestation(response);
110
+ const keyHash = computeKeyHash(publicKey.x, publicKey.y);
111
+ this.credential = {
112
+ credentialId: response.id,
113
+ publicKeyX: publicKey.x,
114
+ publicKeyY: publicKey.y,
115
+ keyHash
116
+ };
117
+ return this.credential;
118
+ }
119
+ async sign(challenge) {
120
+ if (!this.credential) {
121
+ throw new Error("No credential set. Call register() or setCredential() first.");
122
+ }
123
+ const challengeBase64 = base64URLEncode(challenge);
124
+ const options = {
125
+ challenge: challengeBase64,
126
+ rpId: this.config.rpId,
127
+ allowCredentials: [
128
+ {
129
+ id: this.credential.credentialId,
130
+ type: "public-key",
131
+ transports: ["internal"]
132
+ }
133
+ ],
134
+ userVerification: this.config.userVerification,
135
+ timeout: this.config.timeout
136
+ };
137
+ const response = await startAuthentication(options);
138
+ return this.parseAuthenticationResponse(response);
139
+ }
140
+ /**
141
+ * Authenticate using a discoverable credential (passkey)
142
+ * This allows sign-in without knowing the credential ID ahead of time.
143
+ * The authenticator will show all available passkeys for this RP.
144
+ *
145
+ * @param challenge - Optional challenge bytes. If not provided, a random challenge is used.
146
+ * @returns The credential that was used to authenticate, along with the signature
147
+ */
148
+ async authenticate(challenge) {
149
+ if (!_PasskeyManager.isSupported()) {
150
+ throw new Error("WebAuthn is not supported in this browser");
151
+ }
152
+ const actualChallenge = challenge ?? ethers.randomBytes(32);
153
+ const challengeBase64 = base64URLEncode(actualChallenge);
154
+ const options = {
155
+ challenge: challengeBase64,
156
+ rpId: this.config.rpId,
157
+ userVerification: this.config.userVerification,
158
+ timeout: this.config.timeout
159
+ };
160
+ const response = await startAuthentication(options);
161
+ const credentialId = response.id;
162
+ const signature = this.parseAuthenticationResponse(response);
163
+ let storedCredential = this.findCredentialById(credentialId);
164
+ if (storedCredential) {
165
+ this.credential = storedCredential;
166
+ return { credential: storedCredential, signature };
167
+ }
168
+ if (this.config.relayerUrl) {
169
+ storedCredential = await this.loadCredentialFromRelayer(credentialId);
170
+ if (storedCredential) {
171
+ this.credential = storedCredential;
172
+ this.addCredentialToStorage(storedCredential);
173
+ return { credential: storedCredential, signature };
174
+ }
175
+ }
176
+ const hasRelayer = !!this.config.relayerUrl;
177
+ throw new Error(
178
+ "Credential not found. This passkey was registered on a different device or the data was cleared. " + (hasRelayer ? "The credential was not found. Please register a new passkey." : "Please register a new passkey or ensure the relayer URL is configured.")
179
+ );
180
+ }
181
+ /**
182
+ * Find a credential by ID in the list of stored credentials
183
+ */
184
+ findCredentialById(credentialId) {
185
+ if (typeof window === "undefined") return null;
186
+ const stored = this.getAllStoredCredentials();
187
+ return stored.find((c) => c.credentialId === credentialId) || null;
188
+ }
189
+ /**
190
+ * Get all credentials stored in localStorage
191
+ */
192
+ getAllStoredCredentials(key = "veridex_credentials") {
193
+ if (typeof window === "undefined") return [];
194
+ const stored = localStorage.getItem(key);
195
+ if (!stored) {
196
+ const legacy = localStorage.getItem("veridex_credential");
197
+ if (legacy) {
198
+ try {
199
+ const data = JSON.parse(legacy);
200
+ const cred = this.parseStoredCredential(data);
201
+ if (cred) {
202
+ this.saveCredentials([cred], key);
203
+ localStorage.removeItem("veridex_credential");
204
+ return [cred];
205
+ }
206
+ } catch (e) {
207
+ }
208
+ }
209
+ return [];
210
+ }
211
+ try {
212
+ const data = JSON.parse(stored);
213
+ if (Array.isArray(data)) {
214
+ return data.map((item) => this.parseStoredCredential(item)).filter((c) => c !== null);
215
+ }
216
+ return [];
217
+ } catch (error) {
218
+ console.error("Failed to load credentials:", error);
219
+ return [];
220
+ }
221
+ }
222
+ parseStoredCredential(data) {
223
+ try {
224
+ return {
225
+ credentialId: data.credentialId,
226
+ publicKeyX: BigInt(data.publicKeyX),
227
+ publicKeyY: BigInt(data.publicKeyY),
228
+ keyHash: data.keyHash
229
+ };
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+ /**
235
+ * Save a list of credentials to localStorage
236
+ */
237
+ saveCredentials(credentials, key = "veridex_credentials") {
238
+ if (typeof window === "undefined") return;
239
+ const data = credentials.map((c) => ({
240
+ credentialId: c.credentialId,
241
+ publicKeyX: c.publicKeyX.toString(),
242
+ publicKeyY: c.publicKeyY.toString(),
243
+ keyHash: c.keyHash
244
+ }));
245
+ localStorage.setItem(key, JSON.stringify(data));
246
+ }
247
+ /**
248
+ * Add a single credential to storage (append or update)
249
+ */
250
+ addCredentialToStorage(credential, key = "veridex_credentials") {
251
+ const stored = this.getAllStoredCredentials(key);
252
+ const existingIndex = stored.findIndex((c) => c.credentialId === credential.credentialId);
253
+ if (existingIndex >= 0) {
254
+ stored[existingIndex] = credential;
255
+ } else {
256
+ stored.push(credential);
257
+ }
258
+ this.saveCredentials(stored, key);
259
+ }
260
+ /**
261
+ * Check if there's ANY stored credential for this RP
262
+ */
263
+ hasStoredCredential() {
264
+ return this.getAllStoredCredentials().length > 0;
265
+ }
266
+ getCredential() {
267
+ return this.credential;
268
+ }
269
+ setCredential(credential) {
270
+ this.credential = credential;
271
+ }
272
+ createCredentialFromPublicKey(credentialId, publicKeyX, publicKeyY) {
273
+ const keyHash = computeKeyHash(publicKeyX, publicKeyY);
274
+ this.credential = {
275
+ credentialId,
276
+ publicKeyX,
277
+ publicKeyY,
278
+ keyHash
279
+ };
280
+ return this.credential;
281
+ }
282
+ clearCredential() {
283
+ this.credential = null;
284
+ }
285
+ /**
286
+ * Save the current credential to localStorage (appends to list)
287
+ */
288
+ saveToLocalStorage(key = "veridex_credentials") {
289
+ if (!this.credential) {
290
+ throw new Error("No credential to save");
291
+ }
292
+ this.addCredentialToStorage(this.credential, key);
293
+ }
294
+ loadFromLocalStorage(key = "veridex_credentials") {
295
+ if (typeof window === "undefined") {
296
+ return null;
297
+ }
298
+ const stored = this.getAllStoredCredentials(key);
299
+ if (stored.length > 0) {
300
+ this.credential = stored[stored.length - 1];
301
+ return this.credential;
302
+ }
303
+ return null;
304
+ }
305
+ removeFromLocalStorage(key = "veridex_credentials") {
306
+ if (typeof window !== "undefined") {
307
+ localStorage.removeItem(key);
308
+ localStorage.removeItem("veridex_credential");
309
+ }
310
+ }
311
+ // =========================================================================
312
+ // Relayer-based Credential Storage (Cross-Device Recovery)
313
+ // =========================================================================
314
+ /**
315
+ * Save the current credential to the relayer for cross-device recovery.
316
+ * This should be called after registration.
317
+ */
318
+ async saveCredentialToRelayer() {
319
+ if (!this.credential) {
320
+ throw new Error("No credential to save");
321
+ }
322
+ if (!this.config.relayerUrl) {
323
+ console.warn("Relayer URL not configured; skipping remote credential storage");
324
+ return false;
325
+ }
326
+ try {
327
+ const response = await fetch(`${this.config.relayerUrl}/api/v1/credential`, {
328
+ method: "POST",
329
+ headers: { "Content-Type": "application/json" },
330
+ body: JSON.stringify({
331
+ keyHash: this.credential.keyHash,
332
+ credentialId: this.credential.credentialId,
333
+ publicKeyX: this.credential.publicKeyX.toString(),
334
+ publicKeyY: this.credential.publicKeyY.toString()
335
+ })
336
+ });
337
+ if (!response.ok) {
338
+ const errorData = await response.json().catch(() => ({}));
339
+ console.error("Failed to save credential to relayer:", errorData);
340
+ return false;
341
+ }
342
+ console.log("Credential saved to relayer for cross-device recovery");
343
+ return true;
344
+ } catch (error) {
345
+ console.error("Failed to save credential to relayer:", error);
346
+ return false;
347
+ }
348
+ }
349
+ /**
350
+ * Load a credential from the relayer by credential ID.
351
+ * Used during discoverable credential authentication when localStorage is empty.
352
+ */
353
+ async loadCredentialFromRelayer(credentialId) {
354
+ if (!this.config.relayerUrl) {
355
+ return null;
356
+ }
357
+ try {
358
+ const response = await fetch(
359
+ `${this.config.relayerUrl}/api/v1/credential/by-id/${encodeURIComponent(credentialId)}`
360
+ );
361
+ if (!response.ok) {
362
+ return null;
363
+ }
364
+ const data = await response.json();
365
+ if (!data.exists) {
366
+ return null;
367
+ }
368
+ if (!data.credentialId || !data.publicKeyX || !data.publicKeyY || !data.keyHash) {
369
+ console.warn("Relayer returned incomplete credential data:", {
370
+ hasCredentialId: !!data.credentialId,
371
+ hasPublicKeyX: !!data.publicKeyX,
372
+ hasPublicKeyY: !!data.publicKeyY,
373
+ hasKeyHash: !!data.keyHash
374
+ });
375
+ return null;
376
+ }
377
+ return {
378
+ credentialId: data.credentialId,
379
+ publicKeyX: BigInt(data.publicKeyX),
380
+ publicKeyY: BigInt(data.publicKeyY),
381
+ keyHash: data.keyHash
382
+ };
383
+ } catch (error) {
384
+ console.error("Failed to load credential from relayer:", error);
385
+ return null;
386
+ }
387
+ }
388
+ /**
389
+ * Load a credential from the relayer by keyHash.
390
+ * Useful when you know the user's keyHash but not their credential ID.
391
+ */
392
+ async loadCredentialFromRelayerByKeyHash(keyHash) {
393
+ if (!this.config.relayerUrl) {
394
+ return null;
395
+ }
396
+ try {
397
+ const response = await fetch(
398
+ `${this.config.relayerUrl}/api/v1/credential/${encodeURIComponent(keyHash)}`
399
+ );
400
+ if (!response.ok) {
401
+ return null;
402
+ }
403
+ const data = await response.json();
404
+ if (!data.exists) {
405
+ return null;
406
+ }
407
+ if (!data.credentialId || !data.publicKeyX || !data.publicKeyY || !data.keyHash) {
408
+ console.warn("Relayer returned incomplete credential data for keyHash:", {
409
+ hasCredentialId: !!data.credentialId,
410
+ hasPublicKeyX: !!data.publicKeyX,
411
+ hasPublicKeyY: !!data.publicKeyY,
412
+ hasKeyHash: !!data.keyHash
413
+ });
414
+ return null;
415
+ }
416
+ return {
417
+ credentialId: data.credentialId,
418
+ publicKeyX: BigInt(data.publicKeyX),
419
+ publicKeyY: BigInt(data.publicKeyY),
420
+ keyHash: data.keyHash
421
+ };
422
+ } catch (error) {
423
+ console.error("Failed to load credential from relayer:", error);
424
+ return null;
425
+ }
426
+ }
427
+ // =========================================================================
428
+ // Backup Passkey & Device Migration (Phase 3)
429
+ // =========================================================================
430
+ /**
431
+ * Register a backup passkey for the current identity.
432
+ *
433
+ * This creates a new WebAuthn credential on this device/platform that becomes
434
+ * an additional authorized key for the same Veridex identity. The caller
435
+ * must submit the returned credential to VeridexHub.addKey() for on-chain registration.
436
+ *
437
+ * Use cases:
438
+ * - "Add this device" flow when signing in on a new machine
439
+ * - Proactive backup creation on a separate authenticator
440
+ * - Cross-ecosystem redundancy (iCloud + Google Password Manager)
441
+ *
442
+ * @param username - Username for the new credential (typically same as primary)
443
+ * @param displayName - Display name for the backup (e.g., "MacBook Pro Backup")
444
+ * @param excludeCredentialIds - Credential IDs to exclude (prevents re-registering same authenticator)
445
+ * @returns The newly registered backup credential
446
+ */
447
+ async registerBackupPasskey(username, displayName, excludeCredentialIds) {
448
+ if (!_PasskeyManager.isSupported()) {
449
+ throw new Error("WebAuthn is not supported in this browser");
450
+ }
451
+ const challenge = ethers.randomBytes(32);
452
+ const challengeBase64 = base64URLEncode(challenge);
453
+ const excludeList = excludeCredentialIds ?? this.getAllStoredCredentials().map((c) => c.credentialId);
454
+ const options = {
455
+ challenge: challengeBase64,
456
+ rp: {
457
+ name: this.config.rpName,
458
+ id: this.config.rpId
459
+ },
460
+ user: {
461
+ id: base64URLEncode(ethers.toUtf8Bytes(username)),
462
+ name: username,
463
+ displayName
464
+ },
465
+ pubKeyCredParams: [
466
+ { alg: -7, type: "public-key" },
467
+ // ES256 (P-256)
468
+ { alg: -257, type: "public-key" },
469
+ // RS256
470
+ { alg: -8, type: "public-key" }
471
+ // EdDSA
472
+ ],
473
+ excludeCredentials: excludeList.map((id) => ({
474
+ id,
475
+ type: "public-key",
476
+ transports: ["internal", "hybrid"]
477
+ })),
478
+ authenticatorSelection: {
479
+ // Allow cross-platform for backup on security keys
480
+ userVerification: this.config.userVerification,
481
+ residentKey: "required",
482
+ requireResidentKey: true
483
+ },
484
+ timeout: this.config.timeout,
485
+ attestation: "none"
486
+ };
487
+ const response = await startRegistration(options);
488
+ const publicKey = this.extractPublicKeyFromAttestation(response);
489
+ const keyHash = computeKeyHash(publicKey.x, publicKey.y);
490
+ const backupCredential = {
491
+ credentialId: response.id,
492
+ publicKeyX: publicKey.x,
493
+ publicKeyY: publicKey.y,
494
+ keyHash
495
+ };
496
+ this.addCredentialToStorage(backupCredential);
497
+ return backupCredential;
498
+ }
499
+ /**
500
+ * Get registration info for backup state from a registration response.
501
+ *
502
+ * This extracts the backup eligibility (BE) and backup state (BS) flags
503
+ * from the authenticator data, which indicate whether the credential
504
+ * is eligible for cloud sync and whether it is currently synced.
505
+ *
506
+ * @param authenticatorData - Hex-encoded authenticator data from registration
507
+ * @returns Backup flags, or null if not determinable
508
+ */
509
+ static parseBackupFlags(authenticatorData) {
510
+ try {
511
+ const data = ethers.getBytes(authenticatorData);
512
+ if (data.length < 37) return null;
513
+ const flags = data[32];
514
+ return {
515
+ backupEligible: (flags & 8) !== 0,
516
+ backupState: (flags & 16) !== 0
517
+ };
518
+ } catch {
519
+ return null;
520
+ }
521
+ }
522
+ /**
523
+ * Get the number of credentials stored locally.
524
+ */
525
+ getStoredCredentialCount() {
526
+ return this.getAllStoredCredentials().length;
527
+ }
528
+ /**
529
+ * Get all credential IDs stored locally (for exclude lists).
530
+ */
531
+ getStoredCredentialIds() {
532
+ return this.getAllStoredCredentials().map((c) => c.credentialId);
533
+ }
534
+ extractPublicKeyFromAttestation(response) {
535
+ const attestationObject = base64URLDecode(response.response.attestationObject);
536
+ let offset = 0;
537
+ if (attestationObject[offset] >= 160 && attestationObject[offset] <= 191) {
538
+ offset++;
539
+ }
540
+ while (offset < attestationObject.length - 37) {
541
+ if (attestationObject[offset] === 104 && // text string, 8 bytes
542
+ attestationObject[offset + 1] === 97 && // 'a'
543
+ attestationObject[offset + 2] === 117 && // 'u'
544
+ attestationObject[offset + 3] === 116 && // 't'
545
+ attestationObject[offset + 4] === 104 && // 'h'
546
+ attestationObject[offset + 5] === 68 && // 'D'
547
+ attestationObject[offset + 6] === 97 && // 'a'
548
+ attestationObject[offset + 7] === 116 && // 't'
549
+ attestationObject[offset + 8] === 97) {
550
+ offset += 9;
551
+ break;
552
+ }
553
+ offset++;
554
+ }
555
+ if (attestationObject[offset] === 88 || attestationObject[offset] === 89) {
556
+ const lengthBytes = attestationObject[offset] === 88 ? 1 : 2;
557
+ offset += 1 + lengthBytes;
558
+ }
559
+ offset += 32;
560
+ offset += 1;
561
+ offset += 4;
562
+ offset += 16;
563
+ const credIdLen = attestationObject[offset] << 8 | attestationObject[offset + 1];
564
+ offset += 2;
565
+ offset += credIdLen;
566
+ const coseKey = attestationObject.slice(offset);
567
+ console.log("COSE key length:", coseKey.length);
568
+ console.log("COSE key hex:", this.bytesToHex(coseKey.slice(0, Math.min(100, coseKey.length))));
569
+ const { x, y } = this.parseCOSEKey(coseKey);
570
+ return { x, y };
571
+ }
572
+ parseCOSEKey(coseKey) {
573
+ console.log("COSE key length:", coseKey.length);
574
+ console.log("COSE key hex:", this.bytesToHex(coseKey));
575
+ const parsed = this.tryParseCOSEKeyStrategies(coseKey);
576
+ if (parsed) {
577
+ return parsed;
578
+ }
579
+ return this.parseCOSEKeyWithCBORStructure(coseKey);
580
+ }
581
+ tryParseCOSEKeyStrategies(coseKey) {
582
+ const keyBytes = new Uint8Array(coseKey);
583
+ for (let i = 0; i < keyBytes.length - 40; i++) {
584
+ if (keyBytes[i] === 88 && keyBytes[i + 1] === 32) {
585
+ const potentialX = keyBytes.slice(i + 2, i + 34);
586
+ for (let j = i + 34; j < keyBytes.length - 34; j++) {
587
+ if (keyBytes[j] === 88 && keyBytes[j + 1] === 32) {
588
+ const potentialY = keyBytes.slice(j + 2, j + 34);
589
+ if (this.isValidCoordinate(potentialX) && this.isValidCoordinate(potentialY)) {
590
+ console.log("Found coordinates via pattern matching");
591
+ return {
592
+ x: this.bytesToBigInt(potentialX),
593
+ y: this.bytesToBigInt(potentialY)
594
+ };
595
+ }
596
+ }
597
+ }
598
+ }
599
+ }
600
+ return this.tryParseASN1Structure(keyBytes);
601
+ }
602
+ parseCOSEKeyWithCBORStructure(coseKey) {
603
+ const bytes = new Uint8Array(coseKey);
604
+ let xBytes = null;
605
+ let yBytes = null;
606
+ let i = 0;
607
+ while (i < bytes.length) {
608
+ if (bytes[i] === 88) {
609
+ const length = bytes[i + 1];
610
+ if (length === 32) {
611
+ const start = i + 2;
612
+ const end = start + 32;
613
+ if (end <= bytes.length) {
614
+ const coordinate = bytes.slice(start, end);
615
+ if (!xBytes) {
616
+ xBytes = coordinate;
617
+ console.log("Found x at offset", i);
618
+ } else if (!yBytes) {
619
+ yBytes = coordinate;
620
+ console.log("Found y at offset", i);
621
+ break;
622
+ }
623
+ }
624
+ i = end;
625
+ } else {
626
+ i += length + 2;
627
+ }
628
+ } else if (bytes[i] === 66) {
629
+ if (i + 3 < bytes.length) {
630
+ const length = bytes[i + 1] << 8 | bytes[i + 2];
631
+ if (length === 32) {
632
+ const start = i + 3;
633
+ const end = start + 32;
634
+ if (end <= bytes.length) {
635
+ const coordinate = bytes.slice(start, end);
636
+ if (!xBytes) {
637
+ xBytes = coordinate;
638
+ console.log("Found x at offset", i);
639
+ } else if (!yBytes) {
640
+ yBytes = coordinate;
641
+ console.log("Found y at offset", i);
642
+ break;
643
+ }
644
+ }
645
+ i = end;
646
+ } else {
647
+ i += length + 3;
648
+ }
649
+ } else {
650
+ i++;
651
+ }
652
+ } else if (bytes[i] === 64) {
653
+ i++;
654
+ while (i < bytes.length && bytes[i] !== 255) {
655
+ if (bytes[i] === 4 && i + 65 <= bytes.length) {
656
+ const x = bytes.slice(i + 1, i + 33);
657
+ const y = bytes.slice(i + 33, i + 65);
658
+ if (this.isValidCoordinate(x) && this.isValidCoordinate(y)) {
659
+ xBytes = x;
660
+ yBytes = y;
661
+ console.log("Found coordinates in uncompressed point format");
662
+ break;
663
+ }
664
+ }
665
+ i++;
666
+ }
667
+ if (xBytes && yBytes) break;
668
+ } else {
669
+ i++;
670
+ }
671
+ }
672
+ if (!xBytes || !yBytes) {
673
+ const potentialCoords = this.find32ByteSequences(bytes);
674
+ if (potentialCoords.length >= 2) {
675
+ xBytes = potentialCoords[0];
676
+ yBytes = potentialCoords[1];
677
+ console.log("Fallback: Using first two 32-byte sequences as coordinates");
678
+ }
679
+ }
680
+ if (!xBytes || !yBytes) {
681
+ console.error("Failed to find coordinates in COSE key. Full dump:");
682
+ console.error("Hex:", this.bytesToHex(bytes));
683
+ console.error("Structure analysis:");
684
+ this.analyzeCOSEStructure(bytes);
685
+ throw new Error("Failed to extract public key coordinates from COSE key. Check console for details.");
686
+ }
687
+ return {
688
+ x: this.bytesToBigInt(xBytes),
689
+ y: this.bytesToBigInt(yBytes)
690
+ };
691
+ }
692
+ tryParseASN1Structure(bytes) {
693
+ if (bytes[0] === 48) {
694
+ let offset = 2;
695
+ if (bytes[offset] === 3) {
696
+ offset += 2;
697
+ if (bytes[offset] === 48) {
698
+ offset += 2;
699
+ offset += 12;
700
+ if (bytes[offset] === 3 && bytes[offset + 2] === 4) {
701
+ offset += 3;
702
+ const x = bytes.slice(offset, offset + 32);
703
+ const y = bytes.slice(offset + 32, offset + 64);
704
+ if (x.length === 32 && y.length === 32) {
705
+ console.log("Found coordinates via ASN.1 parsing");
706
+ return {
707
+ x: this.bytesToBigInt(x),
708
+ y: this.bytesToBigInt(y)
709
+ };
710
+ }
711
+ }
712
+ }
713
+ }
714
+ }
715
+ return null;
716
+ }
717
+ find32ByteSequences(bytes) {
718
+ const sequences = [];
719
+ for (let i = 0; i <= bytes.length - 32; i++) {
720
+ const sequence = bytes.slice(i, i + 32);
721
+ if (this.isValidCoordinate(sequence)) {
722
+ sequences.push(sequence);
723
+ }
724
+ }
725
+ return sequences;
726
+ }
727
+ isValidCoordinate(bytes) {
728
+ if (bytes.length !== 32) return false;
729
+ let allZeros = true;
730
+ let allOnes = true;
731
+ for (const byte of bytes) {
732
+ if (byte !== 0) allZeros = false;
733
+ if (byte !== 255) allOnes = false;
734
+ }
735
+ return !allZeros && !allOnes;
736
+ }
737
+ bytesToBigInt(bytes) {
738
+ return BigInt("0x" + this.bytesToHex(bytes));
739
+ }
740
+ bytesToHex(bytes) {
741
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
742
+ }
743
+ analyzeCOSEStructure(bytes) {
744
+ console.log("COSE Structure Analysis:");
745
+ console.log("First 20 bytes:", this.bytesToHex(bytes.slice(0, 20)));
746
+ const firstByte = bytes[0];
747
+ console.log("First byte (0x" + firstByte.toString(16) + "):");
748
+ if (firstByte >= 160 && firstByte <= 191) {
749
+ console.log("- Definite length map with", firstByte & 31, "pairs");
750
+ } else if (firstByte === 191) {
751
+ console.log("- Indefinite length map");
752
+ } else if (firstByte === 4) {
753
+ console.log("- Byte string");
754
+ } else if (firstByte === 2) {
755
+ console.log("- Negative integer");
756
+ }
757
+ let count32 = 0;
758
+ for (let i = 0; i <= bytes.length - 32; i++) {
759
+ const chunk = bytes.slice(i, i + 32);
760
+ if (this.isValidCoordinate(chunk)) {
761
+ console.log(
762
+ `Found valid 32-byte sequence at offset ${i}:`,
763
+ this.bytesToHex(chunk.slice(0, 8)) + "..."
764
+ );
765
+ count32++;
766
+ }
767
+ }
768
+ console.log(`Total valid 32-byte sequences: ${count32}`);
769
+ console.log("Looking for known markers:");
770
+ const markers = [
771
+ { byte: 4, name: "Uncompressed point marker" },
772
+ { byte: 3, name: "BIT STRING" },
773
+ { byte: 48, name: "SEQUENCE" },
774
+ { byte: 2, name: "INTEGER" },
775
+ { byte: 6, name: "OBJECT IDENTIFIER" },
776
+ { byte: 88, name: "Byte string with length byte" },
777
+ { byte: 66, name: "Byte string with 2-byte length" },
778
+ { byte: 64, name: "Byte string indefinite length" },
779
+ { byte: 160, name: "Map start" },
780
+ { byte: 191, name: "Indefinite map start" }
781
+ ];
782
+ for (const marker of markers) {
783
+ const indices = [];
784
+ for (let i = 0; i < bytes.length; i++) {
785
+ if (bytes[i] === marker.byte) {
786
+ indices.push(i);
787
+ }
788
+ }
789
+ if (indices.length > 0) {
790
+ console.log(` ${marker.name} (0x${marker.byte.toString(16)}) at positions:`, indices.slice(0, 5).join(", "));
791
+ }
792
+ }
793
+ }
794
+ parseAuthenticationResponse(response) {
795
+ const authenticatorData = base64URLDecode(response.response.authenticatorData);
796
+ const clientDataJSON = response.response.clientDataJSON;
797
+ const signature = base64URLDecode(response.response.signature);
798
+ const { r, s } = parseDERSignature(signature);
799
+ const P256_N = BigInt("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
800
+ const P256_N_DIV_2 = BigInt(
801
+ "0x7FFFFFFF800000007FFFFFFFFFFFFFFFDE737D56D38BCF4279DCE5617E3192A8"
802
+ );
803
+ const clientDataStr = new TextDecoder().decode(base64URLDecode(clientDataJSON));
804
+ const challengeIndex = clientDataStr.indexOf('"challenge"');
805
+ const typeIndex = clientDataStr.indexOf('"type"');
806
+ if (challengeIndex === -1 || typeIndex === -1) {
807
+ throw new Error("Invalid clientDataJSON format");
808
+ }
809
+ return {
810
+ authenticatorData: ethers.hexlify(authenticatorData),
811
+ clientDataJSON: clientDataStr,
812
+ challengeIndex,
813
+ typeIndex,
814
+ r: this.bytesToBigInt(r),
815
+ s: (() => {
816
+ const sBig = this.bytesToBigInt(s);
817
+ return sBig > P256_N_DIV_2 ? P256_N - sBig : sBig;
818
+ })()
819
+ };
820
+ }
821
+ };
822
+
823
+ export {
824
+ VERIDEX_RP_ID,
825
+ detectRpId,
826
+ supportsRelatedOrigins,
827
+ PasskeyManager
828
+ };
829
+ //# sourceMappingURL=chunk-YCUJZ6Z7.mjs.map