@thru/passkey 0.2.13 → 0.2.15

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 (71) hide show
  1. package/README.md +73 -90
  2. package/dist/auth.cjs +672 -0
  3. package/dist/auth.cjs.map +1 -0
  4. package/dist/auth.d.cts +60 -0
  5. package/dist/auth.d.ts +60 -0
  6. package/dist/auth.js +422 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/chunk-2JHC7OOH.js +250 -0
  9. package/dist/chunk-2JHC7OOH.js.map +1 -0
  10. package/dist/chunk-75G2FPYW.js +54 -0
  11. package/dist/chunk-75G2FPYW.js.map +1 -0
  12. package/dist/chunk-B5SN7AS7.js +586 -0
  13. package/dist/chunk-B5SN7AS7.js.map +1 -0
  14. package/dist/chunk-LNDWK3FA.js +163 -0
  15. package/dist/chunk-LNDWK3FA.js.map +1 -0
  16. package/dist/index.cjs +27 -94
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +4 -187
  19. package/dist/index.d.ts +4 -187
  20. package/dist/index.js +47 -810
  21. package/dist/index.js.map +1 -1
  22. package/dist/mobile.cjs +301 -0
  23. package/dist/mobile.cjs.map +1 -0
  24. package/dist/mobile.d.cts +49 -0
  25. package/dist/mobile.d.ts +49 -0
  26. package/dist/mobile.js +41 -0
  27. package/dist/mobile.js.map +1 -0
  28. package/dist/popup.cjs +247 -0
  29. package/dist/popup.cjs.map +1 -0
  30. package/dist/popup.d.cts +22 -0
  31. package/dist/popup.d.ts +22 -0
  32. package/dist/popup.js +31 -0
  33. package/dist/popup.js.map +1 -0
  34. package/dist/server.cjs +351 -0
  35. package/dist/server.cjs.map +1 -0
  36. package/dist/server.d.cts +119 -0
  37. package/dist/server.d.ts +119 -0
  38. package/dist/server.js +340 -0
  39. package/dist/server.js.map +1 -0
  40. package/dist/types-_HRzmn-j.d.cts +125 -0
  41. package/dist/types-_HRzmn-j.d.ts +125 -0
  42. package/dist/web.cjs +758 -0
  43. package/dist/web.cjs.map +1 -0
  44. package/dist/web.d.cts +32 -0
  45. package/dist/web.d.ts +32 -0
  46. package/dist/web.js +60 -0
  47. package/dist/web.js.map +1 -0
  48. package/package.json +47 -2
  49. package/src/auth/execute-tx.ts +87 -0
  50. package/src/auth/index.ts +18 -0
  51. package/src/auth/types.ts +56 -0
  52. package/src/auth/use-passkey-auth.ts +428 -0
  53. package/src/index.ts +37 -39
  54. package/src/mobile/errors.ts +31 -0
  55. package/src/mobile/index.ts +33 -0
  56. package/src/mobile/passkey.ts +154 -0
  57. package/src/mobile/storage.ts +115 -0
  58. package/src/mobile/types.ts +24 -0
  59. package/src/popup-entry.ts +33 -0
  60. package/src/popup-service.ts +0 -103
  61. package/src/server/challenge.ts +26 -0
  62. package/src/server/create-wallet.ts +149 -0
  63. package/src/server/handlers.ts +93 -0
  64. package/src/server/index.ts +13 -0
  65. package/src/server/submit.ts +47 -0
  66. package/src/server/types.ts +70 -0
  67. package/src/server/utils.ts +69 -0
  68. package/src/types.ts +1 -0
  69. package/src/web.ts +51 -0
  70. package/tsconfig.json +6 -1
  71. package/tsup.config.ts +9 -1
package/dist/web.cjs ADDED
@@ -0,0 +1,758 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/web.ts
21
+ var web_exports = {};
22
+ __export(web_exports, {
23
+ P256_HALF_N: () => import_passkey_manager3.P256_HALF_N,
24
+ P256_N: () => import_passkey_manager3.P256_N,
25
+ arrayBufferToBase64Url: () => import_passkey_manager4.arrayBufferToBase64Url,
26
+ base64UrlToArrayBuffer: () => import_passkey_manager4.base64UrlToArrayBuffer,
27
+ base64UrlToBytes: () => import_passkey_manager4.base64UrlToBytes,
28
+ bigIntToBytesBE: () => import_passkey_manager3.bigIntToBytesBE,
29
+ bytesEqual: () => import_passkey_manager4.bytesEqual,
30
+ bytesToBase64: () => import_passkey_manager4.bytesToBase64,
31
+ bytesToBase64Url: () => import_passkey_manager4.bytesToBase64Url,
32
+ bytesToBigIntBE: () => import_passkey_manager3.bytesToBigIntBE,
33
+ bytesToHex: () => import_passkey_manager4.bytesToHex,
34
+ compareBytes: () => import_passkey_manager4.compareBytes,
35
+ getCachedPasskeyClientCapabilities: () => getCachedPasskeyClientCapabilities,
36
+ getPasskeyClientCapabilities: () => getPasskeyClientCapabilities,
37
+ hexToBytes: () => import_passkey_manager4.hexToBytes,
38
+ isInIframe: () => isInIframe,
39
+ isWebAuthnSupported: () => isWebAuthnSupported,
40
+ normalizeLowS: () => import_passkey_manager3.normalizeLowS,
41
+ normalizeSignatureComponent: () => import_passkey_manager3.normalizeSignatureComponent,
42
+ parseDerSignature: () => import_passkey_manager3.parseDerSignature,
43
+ preloadPasskeyClientCapabilities: () => preloadPasskeyClientCapabilities,
44
+ registerPasskey: () => registerPasskey,
45
+ shouldUsePasskeyPopup: () => shouldUsePasskeyPopup,
46
+ signWithDiscoverablePasskey: () => signWithDiscoverablePasskey,
47
+ signWithPasskey: () => signWithPasskey,
48
+ signWithStoredPasskey: () => signWithStoredPasskey,
49
+ uniqueAccounts: () => import_passkey_manager4.uniqueAccounts
50
+ });
51
+ module.exports = __toCommonJS(web_exports);
52
+
53
+ // src/register.ts
54
+ var import_passkey_manager = require("@thru/passkey-manager");
55
+
56
+ // src/capabilities.ts
57
+ var DEBUG = typeof process !== "undefined" && process.env?.NEXT_PUBLIC_PASSKEY_DEBUG === "1";
58
+ var cachedClientCapabilities;
59
+ var clientCapabilitiesPromise = null;
60
+ function isWebAuthnSupported() {
61
+ const supported = typeof window !== "undefined" && typeof window.PublicKeyCredential !== "undefined" && typeof navigator.credentials !== "undefined";
62
+ if (DEBUG) {
63
+ console.log("[Passkey] WebAuthn support check:", {
64
+ window: typeof window !== "undefined",
65
+ PublicKeyCredential: typeof window !== "undefined" && typeof window.PublicKeyCredential !== "undefined",
66
+ credentials: typeof window !== "undefined" && typeof navigator !== "undefined" && typeof navigator.credentials !== "undefined",
67
+ supported
68
+ });
69
+ }
70
+ return supported;
71
+ }
72
+ async function fetchPasskeyClientCapabilities() {
73
+ if (typeof window === "undefined" || typeof window.PublicKeyCredential === "undefined") {
74
+ return null;
75
+ }
76
+ const getClientCapabilities = window.PublicKeyCredential.getClientCapabilities;
77
+ if (typeof getClientCapabilities !== "function") {
78
+ return null;
79
+ }
80
+ try {
81
+ const capabilities = await getClientCapabilities.call(window.PublicKeyCredential);
82
+ if (DEBUG) {
83
+ console.log("[Passkey] WebAuthn client capabilities:", capabilities);
84
+ }
85
+ return capabilities ?? null;
86
+ } catch (error) {
87
+ if (DEBUG) {
88
+ console.warn("[Passkey] Failed to read client capabilities:", error);
89
+ }
90
+ return null;
91
+ }
92
+ }
93
+ function preloadPasskeyClientCapabilities() {
94
+ if (cachedClientCapabilities !== void 0 || clientCapabilitiesPromise) {
95
+ return;
96
+ }
97
+ clientCapabilitiesPromise = fetchPasskeyClientCapabilities().then((capabilities) => {
98
+ cachedClientCapabilities = capabilities;
99
+ return capabilities;
100
+ });
101
+ }
102
+ async function getPasskeyClientCapabilities() {
103
+ if (cachedClientCapabilities !== void 0) {
104
+ return cachedClientCapabilities;
105
+ }
106
+ if (!clientCapabilitiesPromise) {
107
+ preloadPasskeyClientCapabilities();
108
+ }
109
+ if (!clientCapabilitiesPromise) {
110
+ cachedClientCapabilities = null;
111
+ return null;
112
+ }
113
+ const capabilities = await clientCapabilitiesPromise;
114
+ cachedClientCapabilities = capabilities;
115
+ return capabilities;
116
+ }
117
+ function getCachedPasskeyClientCapabilities() {
118
+ return cachedClientCapabilities;
119
+ }
120
+ function isInIframe() {
121
+ if (typeof window === "undefined") {
122
+ return false;
123
+ }
124
+ try {
125
+ return window.self !== window.top;
126
+ } catch {
127
+ return true;
128
+ }
129
+ }
130
+ async function shouldUsePasskeyPopup(action) {
131
+ if (!isInIframe()) {
132
+ return false;
133
+ }
134
+ const mode = await getPasskeyPromptMode(action);
135
+ return mode === "popup";
136
+ }
137
+ function getPermissionsPolicyAllowsFeature(feature) {
138
+ if (typeof document === "undefined") {
139
+ return null;
140
+ }
141
+ const policy = document.permissionsPolicy;
142
+ const featurePolicy = document.featurePolicy;
143
+ const allowsFeature = policy?.allowsFeature || featurePolicy?.allowsFeature;
144
+ if (typeof allowsFeature !== "function") {
145
+ return null;
146
+ }
147
+ try {
148
+ return allowsFeature(feature);
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+ function getCachedPromptMode(action) {
154
+ if (!isInIframe()) {
155
+ return "inline";
156
+ }
157
+ if (cachedClientCapabilities === void 0 && !clientCapabilitiesPromise) {
158
+ preloadPasskeyClientCapabilities();
159
+ }
160
+ const feature = action === "create" ? "publickey-credentials-create" : "publickey-credentials-get";
161
+ const policyAllows = getPermissionsPolicyAllowsFeature(feature);
162
+ const capabilities = getCachedPasskeyClientCapabilities();
163
+ const supportsInline = capabilities?.passkeyPlatformAuthenticator === true || capabilities?.userVerifyingPlatformAuthenticator === true;
164
+ if (policyAllows === false) {
165
+ return "popup";
166
+ }
167
+ if (capabilities === void 0) {
168
+ return "unknown";
169
+ }
170
+ if (!supportsInline) {
171
+ return "popup";
172
+ }
173
+ return "inline";
174
+ }
175
+ async function getPasskeyPromptMode(action) {
176
+ if (!isInIframe()) {
177
+ return "inline";
178
+ }
179
+ const feature = action === "create" ? "publickey-credentials-create" : "publickey-credentials-get";
180
+ const policyAllows = getPermissionsPolicyAllowsFeature(feature);
181
+ const capabilities = await getPasskeyClientCapabilities();
182
+ const supportsInline = capabilities?.passkeyPlatformAuthenticator === true || capabilities?.userVerifyingPlatformAuthenticator === true;
183
+ if (DEBUG) {
184
+ console.log("[Passkey] Prompt mode check:", {
185
+ action,
186
+ policyAllows,
187
+ supportsInline,
188
+ capabilities
189
+ });
190
+ }
191
+ if (!supportsInline) {
192
+ return "popup";
193
+ }
194
+ if (policyAllows === false) {
195
+ return "popup";
196
+ }
197
+ return "inline";
198
+ }
199
+ function maybePreopenPopup(action, openPopupFn) {
200
+ const cachedMode = getCachedPromptMode(action);
201
+ if (cachedMode !== "popup") {
202
+ return null;
203
+ }
204
+ try {
205
+ return openPopupFn();
206
+ } catch {
207
+ return null;
208
+ }
209
+ }
210
+ function shouldFallbackToPopup(error) {
211
+ if (!isInIframe()) {
212
+ return false;
213
+ }
214
+ const name = error && typeof error === "object" && "name" in error ? String(error.name) : "";
215
+ const message = error && typeof error === "object" && "message" in error ? String(error.message) : "";
216
+ const normalized = `${name} ${message}`.toLowerCase();
217
+ if (normalized.includes("cancel") || normalized.includes("canceled") || normalized.includes("cancelled") || normalized.includes("user canceled") || normalized.includes("user cancelled") || normalized.includes("aborted")) {
218
+ return false;
219
+ }
220
+ if (normalized.includes("securityerror")) {
221
+ return true;
222
+ }
223
+ if (normalized.includes("notallowederror")) {
224
+ if (normalized.includes("permission") || normalized.includes("policy") || normalized.includes("iframe") || normalized.includes("frame")) {
225
+ return true;
226
+ }
227
+ }
228
+ return false;
229
+ }
230
+
231
+ // src/popup.ts
232
+ var PASSKEY_POPUP_PATH = "/passkey/popup";
233
+ var PASSKEY_POPUP_READY_EVENT = "thru:passkey-popup-ready";
234
+ var PASSKEY_POPUP_REQUEST_EVENT = "thru:passkey-popup-request";
235
+ var PASSKEY_POPUP_RESPONSE_EVENT = "thru:passkey-popup-response";
236
+ var PASSKEY_POPUP_CHANNEL = "thru:passkey-popup-channel";
237
+ var PASSKEY_POPUP_TIMEOUT_MS = 6e4;
238
+ function closePopup(popup) {
239
+ if (popup && !popup.closed) {
240
+ popup.close();
241
+ }
242
+ }
243
+ function openPasskeyPopupWindow() {
244
+ const popupUrl = new URL(PASSKEY_POPUP_PATH, window.location.origin).toString();
245
+ const popup = window.open(
246
+ popupUrl,
247
+ "thru_passkey_popup",
248
+ "popup=yes,width=440,height=640"
249
+ );
250
+ if (!popup) {
251
+ throw new Error("Passkey popup was blocked");
252
+ }
253
+ return popup;
254
+ }
255
+ function createPopupRequestId() {
256
+ const rand = Math.random().toString(36).slice(2, 10);
257
+ return `passkey_${Date.now()}_${rand}`;
258
+ }
259
+ async function requestPasskeyPopup(action, payload, preopenedPopup) {
260
+ if (typeof window === "undefined") {
261
+ throw new Error("Passkey popup is only available in the browser");
262
+ }
263
+ const requestId = createPopupRequestId();
264
+ const targetOrigin = window.location.origin;
265
+ let popup = preopenedPopup ?? null;
266
+ const channel = typeof BroadcastChannel !== "undefined" ? new BroadcastChannel(PASSKEY_POPUP_CHANNEL) : null;
267
+ return new Promise((resolve, reject) => {
268
+ let timeout = null;
269
+ let closePoll = null;
270
+ let requestSent = false;
271
+ const cleanup = () => {
272
+ if (timeout) {
273
+ clearTimeout(timeout);
274
+ timeout = null;
275
+ }
276
+ if (closePoll) {
277
+ clearInterval(closePoll);
278
+ closePoll = null;
279
+ }
280
+ window.removeEventListener("message", handleMessage);
281
+ if (channel) {
282
+ channel.removeEventListener("message", handleChannelMessage);
283
+ channel.close();
284
+ }
285
+ };
286
+ const sendRequest = (viaChannel) => {
287
+ if (requestSent) {
288
+ return;
289
+ }
290
+ requestSent = true;
291
+ const request = {
292
+ type: PASSKEY_POPUP_REQUEST_EVENT,
293
+ requestId,
294
+ action,
295
+ payload
296
+ };
297
+ if (viaChannel) {
298
+ channel?.postMessage(request);
299
+ return;
300
+ }
301
+ popup?.postMessage(request, targetOrigin);
302
+ };
303
+ const handleResponse = (data) => {
304
+ if (data.requestId !== requestId) {
305
+ return;
306
+ }
307
+ cleanup();
308
+ if (popup && !popup.closed) {
309
+ popup.close();
310
+ }
311
+ if (data.success) {
312
+ resolve(data.result);
313
+ } else {
314
+ const err = new Error(data.error?.message || "Passkey popup failed");
315
+ if (data.error?.name) {
316
+ err.name = data.error.name;
317
+ }
318
+ reject(err);
319
+ }
320
+ };
321
+ const handleMessage = (event) => {
322
+ if (event.origin !== targetOrigin) {
323
+ return;
324
+ }
325
+ const data = event.data;
326
+ if (!data || typeof data !== "object") {
327
+ return;
328
+ }
329
+ if (data.type === PASSKEY_POPUP_READY_EVENT) {
330
+ if (popup && event.source !== popup) {
331
+ return;
332
+ }
333
+ sendRequest(false);
334
+ return;
335
+ }
336
+ if (data.type === PASSKEY_POPUP_RESPONSE_EVENT && "requestId" in data) {
337
+ handleResponse(data);
338
+ }
339
+ };
340
+ window.addEventListener("message", handleMessage);
341
+ const handleChannelMessage = (event) => {
342
+ const data = event.data;
343
+ if (!data || typeof data !== "object") {
344
+ return;
345
+ }
346
+ if (data.type === PASSKEY_POPUP_READY_EVENT) {
347
+ sendRequest(true);
348
+ return;
349
+ }
350
+ if (data.type === PASSKEY_POPUP_RESPONSE_EVENT && "requestId" in data) {
351
+ handleResponse(data);
352
+ }
353
+ };
354
+ if (channel) {
355
+ channel.addEventListener("message", handleChannelMessage);
356
+ }
357
+ if (!popup) {
358
+ try {
359
+ popup = openPasskeyPopupWindow();
360
+ } catch (error) {
361
+ cleanup();
362
+ reject(error);
363
+ return;
364
+ }
365
+ }
366
+ timeout = setTimeout(() => {
367
+ cleanup();
368
+ try {
369
+ popup?.close();
370
+ } catch {
371
+ }
372
+ reject(new Error("Passkey popup timed out"));
373
+ }, PASSKEY_POPUP_TIMEOUT_MS);
374
+ closePoll = setInterval(() => {
375
+ if (popup && popup.closed) {
376
+ cleanup();
377
+ reject(new Error("Passkey popup was closed"));
378
+ }
379
+ }, 250);
380
+ });
381
+ }
382
+
383
+ // src/register.ts
384
+ async function registerPasskey(alias, userId, rpId) {
385
+ if (!isWebAuthnSupported()) {
386
+ throw new Error("WebAuthn is not supported in this browser");
387
+ }
388
+ return runWithPromptMode(
389
+ "create",
390
+ () => registerPasskeyInline(alias, userId, rpId),
391
+ (preopenedPopup) => registerPasskeyViaPopup(alias, userId, rpId, preopenedPopup)
392
+ );
393
+ }
394
+ async function runWithPromptMode(action, inlineFn, popupFn) {
395
+ const preopenedPopup = maybePreopenPopup(action, openPasskeyPopupWindow);
396
+ const promptMode = await getPasskeyPromptMode(action);
397
+ if (promptMode === "popup") {
398
+ return popupFn(preopenedPopup);
399
+ }
400
+ closePopup(preopenedPopup);
401
+ try {
402
+ return await inlineFn();
403
+ } catch (error) {
404
+ if (shouldFallbackToPopup(error)) {
405
+ return popupFn();
406
+ }
407
+ throw error;
408
+ }
409
+ }
410
+ async function registerPasskeyInline(alias, userId, rpId) {
411
+ const rpName = "Thru Wallet";
412
+ const userIdBytes = new TextEncoder().encode(userId);
413
+ const userIdBuffer = userIdBytes.slice(0, 64);
414
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
415
+ const createOptions = {
416
+ challenge,
417
+ rp: {
418
+ id: rpId,
419
+ name: rpName
420
+ },
421
+ user: {
422
+ id: userIdBuffer,
423
+ name: alias,
424
+ displayName: alias
425
+ },
426
+ pubKeyCredParams: [
427
+ { type: "public-key", alg: -7 }
428
+ ],
429
+ authenticatorSelection: {
430
+ authenticatorAttachment: "platform",
431
+ userVerification: "required",
432
+ residentKey: "required",
433
+ requireResidentKey: true
434
+ },
435
+ attestation: "none",
436
+ timeout: 6e4
437
+ };
438
+ const credential = await navigator.credentials.create({
439
+ publicKey: createOptions
440
+ });
441
+ if (!credential) {
442
+ throw new Error("Passkey registration was cancelled");
443
+ }
444
+ const response = credential.response;
445
+ const { x, y } = extractP256PublicKey(response);
446
+ return {
447
+ credentialId: (0, import_passkey_manager.arrayBufferToBase64Url)(credential.rawId),
448
+ publicKeyX: (0, import_passkey_manager.bytesToHex)(x),
449
+ publicKeyY: (0, import_passkey_manager.bytesToHex)(y),
450
+ rpId
451
+ };
452
+ }
453
+ async function registerPasskeyViaPopup(alias, userId, rpId, preopenedPopup) {
454
+ const result = await requestPasskeyPopup(
455
+ "create",
456
+ { alias, userId, rpId },
457
+ preopenedPopup
458
+ );
459
+ return result;
460
+ }
461
+ function extractP256PublicKey(response) {
462
+ if (typeof response.getPublicKey === "function") {
463
+ const spkiKey = response.getPublicKey();
464
+ if (spkiKey) {
465
+ return extractFromSpki(new Uint8Array(spkiKey));
466
+ }
467
+ }
468
+ if (typeof response.getAuthenticatorData === "function") {
469
+ const authData = new Uint8Array(response.getAuthenticatorData());
470
+ return extractFromAuthenticatorData(authData);
471
+ }
472
+ throw new Error("Unable to extract public key: browser does not support required WebAuthn methods");
473
+ }
474
+ function extractFromSpki(spki) {
475
+ const pointStart = spki.length - 65;
476
+ if (spki[pointStart] !== 4) {
477
+ throw new Error("Invalid SPKI format: expected uncompressed point");
478
+ }
479
+ const x = spki.slice(pointStart + 1, pointStart + 33);
480
+ const y = spki.slice(pointStart + 33, pointStart + 65);
481
+ if (x.length !== 32 || y.length !== 32) {
482
+ throw new Error("Invalid SPKI format: incorrect coordinate length");
483
+ }
484
+ return { x, y };
485
+ }
486
+ function extractFromAuthenticatorData(authData) {
487
+ const rpIdHashLength = 32;
488
+ const flagsLength = 1;
489
+ const counterLength = 4;
490
+ const offset = rpIdHashLength + flagsLength + counterLength;
491
+ const aaguidLength = 16;
492
+ const credIdLenOffset = offset + aaguidLength;
493
+ const credIdLength = authData[credIdLenOffset] << 8 | authData[credIdLenOffset + 1];
494
+ const coseKeyOffset = credIdLenOffset + 2 + credIdLength;
495
+ const coseKey = authData.slice(coseKeyOffset);
496
+ return extractFromCoseKey(coseKey);
497
+ }
498
+ function extractFromCoseKey(coseKey) {
499
+ const mapStart = coseKey[0];
500
+ if (mapStart !== 165 && mapStart !== 164) {
501
+ throw new Error("Invalid COSE key format");
502
+ }
503
+ let offset = 1;
504
+ let x = null;
505
+ let y = null;
506
+ while (offset < coseKey.length) {
507
+ const key = coseKey[offset++];
508
+ const valueType = coseKey[offset++];
509
+ if (key === 33) {
510
+ const length = valueType & 31;
511
+ x = coseKey.slice(offset, offset + length);
512
+ offset += length;
513
+ continue;
514
+ }
515
+ if (key === 34) {
516
+ const length = valueType & 31;
517
+ y = coseKey.slice(offset, offset + length);
518
+ offset += length;
519
+ continue;
520
+ }
521
+ if (valueType >= 64 && valueType <= 95) {
522
+ const length = valueType & 31;
523
+ offset += length;
524
+ continue;
525
+ }
526
+ if (valueType === 1 || valueType === 2 || valueType === 3) {
527
+ continue;
528
+ }
529
+ if (valueType >= 24 && valueType <= 27) {
530
+ const size = 1 << valueType - 24;
531
+ offset += size;
532
+ continue;
533
+ }
534
+ }
535
+ if (!x || !y) {
536
+ throw new Error("Failed to extract P-256 public key from COSE data");
537
+ }
538
+ if (x.length !== 32 || y.length !== 32) {
539
+ throw new Error("Invalid COSE key: incorrect coordinate length");
540
+ }
541
+ return { x, y };
542
+ }
543
+
544
+ // src/sign.ts
545
+ var import_passkey_manager2 = require("@thru/passkey-manager");
546
+ async function signWithPasskey(credentialId, challenge, rpId) {
547
+ if (!isWebAuthnSupported()) {
548
+ throw new Error("WebAuthn is not supported in this browser");
549
+ }
550
+ return runWithPromptMode2(
551
+ "get",
552
+ () => signWithPasskeyInline(credentialId, challenge, rpId),
553
+ (preopenedPopup) => signWithPasskeyViaPopup(credentialId, challenge, rpId, preopenedPopup)
554
+ );
555
+ }
556
+ async function signWithStoredPasskey(challenge, rpId, preferredPasskey, allPasskeys, context) {
557
+ if (!isWebAuthnSupported()) {
558
+ throw new Error("WebAuthn is not supported in this browser");
559
+ }
560
+ const preopenedPopup = maybePreopenPopup("get", openPasskeyPopupWindow);
561
+ const promptMode = await getPasskeyPromptMode("get");
562
+ const storedPasskey = preferredPasskey;
563
+ const canUsePopup = isInIframe();
564
+ if (promptMode === "popup" || canUsePopup && !storedPasskey) {
565
+ return requestStoredPasskeyPopup(challenge, preopenedPopup, context);
566
+ }
567
+ closePopup(preopenedPopup);
568
+ try {
569
+ if (storedPasskey) {
570
+ const result = await signWithPasskeyInline(
571
+ storedPasskey.credentialId,
572
+ challenge,
573
+ storedPasskey.rpId
574
+ );
575
+ return {
576
+ ...result,
577
+ passkey: storedPasskey
578
+ };
579
+ }
580
+ const discoverable = await signWithDiscoverablePasskey(challenge, rpId);
581
+ const matchingPasskey = allPasskeys.find((p) => p.credentialId === discoverable.credentialId) ?? null;
582
+ const now = (/* @__PURE__ */ new Date()).toISOString();
583
+ const passkey = matchingPasskey ?? {
584
+ credentialId: discoverable.credentialId,
585
+ publicKeyX: "",
586
+ publicKeyY: "",
587
+ rpId: discoverable.rpId,
588
+ createdAt: now,
589
+ lastUsedAt: now
590
+ };
591
+ return {
592
+ signature: discoverable.signature,
593
+ authenticatorData: discoverable.authenticatorData,
594
+ clientDataJSON: discoverable.clientDataJSON,
595
+ signatureR: discoverable.signatureR,
596
+ signatureS: discoverable.signatureS,
597
+ passkey
598
+ };
599
+ } catch (error) {
600
+ if (canUsePopup && shouldFallbackToPopup(error)) {
601
+ return requestStoredPasskeyPopup(challenge, void 0, context);
602
+ }
603
+ throw error;
604
+ }
605
+ }
606
+ async function signWithDiscoverablePasskey(challenge, rpId) {
607
+ if (!isWebAuthnSupported()) {
608
+ throw new Error("WebAuthn is not supported in this browser");
609
+ }
610
+ const resolvedRpId = rpId;
611
+ const result = await signWithPasskeyAssertion(challenge, resolvedRpId);
612
+ return {
613
+ signature: result.signature,
614
+ authenticatorData: result.authenticatorData,
615
+ clientDataJSON: result.clientDataJSON,
616
+ signatureR: result.signatureR,
617
+ signatureS: result.signatureS,
618
+ credentialId: result.credentialId,
619
+ rpId: resolvedRpId
620
+ };
621
+ }
622
+ async function runWithPromptMode2(action, inlineFn, popupFn) {
623
+ const preopenedPopup = maybePreopenPopup(action, openPasskeyPopupWindow);
624
+ const promptMode = await getPasskeyPromptMode(action);
625
+ if (promptMode === "popup") {
626
+ return popupFn(preopenedPopup);
627
+ }
628
+ closePopup(preopenedPopup);
629
+ try {
630
+ return await inlineFn();
631
+ } catch (error) {
632
+ if (shouldFallbackToPopup(error)) {
633
+ return popupFn();
634
+ }
635
+ throw error;
636
+ }
637
+ }
638
+ async function signWithPasskeyInline(credentialId, challenge, rpId) {
639
+ const result = await signWithPasskeyAssertion(challenge, rpId, credentialId);
640
+ return {
641
+ signature: result.signature,
642
+ authenticatorData: result.authenticatorData,
643
+ clientDataJSON: result.clientDataJSON,
644
+ signatureR: result.signatureR,
645
+ signatureS: result.signatureS
646
+ };
647
+ }
648
+ async function signWithPasskeyAssertion(challenge, rpId, credentialId) {
649
+ const challengeBytes = new Uint8Array(challenge);
650
+ const getOptions = {
651
+ challenge: challengeBytes,
652
+ rpId,
653
+ userVerification: "required",
654
+ timeout: 6e4
655
+ };
656
+ if (credentialId) {
657
+ const credentialIdBuffer = (0, import_passkey_manager2.base64UrlToArrayBuffer)(credentialId);
658
+ getOptions.allowCredentials = [
659
+ {
660
+ type: "public-key",
661
+ id: credentialIdBuffer,
662
+ transports: ["internal", "hybrid", "usb", "ble", "nfc"]
663
+ }
664
+ ];
665
+ }
666
+ const assertion = await navigator.credentials.get({
667
+ publicKey: getOptions
668
+ });
669
+ if (!assertion) {
670
+ throw new Error("Passkey authentication was cancelled");
671
+ }
672
+ const response = assertion.response;
673
+ const signature = new Uint8Array(response.signature);
674
+ let { r, s } = (0, import_passkey_manager2.parseDerSignature)(signature);
675
+ s = (0, import_passkey_manager2.normalizeLowS)(s);
676
+ return {
677
+ signature: new Uint8Array([...r, ...s]),
678
+ authenticatorData: new Uint8Array(response.authenticatorData),
679
+ clientDataJSON: new Uint8Array(response.clientDataJSON),
680
+ signatureR: r,
681
+ signatureS: s,
682
+ credentialId: (0, import_passkey_manager2.arrayBufferToBase64Url)(assertion.rawId)
683
+ };
684
+ }
685
+ async function signWithPasskeyViaPopup(credentialId, challenge, rpId, preopenedPopup) {
686
+ const result = await requestPasskeyPopup(
687
+ "get",
688
+ {
689
+ credentialId,
690
+ challengeBase64Url: (0, import_passkey_manager2.bytesToBase64Url)(challenge),
691
+ rpId
692
+ },
693
+ preopenedPopup
694
+ );
695
+ return decodePopupSigningResult(result);
696
+ }
697
+ async function requestStoredPasskeyPopup(challenge, preopenedPopup, context) {
698
+ const result = await requestPasskeyPopup(
699
+ "getStored",
700
+ {
701
+ challengeBase64Url: (0, import_passkey_manager2.bytesToBase64Url)(challenge),
702
+ context
703
+ },
704
+ preopenedPopup
705
+ );
706
+ return decodePopupStoredSigningResult(result);
707
+ }
708
+ function decodePopupSigningResult(result) {
709
+ return {
710
+ signature: (0, import_passkey_manager2.base64UrlToBytes)(result.signatureBase64Url),
711
+ authenticatorData: (0, import_passkey_manager2.base64UrlToBytes)(result.authenticatorDataBase64Url),
712
+ clientDataJSON: (0, import_passkey_manager2.base64UrlToBytes)(result.clientDataJSONBase64Url),
713
+ signatureR: (0, import_passkey_manager2.base64UrlToBytes)(result.signatureRBase64Url),
714
+ signatureS: (0, import_passkey_manager2.base64UrlToBytes)(result.signatureSBase64Url)
715
+ };
716
+ }
717
+ function decodePopupStoredSigningResult(result) {
718
+ return {
719
+ ...decodePopupSigningResult(result),
720
+ passkey: result.passkey,
721
+ accounts: result.accounts
722
+ };
723
+ }
724
+
725
+ // src/web.ts
726
+ var import_passkey_manager3 = require("@thru/passkey-manager");
727
+ var import_passkey_manager4 = require("@thru/passkey-manager");
728
+ // Annotate the CommonJS export names for ESM import in node:
729
+ 0 && (module.exports = {
730
+ P256_HALF_N,
731
+ P256_N,
732
+ arrayBufferToBase64Url,
733
+ base64UrlToArrayBuffer,
734
+ base64UrlToBytes,
735
+ bigIntToBytesBE,
736
+ bytesEqual,
737
+ bytesToBase64,
738
+ bytesToBase64Url,
739
+ bytesToBigIntBE,
740
+ bytesToHex,
741
+ compareBytes,
742
+ getCachedPasskeyClientCapabilities,
743
+ getPasskeyClientCapabilities,
744
+ hexToBytes,
745
+ isInIframe,
746
+ isWebAuthnSupported,
747
+ normalizeLowS,
748
+ normalizeSignatureComponent,
749
+ parseDerSignature,
750
+ preloadPasskeyClientCapabilities,
751
+ registerPasskey,
752
+ shouldUsePasskeyPopup,
753
+ signWithDiscoverablePasskey,
754
+ signWithPasskey,
755
+ signWithStoredPasskey,
756
+ uniqueAccounts
757
+ });
758
+ //# sourceMappingURL=web.cjs.map