@authsignal/browser 1.5.1 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,7 @@ export declare class PasskeyApiClient {
11
11
  authenticationOptions({ token, challengeId, }: {
12
12
  token?: string;
13
13
  } & AuthenticationOptsRequest): Promise<AuthenticationOptsResponse | ErrorResponse>;
14
- addAuthenticator({ token, challengeId, registrationCredential, }: {
14
+ addAuthenticator({ token, challengeId, registrationCredential, conditionalCreate, }: {
15
15
  token: string;
16
16
  } & AddAuthenticatorRequest): Promise<AddAuthenticatorResponse | ErrorResponse>;
17
17
  verify({ token, challengeId, authenticationCredential, deviceId, }: {
@@ -1,4 +1,4 @@
1
- import { AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsJSON, RegistrationResponseJSON } from "@simplewebauthn/types";
1
+ import { AuthenticationResponseJSON, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsJSON, RegistrationResponseJSON } from "@simplewebauthn/browser";
2
2
  import { AddAuthenticatorResponse, ErrorResponse, VerifyResponse } from "./types/passkey";
3
3
  import { ApiClientOptions } from "./types/shared";
4
4
  export declare class SecurityKeyApiClient {
@@ -1,4 +1,4 @@
1
- import { AuthenticationResponseJSON, AuthenticatorAttachment, PublicKeyCredentialCreationOptionsJSON, RegistrationResponseJSON } from "@simplewebauthn/types";
1
+ import { AuthenticationResponseJSON, AuthenticatorAttachment, PublicKeyCredentialCreationOptionsJSON, RegistrationResponseJSON } from "@simplewebauthn/browser";
2
2
  import { Authenticator } from "./shared";
3
3
  export type RegistrationOptsRequest = {
4
4
  username?: string;
@@ -18,6 +18,7 @@ export type AuthenticationOptsResponse = {
18
18
  export type AddAuthenticatorRequest = {
19
19
  challengeId: string;
20
20
  registrationCredential: RegistrationResponseJSON;
21
+ conditionalCreate?: boolean;
21
22
  };
22
23
  export type AddAuthenticatorResponse = {
23
24
  isVerified: boolean;
@@ -1,4 +1,4 @@
1
- import { CredentialDeviceType } from "@simplewebauthn/types";
1
+ import { CredentialDeviceType } from "@simplewebauthn/browser";
2
2
  export type ApiClientOptions = {
3
3
  baseUrl: string;
4
4
  tenantId: string;
package/dist/index.js CHANGED
@@ -139,7 +139,12 @@ function __generator(thisArg, body) {
139
139
  }
140
140
  }
141
141
 
142
- /* [@simplewebauthn/browser@11.0.0] */
142
+ /**
143
+ * Convert the given array buffer into a Base64URL-encoded string. Ideal for converting various
144
+ * credential response ArrayBuffers to string for sending back to the server as JSON.
145
+ *
146
+ * Helper method to compliment `base64URLStringToBuffer`
147
+ */
143
148
  function bufferToBase64URLString(buffer) {
144
149
  const bytes = new Uint8Array(buffer);
145
150
  let str = '';
@@ -150,11 +155,28 @@ function bufferToBase64URLString(buffer) {
150
155
  return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
151
156
  }
152
157
 
158
+ /**
159
+ * Convert from a Base64URL-encoded string to an Array Buffer. Best used when converting a
160
+ * credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or
161
+ * excludeCredentials
162
+ *
163
+ * Helper method to compliment `bufferToBase64URLString`
164
+ */
153
165
  function base64URLStringToBuffer(base64URLString) {
166
+ // Convert from Base64URL to Base64
154
167
  const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');
168
+ /**
169
+ * Pad with '=' until it's a multiple of four
170
+ * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding
171
+ * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding
172
+ * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding
173
+ * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding
174
+ */
155
175
  const padLength = (4 - (base64.length % 4)) % 4;
156
176
  const padded = base64.padEnd(base64.length + padLength, '=');
177
+ // Convert to a binary string
157
178
  const binary = atob(padded);
179
+ // Convert binary string to buffer
158
180
  const buffer = new ArrayBuffer(binary.length);
159
181
  const bytes = new Uint8Array(buffer);
160
182
  for (let i = 0; i < binary.length; i++) {
@@ -163,33 +185,85 @@ function base64URLStringToBuffer(base64URLString) {
163
185
  return buffer;
164
186
  }
165
187
 
188
+ /**
189
+ * Determine if the browser is capable of Webauthn
190
+ */
166
191
  function browserSupportsWebAuthn() {
167
- return (window?.PublicKeyCredential !== undefined &&
168
- typeof window.PublicKeyCredential === 'function');
192
+ return _browserSupportsWebAuthnInternals.stubThis(globalThis?.PublicKeyCredential !== undefined &&
193
+ typeof globalThis.PublicKeyCredential === 'function');
169
194
  }
195
+ /**
196
+ * Make it possible to stub the return value during testing
197
+ * @ignore Don't include this in docs output
198
+ */
199
+ const _browserSupportsWebAuthnInternals = {
200
+ stubThis: (value) => value,
201
+ };
170
202
 
171
203
  function toPublicKeyCredentialDescriptor(descriptor) {
172
204
  const { id } = descriptor;
173
205
  return {
174
206
  ...descriptor,
175
207
  id: base64URLStringToBuffer(id),
208
+ /**
209
+ * `descriptor.transports` is an array of our `AuthenticatorTransportFuture` that includes newer
210
+ * transports that TypeScript's DOM lib is ignorant of. Convince TS that our list of transports
211
+ * are fine to pass to WebAuthn since browsers will recognize the new value.
212
+ */
176
213
  transports: descriptor.transports,
177
214
  };
178
215
  }
179
216
 
217
+ /**
218
+ * A simple test to determine if a hostname is a properly-formatted domain name
219
+ *
220
+ * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain
221
+ *
222
+ * Regex sourced from here:
223
+ * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html
224
+ */
180
225
  function isValidDomain(hostname) {
181
- return (hostname === 'localhost' ||
226
+ return (
227
+ // Consider localhost valid as well since it's okay wrt Secure Contexts
228
+ hostname === 'localhost' ||
182
229
  /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname));
183
230
  }
184
231
 
232
+ /**
233
+ * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented
234
+ * errors in the spec was raised after calling `navigator.credentials.create()` or
235
+ * `navigator.credentials.get()`:
236
+ *
237
+ * - `AbortError`
238
+ * - `ConstraintError`
239
+ * - `InvalidStateError`
240
+ * - `NotAllowedError`
241
+ * - `NotSupportedError`
242
+ * - `SecurityError`
243
+ * - `TypeError`
244
+ * - `UnknownError`
245
+ *
246
+ * Error messages were determined through investigation of the spec to determine under which
247
+ * scenarios a given error would be raised.
248
+ */
185
249
  class WebAuthnError extends Error {
186
250
  constructor({ message, code, cause, name, }) {
251
+ // @ts-ignore: help Rollup understand that `cause` is okay to set
187
252
  super(message, { cause });
253
+ Object.defineProperty(this, "code", {
254
+ enumerable: true,
255
+ configurable: true,
256
+ writable: true,
257
+ value: void 0
258
+ });
188
259
  this.name = name ?? cause.name;
189
260
  this.code = code;
190
261
  }
191
262
  }
192
263
 
264
+ /**
265
+ * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`
266
+ */
193
267
  function identifyRegistrationError({ error, options, }) {
194
268
  const { publicKey } = options;
195
269
  if (!publicKey) {
@@ -197,6 +271,7 @@ function identifyRegistrationError({ error, options, }) {
197
271
  }
198
272
  if (error.name === 'AbortError') {
199
273
  if (options.signal instanceof AbortSignal) {
274
+ // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)
200
275
  return new WebAuthnError({
201
276
  message: 'Registration ceremony was sent an abort signal',
202
277
  code: 'ERROR_CEREMONY_ABORTED',
@@ -206,14 +281,18 @@ function identifyRegistrationError({ error, options, }) {
206
281
  }
207
282
  else if (error.name === 'ConstraintError') {
208
283
  if (publicKey.authenticatorSelection?.requireResidentKey === true) {
284
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)
209
285
  return new WebAuthnError({
210
286
  message: 'Discoverable credentials were required but no available authenticator supported it',
211
287
  code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',
212
288
  cause: error,
213
289
  });
214
290
  }
215
- else if (options.mediation === 'conditional' &&
291
+ else if (
292
+ // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024
293
+ options.mediation === 'conditional' &&
216
294
  publicKey.authenticatorSelection?.userVerification === 'required') {
295
+ // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)
217
296
  return new WebAuthnError({
218
297
  message: 'User verification was required during automatic registration but it could not be performed',
219
298
  code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',
@@ -221,6 +300,7 @@ function identifyRegistrationError({ error, options, }) {
221
300
  });
222
301
  }
223
302
  else if (publicKey.authenticatorSelection?.userVerification === 'required') {
303
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)
224
304
  return new WebAuthnError({
225
305
  message: 'User verification was required but no available authenticator supported it',
226
306
  code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',
@@ -229,6 +309,8 @@ function identifyRegistrationError({ error, options, }) {
229
309
  }
230
310
  }
231
311
  else if (error.name === 'InvalidStateError') {
312
+ // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)
313
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)
232
314
  return new WebAuthnError({
233
315
  message: 'The authenticator was previously registered',
234
316
  code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',
@@ -236,6 +318,10 @@ function identifyRegistrationError({ error, options, }) {
236
318
  });
237
319
  }
238
320
  else if (error.name === 'NotAllowedError') {
321
+ /**
322
+ * Pass the error directly through. Platforms are overloading this error beyond what the spec
323
+ * defines and we don't want to overwrite potentially useful error messages.
324
+ */
239
325
  return new WebAuthnError({
240
326
  message: error.message,
241
327
  code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
@@ -245,12 +331,14 @@ function identifyRegistrationError({ error, options, }) {
245
331
  else if (error.name === 'NotSupportedError') {
246
332
  const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');
247
333
  if (validPubKeyCredParams.length === 0) {
334
+ // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)
248
335
  return new WebAuthnError({
249
336
  message: 'No entry in pubKeyCredParams was of type "public-key"',
250
337
  code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',
251
338
  cause: error,
252
339
  });
253
340
  }
341
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)
254
342
  return new WebAuthnError({
255
343
  message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',
256
344
  code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',
@@ -258,15 +346,17 @@ function identifyRegistrationError({ error, options, }) {
258
346
  });
259
347
  }
260
348
  else if (error.name === 'SecurityError') {
261
- const effectiveDomain = window.location.hostname;
349
+ const effectiveDomain = globalThis.location.hostname;
262
350
  if (!isValidDomain(effectiveDomain)) {
351
+ // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)
263
352
  return new WebAuthnError({
264
- message: `${window.location.hostname} is an invalid domain`,
353
+ message: `${globalThis.location.hostname} is an invalid domain`,
265
354
  code: 'ERROR_INVALID_DOMAIN',
266
355
  cause: error,
267
356
  });
268
357
  }
269
358
  else if (publicKey.rp.id !== effectiveDomain) {
359
+ // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)
270
360
  return new WebAuthnError({
271
361
  message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`,
272
362
  code: 'ERROR_INVALID_RP_ID',
@@ -276,6 +366,7 @@ function identifyRegistrationError({ error, options, }) {
276
366
  }
277
367
  else if (error.name === 'TypeError') {
278
368
  if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {
369
+ // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)
279
370
  return new WebAuthnError({
280
371
  message: 'User ID was not between 1 and 64 characters',
281
372
  code: 'ERROR_INVALID_USER_ID_LENGTH',
@@ -284,6 +375,8 @@ function identifyRegistrationError({ error, options, }) {
284
375
  }
285
376
  }
286
377
  else if (error.name === 'UnknownError') {
378
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)
379
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)
287
380
  return new WebAuthnError({
288
381
  message: 'The authenticator was unable to process the specified options, or could not create a new credential',
289
382
  code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
@@ -294,7 +387,16 @@ function identifyRegistrationError({ error, options, }) {
294
387
  }
295
388
 
296
389
  class BaseWebAuthnAbortService {
390
+ constructor() {
391
+ Object.defineProperty(this, "controller", {
392
+ enumerable: true,
393
+ configurable: true,
394
+ writable: true,
395
+ value: void 0
396
+ });
397
+ }
297
398
  createNewAbortSignal() {
399
+ // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()
298
400
  if (this.controller) {
299
401
  const abortError = new Error('Cancelling existing WebAuthn API call for new one');
300
402
  abortError.name = 'AbortError';
@@ -313,9 +415,19 @@ class BaseWebAuthnAbortService {
313
415
  }
314
416
  }
315
417
  }
418
+ /**
419
+ * A service singleton to help ensure that only a single WebAuthn ceremony is active at a time.
420
+ *
421
+ * Users of **@simplewebauthn/browser** shouldn't typically need to use this, but it can help e.g.
422
+ * developers building projects that use client-side routing to better control the behavior of
423
+ * their UX in response to router navigation events.
424
+ */
316
425
  const WebAuthnAbortService = new BaseWebAuthnAbortService();
317
426
 
318
427
  const attachments = ['cross-platform', 'platform'];
428
+ /**
429
+ * If possible coerce a `string` value into a known `AuthenticatorAttachment`
430
+ */
319
431
  function toAuthenticatorAttachment(attachment) {
320
432
  if (!attachment) {
321
433
  return;
@@ -326,11 +438,24 @@ function toAuthenticatorAttachment(attachment) {
326
438
  return attachment;
327
439
  }
328
440
 
441
+ /**
442
+ * Begin authenticator "registration" via WebAuthn attestation
443
+ *
444
+ * @param optionsJSON Output from **@simplewebauthn/server**'s `generateRegistrationOptions()`
445
+ * @param useAutoRegister (Optional) Try to silently create a passkey with the password manager that the user just signed in with. Defaults to `false`.
446
+ */
329
447
  async function startRegistration(options) {
448
+ // @ts-ignore: Intentionally check for old call structure to warn about improper API call
449
+ if (!options.optionsJSON && options.challenge) {
450
+ console.warn('startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');
451
+ // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable
452
+ options = { optionsJSON: options };
453
+ }
330
454
  const { optionsJSON, useAutoRegister = false } = options;
331
455
  if (!browserSupportsWebAuthn()) {
332
456
  throw new Error('WebAuthn is not supported in this browser');
333
457
  }
458
+ // We need to convert some values to Uint8Arrays before passing the credentials to the navigator
334
459
  const publicKey = {
335
460
  ...optionsJSON,
336
461
  challenge: base64URLStringToBuffer(optionsJSON.challenge),
@@ -340,12 +465,22 @@ async function startRegistration(options) {
340
465
  },
341
466
  excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor),
342
467
  };
468
+ // Prepare options for `.create()`
343
469
  const createOptions = {};
470
+ /**
471
+ * Try to use conditional create to register a passkey for the user with the password manager
472
+ * the user just used to authenticate with. The user won't be shown any prominent UI by the
473
+ * browser.
474
+ */
344
475
  if (useAutoRegister) {
476
+ // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024
345
477
  createOptions.mediation = 'conditional';
346
478
  }
479
+ // Finalize options
347
480
  createOptions.publicKey = publicKey;
481
+ // Set up the ability to cancel this request if the user attempts another
348
482
  createOptions.signal = WebAuthnAbortService.createNewAbortSignal();
483
+ // Wait for the user to complete attestation
349
484
  let credential;
350
485
  try {
351
486
  credential = (await navigator.credentials.create(createOptions));
@@ -357,10 +492,12 @@ async function startRegistration(options) {
357
492
  throw new Error('Registration was not completed');
358
493
  }
359
494
  const { id, rawId, response, type } = credential;
495
+ // Continue to play it safe with `getTransports()` for now, even when L3 types say it's required
360
496
  let transports = undefined;
361
497
  if (typeof response.getTransports === 'function') {
362
498
  transports = response.getTransports();
363
499
  }
500
+ // L3 says this is required, but browser and webview support are still not guaranteed.
364
501
  let responsePublicKeyAlgorithm = undefined;
365
502
  if (typeof response.getPublicKeyAlgorithm === 'function') {
366
503
  try {
@@ -382,6 +519,7 @@ async function startRegistration(options) {
382
519
  warnOnBrokenImplementation('getPublicKey()', error);
383
520
  }
384
521
  }
522
+ // L3 says this is required, but browser and webview support are still not guaranteed.
385
523
  let responseAuthenticatorData;
386
524
  if (typeof response.getAuthenticatorData === 'function') {
387
525
  try {
@@ -407,22 +545,43 @@ async function startRegistration(options) {
407
545
  authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),
408
546
  };
409
547
  }
548
+ /**
549
+ * Visibly warn when we detect an issue related to a passkey provider intercepting WebAuthn API
550
+ * calls
551
+ */
410
552
  function warnOnBrokenImplementation(methodName, cause) {
411
553
  console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\n`, cause);
412
554
  }
413
555
 
556
+ /**
557
+ * Determine if the browser supports conditional UI, so that WebAuthn credentials can
558
+ * be shown to the user in the browser's typical password autofill popup.
559
+ */
414
560
  function browserSupportsWebAuthnAutofill() {
415
561
  if (!browserSupportsWebAuthn()) {
416
- return new Promise((resolve) => resolve(false));
562
+ return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));
417
563
  }
418
- const globalPublicKeyCredential = window
564
+ /**
565
+ * I don't like the `as unknown` here but there's a `declare var PublicKeyCredential` in
566
+ * TS' DOM lib that's making it difficult for me to just go `as PublicKeyCredentialFuture` as I
567
+ * want. I think I'm fine with this for now since it's _supposed_ to be temporary, until TS types
568
+ * have a chance to catch up.
569
+ */
570
+ const globalPublicKeyCredential = globalThis
419
571
  .PublicKeyCredential;
420
- if (globalPublicKeyCredential.isConditionalMediationAvailable === undefined) {
421
- return new Promise((resolve) => resolve(false));
572
+ if (globalPublicKeyCredential?.isConditionalMediationAvailable === undefined) {
573
+ return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));
422
574
  }
423
- return globalPublicKeyCredential.isConditionalMediationAvailable();
575
+ return _browserSupportsWebAuthnAutofillInternals.stubThis(globalPublicKeyCredential.isConditionalMediationAvailable());
424
576
  }
577
+ // Make it possible to stub the return value during testing
578
+ const _browserSupportsWebAuthnAutofillInternals = {
579
+ stubThis: (value) => value,
580
+ };
425
581
 
582
+ /**
583
+ * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`
584
+ */
426
585
  function identifyAuthenticationError({ error, options, }) {
427
586
  const { publicKey } = options;
428
587
  if (!publicKey) {
@@ -430,6 +589,7 @@ function identifyAuthenticationError({ error, options, }) {
430
589
  }
431
590
  if (error.name === 'AbortError') {
432
591
  if (options.signal instanceof AbortSignal) {
592
+ // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)
433
593
  return new WebAuthnError({
434
594
  message: 'Authentication ceremony was sent an abort signal',
435
595
  code: 'ERROR_CEREMONY_ABORTED',
@@ -438,6 +598,10 @@ function identifyAuthenticationError({ error, options, }) {
438
598
  }
439
599
  }
440
600
  else if (error.name === 'NotAllowedError') {
601
+ /**
602
+ * Pass the error directly through. Platforms are overloading this error beyond what the spec
603
+ * defines and we don't want to overwrite potentially useful error messages.
604
+ */
441
605
  return new WebAuthnError({
442
606
  message: error.message,
443
607
  code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
@@ -445,15 +609,17 @@ function identifyAuthenticationError({ error, options, }) {
445
609
  });
446
610
  }
447
611
  else if (error.name === 'SecurityError') {
448
- const effectiveDomain = window.location.hostname;
612
+ const effectiveDomain = globalThis.location.hostname;
449
613
  if (!isValidDomain(effectiveDomain)) {
614
+ // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)
450
615
  return new WebAuthnError({
451
- message: `${window.location.hostname} is an invalid domain`,
616
+ message: `${globalThis.location.hostname} is an invalid domain`,
452
617
  code: 'ERROR_INVALID_DOMAIN',
453
618
  cause: error,
454
619
  });
455
620
  }
456
621
  else if (publicKey.rpId !== effectiveDomain) {
622
+ // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)
457
623
  return new WebAuthnError({
458
624
  message: `The RP ID "${publicKey.rpId}" is invalid for this domain`,
459
625
  code: 'ERROR_INVALID_RP_ID',
@@ -462,6 +628,8 @@ function identifyAuthenticationError({ error, options, }) {
462
628
  }
463
629
  }
464
630
  else if (error.name === 'UnknownError') {
631
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)
632
+ // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)
465
633
  return new WebAuthnError({
466
634
  message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',
467
635
  code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
@@ -471,34 +639,63 @@ function identifyAuthenticationError({ error, options, }) {
471
639
  return error;
472
640
  }
473
641
 
642
+ /**
643
+ * Begin authenticator "login" via WebAuthn assertion
644
+ *
645
+ * @param optionsJSON Output from **@simplewebauthn/server**'s `generateAuthenticationOptions()`
646
+ * @param useBrowserAutofill (Optional) Initialize conditional UI to enable logging in via browser autofill prompts. Defaults to `false`.
647
+ * @param verifyBrowserAutofillInput (Optional) Ensure a suitable `<input>` element is present when `useBrowserAutofill` is `true`. Defaults to `true`.
648
+ */
474
649
  async function startAuthentication(options) {
650
+ // @ts-ignore: Intentionally check for old call structure to warn about improper API call
651
+ if (!options.optionsJSON && options.challenge) {
652
+ console.warn('startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');
653
+ // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable
654
+ options = { optionsJSON: options };
655
+ }
475
656
  const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true, } = options;
476
657
  if (!browserSupportsWebAuthn()) {
477
658
  throw new Error('WebAuthn is not supported in this browser');
478
659
  }
660
+ // We need to avoid passing empty array to avoid blocking retrieval
661
+ // of public key
479
662
  let allowCredentials;
480
663
  if (optionsJSON.allowCredentials?.length !== 0) {
481
664
  allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);
482
665
  }
666
+ // We need to convert some values to Uint8Arrays before passing the credentials to the navigator
483
667
  const publicKey = {
484
668
  ...optionsJSON,
485
669
  challenge: base64URLStringToBuffer(optionsJSON.challenge),
486
670
  allowCredentials,
487
671
  };
672
+ // Prepare options for `.get()`
488
673
  const getOptions = {};
674
+ /**
675
+ * Set up the page to prompt the user to select a credential for authentication via the browser's
676
+ * input autofill mechanism.
677
+ */
489
678
  if (useBrowserAutofill) {
490
679
  if (!(await browserSupportsWebAuthnAutofill())) {
491
680
  throw Error('Browser does not support WebAuthn autofill');
492
681
  }
682
+ // Check for an <input> with "webauthn" in its `autocomplete` attribute
493
683
  const eligibleInputs = document.querySelectorAll("input[autocomplete$='webauthn']");
684
+ // WebAuthn autofill requires at least one valid input
494
685
  if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) {
495
686
  throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');
496
687
  }
688
+ // `CredentialMediationRequirement` doesn't know about "conditional" yet as of
689
+ // typescript@4.6.3
497
690
  getOptions.mediation = 'conditional';
691
+ // Conditional UI requires an empty allow list
498
692
  publicKey.allowCredentials = [];
499
693
  }
694
+ // Finalize options
500
695
  getOptions.publicKey = publicKey;
696
+ // Set up the ability to cancel this request if the user attempts another
501
697
  getOptions.signal = WebAuthnAbortService.createNewAbortSignal();
698
+ // Wait for the user to complete assertion
502
699
  let credential;
503
700
  try {
504
701
  credential = (await navigator.credentials.get(getOptions));
@@ -514,6 +711,7 @@ async function startAuthentication(options) {
514
711
  if (response.userHandle) {
515
712
  userHandle = bufferToBase64URLString(response.userHandle);
516
713
  }
714
+ // Convert values to base64 to make it easier to send back to the server
517
715
  return {
518
716
  id,
519
717
  rawId: bufferToBase64URLString(rawId),
@@ -670,13 +868,14 @@ var PasskeyApiClient = /** @class */ (function () {
670
868
  PasskeyApiClient.prototype.addAuthenticator = function (_a) {
671
869
  return __awaiter(this, arguments, void 0, function (_b) {
672
870
  var body, response, responseJson;
673
- var token = _b.token, challengeId = _b.challengeId, registrationCredential = _b.registrationCredential;
871
+ var token = _b.token, challengeId = _b.challengeId, registrationCredential = _b.registrationCredential, conditionalCreate = _b.conditionalCreate;
674
872
  return __generator(this, function (_c) {
675
873
  switch (_c.label) {
676
874
  case 0:
677
875
  body = {
678
876
  challengeId: challengeId,
679
877
  registrationCredential: registrationCredential,
878
+ conditionalCreate: conditionalCreate,
680
879
  };
681
880
  return [4 /*yield*/, fetch("".concat(this.baseUrl, "/client/user-authenticators/passkey"), {
682
881
  method: "POST",
@@ -821,6 +1020,7 @@ var Passkey = /** @class */ (function () {
821
1020
  challengeId: optionsResponse.challengeId,
822
1021
  registrationCredential: registrationResponse,
823
1022
  token: userToken,
1023
+ conditionalCreate: useAutoRegister,
824
1024
  })];
825
1025
  case 4:
826
1026
  addAuthenticatorResponse = _e.sent();
package/dist/index.min.js CHANGED
@@ -1 +1 @@
1
- var authsignal=function(e){"use strict";let t;const n=new Uint8Array(16);function o(){if(!t&&(t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!t))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(n)}const r=[];for(let e=0;e<256;++e)r.push((e+256).toString(16).slice(1));var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function s(e,t,n){if(i.randomUUID&&!t&&!e)return i.randomUUID();const s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=s[e];return t}return function(e,t=0){return(r[e[t+0]]+r[e[t+1]]+r[e[t+2]]+r[e[t+3]]+"-"+r[e[t+4]]+r[e[t+5]]+"-"+r[e[t+6]]+r[e[t+7]]+"-"+r[e[t+8]]+r[e[t+9]]+"-"+r[e[t+10]]+r[e[t+11]]+r[e[t+12]]+r[e[t+13]]+r[e[t+14]]+r[e[t+15]]).toLowerCase()}(s)}var a=function(){return a=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},a.apply(this,arguments)};function c(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{c(o.next(e))}catch(e){i(e)}}function a(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}function u(e,t){var n,o,r,i,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,o=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(r=s.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){s.label=i[1];break}if(6===i[0]&&s.label<r[1]){s.label=r[1],r=i;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(i);break}r[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],o=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function h(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function l(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,o=t.padEnd(t.length+n,"="),r=atob(o),i=new ArrayBuffer(r.length),s=new Uint8Array(i);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return i}function d(){return void 0!==window?.PublicKeyCredential&&"function"==typeof window.PublicKeyCredential}function p(e){const{id:t}=e;return{...e,id:l(t),transports:e.transports}}function f(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}class y extends Error{constructor({message:e,code:t,cause:n,name:o}){super(e,{cause:n}),this.name=o??n.name,this.code=t}}const m=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},v=["cross-platform","platform"];function w(e){if(e&&!(v.indexOf(e)<0))return e}async function b(e){const{optionsJSON:t,useAutoRegister:n=!1}=e;if(!d())throw new Error("WebAuthn is not supported in this browser");const o={...t,challenge:l(t.challenge),user:{...t.user,id:l(t.user.id)},excludeCredentials:t.excludeCredentials?.map(p)},r={};let i;n&&(r.mediation="conditional"),r.publicKey=o,r.signal=m.createNewAbortSignal();try{i=await navigator.credentials.create(r)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new y({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===n.authenticatorSelection?.requireResidentKey)return new y({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===n.authenticatorSelection?.userVerification)return new y({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===n.authenticatorSelection?.userVerification)return new y({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new y({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new y({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===n.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new y({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new y({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!f(t))return new y({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new y({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new y({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new y({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:r})}if(!i)throw new Error("Registration was not completed");const{id:s,rawId:a,response:c,type:u}=i;let v,b,g,E;if("function"==typeof c.getTransports&&(v=c.getTransports()),"function"==typeof c.getPublicKeyAlgorithm)try{b=c.getPublicKeyAlgorithm()}catch(e){k("getPublicKeyAlgorithm()",e)}if("function"==typeof c.getPublicKey)try{const e=c.getPublicKey();null!==e&&(g=h(e))}catch(e){k("getPublicKey()",e)}if("function"==typeof c.getAuthenticatorData)try{E=h(c.getAuthenticatorData())}catch(e){k("getAuthenticatorData()",e)}return{id:s,rawId:h(a),response:{attestationObject:h(c.attestationObject),clientDataJSON:h(c.clientDataJSON),transports:v,publicKeyAlgorithm:b,publicKey:g,authenticatorData:E},type:u,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:w(i.authenticatorAttachment)}}function k(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}async function g(e){const{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:o=!0}=e;if(!d())throw new Error("WebAuthn is not supported in this browser");let r;0!==t.allowCredentials?.length&&(r=t.allowCredentials?.map(p));const i={...t,challenge:l(t.challenge),allowCredentials:r},s={};if(n){if(!await function(){if(!d())return new Promise((e=>e(!1)));const e=window.PublicKeyCredential;return void 0===e.isConditionalMediationAvailable?new Promise((e=>e(!1))):e.isConditionalMediationAvailable()}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&o)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');s.mediation="conditional",i.allowCredentials=[]}let a;s.publicKey=i,s.signal=m.createNewAbortSignal();try{a=await navigator.credentials.get(s)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new y({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new y({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!f(t))return new y({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new y({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new y({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:s})}if(!a)throw new Error("Authentication was not completed");const{id:c,rawId:u,response:v,type:b}=a;let k;return v.userHandle&&(k=h(v.userHandle)),{id:c,rawId:h(u),response:{authenticatorData:h(v.authenticatorData),clientDataJSON:h(v.clientDataJSON),signature:h(v.signature),userHandle:k},type:b,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:w(a.authenticatorAttachment)}}function E(e){var t=e.name,n=e.value,o=e.expire,r=e.domain,i=e.secure,s=o===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+o;document.cookie=encodeURIComponent(t)+"="+n+"; path=/;"+s+(r?"; domain="+r:"")+(i?"; secure":"")}function T(e){var t,n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}function I(e){var t;if(e&&"object"==typeof e&&"error"in e){var n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}if(e&&"object"==typeof e&&"accessToken"in e&&"string"==typeof e.accessToken){var o=e.accessToken,r=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}(e,["accessToken"]);return{data:a(a({},r),{token:o})}}return{data:e}}function A(e){var t,n;if(e instanceof y&&"ERROR_INVALID_RP_ID"===e.code){var o=(null===(n=null===(t=e.message)||void 0===t?void 0:t.match(/"([^"]*)"/))||void 0===n?void 0:n[1])||"";console.error('[Authsignal] The Relying Party ID "'.concat(o,'" is invalid for this domain.\n To learn more, visit https://docs.authsignal.com/scenarios/passkeys-prebuilt-ui#defining-the-relying-party'))}}function S(e){var t=e.token,n=e.tenantId;return{"Content-Type":"application/json",Authorization:t?"Bearer ".concat(t):"Basic ".concat(window.btoa(encodeURIComponent(n)))}}function R(e){var t=e.response,n=e.onTokenExpired;"error"in t&&"expired_token"===t.errorCode&&n&&n()}e.AuthsignalWindowMessage=void 0,(e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP";var O=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.registrationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.username,i=e.authenticatorAttachment;return u(this,(function(e){switch(e.label){case 0:return t=Boolean(i)?{username:r,authenticatorAttachment:i}:{username:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/registration-options"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.authenticationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.challengeId;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.addAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.challengeId,i=e.registrationCredential;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:r,registrationCredential:i},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.challengeId,i=e.authenticationCredential,s=e.deviceId;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:r,authenticationCredential:i,deviceId:s},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.getPasskeyAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.credentialIds;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey?credentialIds=").concat(n),{method:"GET",headers:S({tenantId:this.tenantId})})];case 1:if(!(t=e.sent()).ok)throw new Error(t.statusText);return[2,t.json()]}}))}))},e.prototype.challenge=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){switch(n.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge"),{method:"POST",headers:S({tenantId:this.tenantId}),body:JSON.stringify({action:e})})];case 1:return[4,n.sent().json()];case 2:return R({response:t=n.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),x=function(){function e(){this.token=null}return e.prototype.handleTokenNotSetError=function(){var e="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(e)),{error:"TOKEN_NOT_SET",errorDescription:e}},e.shared=new e,e}(),_=!1,U=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.anonymousId,r=e.onTokenExpired;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=x.shared,this.api=new O({baseUrl:t,tenantId:n,onTokenExpired:r}),this.anonymousId=o}return e.prototype.signUp=function(e){return c(this,arguments,void 0,(function(e){var t,n,o,r,i,s,c=e.username,h=e.displayName,l=e.token,d=e.authenticatorAttachment,p=void 0===d?"platform":d,f=e.useAutoRegister,y=void 0!==f&&f;return u(this,(function(e){switch(e.label){case 0:return(t=null!=l?l:this.cache.token)?(n={username:c,displayName:h,token:t,authenticatorAttachment:p},[4,this.api.registrationOptions(n)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(o=e.sent()))return[2,T(o)];e.label=2;case 2:return e.trys.push([2,5,,6]),[4,b({optionsJSON:o.options,useAutoRegister:y})];case 3:return r=e.sent(),[4,this.api.addAuthenticator({challengeId:o.challengeId,registrationCredential:r,token:t})];case 4:return"error"in(i=e.sent())?[2,T(i)]:(i.isVerified&&this.storeCredentialAgainstDevice(a(a({},r),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),[2,{data:{token:i.accessToken,userAuthenticator:i.userAuthenticator,registrationResponse:r}}]);case 5:throw s=e.sent(),_=!1,A(s),s;case 6:return[2]}}))}))},e.prototype.signIn=function(e){return c(this,void 0,void 0,(function(){var t,n,o,r,i,s,c,h,l,d,p,f;return u(this,(function(u){switch(u.label){case 0:if((null==e?void 0:e.token)&&e.autofill)throw new Error("autofill is not supported when providing a token");if((null==e?void 0:e.action)&&e.token)throw new Error("action is not supported when providing a token");if(null==e?void 0:e.autofill){if(_)return[2,{}];_=!0}return(null==e?void 0:e.action)?[4,this.api.challenge(e.action)]:[3,2];case 1:return n=u.sent(),[3,3];case 2:n=null,u.label=3;case 3:return(t=n)&&"error"in t?(_=!1,[2,T(t)]):[4,this.api.authenticationOptions({token:null==e?void 0:e.token,challengeId:null==t?void 0:t.challengeId})];case 4:if("error"in(o=u.sent()))return _=!1,[2,T(o)];u.label=5;case 5:return u.trys.push([5,8,,9]),[4,g({optionsJSON:o.options,useBrowserAutofill:null==e?void 0:e.autofill})];case 6:return r=u.sent(),(null==e?void 0:e.onVerificationStarted)&&e.onVerificationStarted(),[4,this.api.verify({challengeId:o.challengeId,authenticationCredential:r,token:null==e?void 0:e.token,deviceId:this.anonymousId})];case 7:return"error"in(i=u.sent())?(_=!1,[2,T(i)]):(i.isVerified&&this.storeCredentialAgainstDevice(a(a({},r),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),s=i.accessToken,c=i.userId,h=i.userAuthenticatorId,l=i.username,d=i.userDisplayName,p=i.isVerified,_=!1,[2,{data:{isVerified:p,token:s,userId:c,userAuthenticatorId:h,username:l,displayName:d,authenticationResponse:r}}]);case 8:throw f=u.sent(),_=!1,A(f),f;case 9:return[2]}}))}))},e.prototype.isAvailableOnDevice=function(e){return c(this,arguments,void 0,(function(e){var t,n,o,r,i=e.userId;return u(this,(function(e){switch(e.label){case 0:if(!i)throw new Error("userId is required");if(!(t=localStorage.getItem(this.passkeyLocalStorageKey)))return[2,!1];if(n=JSON.parse(t),0===(o=null!==(r=n[i])&&void 0!==r?r:[]).length)return[2,!1];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.api.getPasskeyAuthenticator({credentialIds:o})];case 2:return e.sent(),[2,!0];case 3:return e.sent(),[2,!1];case 4:return[2]}}))}))},e.prototype.storeCredentialAgainstDevice=function(e){var t=e.id,n=e.authenticatorAttachment,o=e.userId,r=void 0===o?"":o;if("cross-platform"!==n){var i=localStorage.getItem(this.passkeyLocalStorageKey),s=i?JSON.parse(i):{};s[r]?s[r].includes(t)||s[r].push(t):s[r]=[t],localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(s))}},e}(),N=function(){function e(){this.windowRef=null}return e.prototype.show=function(e){var t=e.url,n=e.width,o=void 0===n?400:n,r=e.height,i=function(e){var t=e.url,n=e.width,o=e.height,r=e.win;if(!r.top)return null;var i=r.top.outerHeight/2+r.top.screenY-o/2,s=r.top.outerWidth/2+r.top.screenX-n/2;return window.open(t,"","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=".concat(n,", height=").concat(o,", top=").concat(i,", left=").concat(s))}({url:t,width:o,height:void 0===r?500:r,win:window});if(!i)throw new Error("Window is not initialized");return this.windowRef=i,i},e.prototype.close=function(){if(!this.windowRef)throw new Error("Window is not initialized");this.windowRef.close()},e}();const C=":not([inert]):not([inert] *)",P=':not([tabindex^="-"])',$=":not(:disabled)";var D=[`a[href]${C}${P}`,`area[href]${C}${P}`,`input:not([type="hidden"]):not([type="radio"])${C}${P}${$}`,`input[type="radio"]${C}${P}${$}`,`select${C}${P}${$}`,`textarea${C}${P}${$}`,`button${C}${P}${$}`,`details${C} > summary:first-of-type${P}`,`iframe${C}${P}`,`audio[controls]${C}${P}`,`video[controls]${C}${P}`,`[contenteditable]${C}${P}`,`[tabindex]${C}${P}`];function L(e){(e.querySelector("[autofocus]")||e).focus()}function j(e,t){if(t&&V(e))return e;if(!((n=e).shadowRoot&&"-1"===n.getAttribute("tabindex")||n.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let n=K(e.shadowRoot,t);for(;n;){const e=j(n,t);if(e)return e;n=J(n,t)}}else if("slot"===e.localName){const n=e.assignedElements({flatten:!0});t||n.reverse();for(const e of n){const n=j(e,t);if(n)return n}}else{let n=K(e,t);for(;n;){const e=j(n,t);if(e)return e;n=J(n,t)}}var n;return!t&&V(e)?e:null}function K(e,t){return t?e.firstElementChild:e.lastElementChild}function J(e,t){return t?e.nextElementSibling:e.previousElementSibling}const V=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(D.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function W(e=document){const t=e.activeElement;return t?t.shadowRoot?W(t.shadowRoot)||document.activeElement:t:null}function M(e,t){const[n,o]=function(e){const t=j(e,!0);return[t,t?j(e,!1)||t:null]}(e);if(!n)return t.preventDefault();const r=W();t.shiftKey&&r===n?(o.focus(),t.preventDefault()):t.shiftKey||r!==o||(n.focus(),t.preventDefault())}class q{$el;id;previouslyFocused;shown;constructor(e){this.$el=e,this.id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this.previouslyFocused=null,this.shown=!1,this.maintainFocus=this.maintainFocus.bind(this),this.bindKeypress=this.bindKeypress.bind(this),this.handleTriggerClicks=this.handleTriggerClicks.bind(this),this.show=this.show.bind(this),this.hide=this.hide.bind(this),this.$el.setAttribute("aria-hidden","true"),this.$el.setAttribute("aria-modal","true"),this.$el.setAttribute("tabindex","-1"),this.$el.hasAttribute("role")||this.$el.setAttribute("role","dialog"),document.addEventListener("click",this.handleTriggerClicks,!0)}destroy(){return this.hide(),document.removeEventListener("click",this.handleTriggerClicks,!0),this.$el.replaceWith(this.$el.cloneNode(!0)),this.fire("destroy"),this}show(e){return this.shown||(this.shown=!0,this.$el.removeAttribute("aria-hidden"),this.previouslyFocused=W(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):L(this.$el),document.body.addEventListener("focus",this.maintainFocus,!0),this.$el.addEventListener("keydown",this.bindKeypress,!0),this.fire("show",e)),this}hide(e){return this.shown?(this.shown=!1,this.$el.setAttribute("aria-hidden","true"),this.previouslyFocused?.focus?.(),document.body.removeEventListener("focus",this.maintainFocus,!0),this.$el.removeEventListener("keydown",this.bindKeypress,!0),this.fire("hide",e),this):this}on(e,t,n){return this.$el.addEventListener(e,t,n),this}off(e,t,n){return this.$el.removeEventListener(e,t,n),this}fire(e,t){this.$el.dispatchEvent(new CustomEvent(e,{detail:t,cancelable:!0}))}handleTriggerClicks(e){const t=e.target;t.closest(`[data-a11y-dialog-show="${this.id}"]`)&&this.show(e),(t.closest(`[data-a11y-dialog-hide="${this.id}"]`)||t.closest("[data-a11y-dialog-hide]")&&t.closest('[aria-modal="true"]')===this.$el)&&this.hide(e)}bindKeypress(e){if(document.activeElement?.closest('[aria-modal="true"]')!==this.$el)return;let t=!1;try{t=!!this.$el.querySelector('[popover]:not([popover="manual"]):popover-open')}catch{}"Escape"!==e.key||"alertdialog"===this.$el.getAttribute("role")||t||(e.preventDefault(),this.hide(e)),"Tab"===e.key&&M(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||L(this.$el)}}function H(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new q(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",H):H());var F="__authsignal-popup-container",G="__authsignal-popup-content",B="__authsignal-popup-overlay",z="__authsignal-popup-style",Y="__authsignal-popup-iframe",X="385px",Q=function(){function e(e){var t=e.width,n=e.isClosable;if(this.popup=null,document.querySelector("#".concat(F)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:t,isClosable:n})}return e.prototype.create=function(e){var t=this,n=e.width,o=void 0===n?X:n,r=e.isClosable,i=void 0===r||r,s=o;CSS.supports("width",o)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),s=X);var a=document.createElement("div");a.setAttribute("id",F),a.setAttribute("aria-hidden","true"),i||a.setAttribute("role","alertdialog");var c=document.createElement("div");c.setAttribute("id",B),i&&c.setAttribute("data-a11y-dialog-hide","true");var u=document.createElement("div");u.setAttribute("id",G),document.body.appendChild(a);var h=document.createElement("style");h.setAttribute("id",z),h.textContent="\n #".concat(F,",\n #").concat(B," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(F," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(F,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(B," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(G," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(s,";\n }\n\n #").concat(G," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: 95vh;\n height: ").concat("384px",";\n }\n "),document.head.insertAdjacentElement("beforeend",h),a.appendChild(c),a.appendChild(u),this.popup=new q(a),a.focus(),this.popup.on("hide",(function(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(F)),t=document.querySelector("#".concat(z));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),window.removeEventListener("message",Z)},e.prototype.show=function(e){var t,n=e.url;if(!this.popup)throw new Error("Popup is not initialized");var o=document.createElement("iframe");o.setAttribute("id",Y),o.setAttribute("name","authsignal"),o.setAttribute("title","Authsignal multi-factor authentication"),o.setAttribute("src",n),o.setAttribute("frameborder","0"),o.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write");var r=document.querySelector("#".concat(G));r&&r.appendChild(o),window.addEventListener("message",Z),null===(t=this.popup)||void 0===t||t.show()},e.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},e.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},e}();function Z(e){var t=document.querySelector("#".concat(Y));t&&e.data.height&&(t.style.height=e.data.height+"px")}var ee=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/totp"),{method:"POST",headers:S({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/totp"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),te=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=x.shared,this.api=new ee({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,I(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,I(t)]}}))}))},e}(),ne=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.email;return u(this,(function(e){switch(e.label){case 0:return t={email:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-otp"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-otp"),{method:"POST",headers:S({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/email-otp"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),oe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=x.shared,this.api=new ne({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.email;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,I(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,I(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,I(t)]}}))}))},e}(),re=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.phoneNumber;return u(this,(function(e){switch(e.label){case 0:return t={phoneNumber:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/sms"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/sms"),{method:"POST",headers:S({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/sms"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ie=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=x.shared,this.api=new re({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.phoneNumber;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,phoneNumber:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,I(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,I(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,I(t)]}}))}))},e}(),se=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.email;return u(this,(function(e){switch(e.label){case 0:return t={email:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-magic-link"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return R({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-magic-link"),{method:"POST",headers:S({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.checkVerificationStatus=function(e){return c(this,arguments,void 0,(function(e){var t,n=this,o=e.token;return u(this,(function(e){switch(e.label){case 0:return t=function(){return c(n,void 0,void 0,(function(){var e,n=this;return u(this,(function(r){switch(r.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/email-magic-link/finalize"),{method:"POST",headers:S({token:o,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,r.sent().json()];case 2:return R({response:e=r.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return c(n,void 0,void 0,(function(){var n;return u(this,(function(o){switch(o.label){case 0:return n=e,[4,t()];case 1:return n.apply(void 0,[o.sent()]),[2]}}))}))}),1e3)}))]}}))}))},[4,t()];case 1:return[2,e.sent()]}}))}))},e}(),ae=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=x.shared,this.api=new se({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.email;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,I(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,I(e.sent())]}}))}))},e.prototype.checkVerificationStatus=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return this.cache.token?[4,this.api.checkVerificationStatus({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(e=t.sent())&&e.accessToken&&(this.cache.token=e.accessToken),[2,I(e)]}}))}))},e}(),ce=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.registrationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/registration-options"),{method:"POST",headers:S({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/authentication-options"),{method:"POST",headers:S({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token,o=e.registrationCredential;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key"),{method:"POST",headers:S({token:n,tenantId:this.tenantId}),body:JSON.stringify(o)})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token,o=e.authenticationCredential;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/security-key"),{method:"POST",headers:S({token:n,tenantId:this.tenantId}),body:JSON.stringify(o)})];case 1:return[4,e.sent().json()];case 2:return R({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),ue=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=x.shared,this.api=new ce({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(){return c(this,void 0,void 0,(function(){var e,t,n,o,r;return u(this,(function(i){switch(i.label){case 0:return this.cache.token?(e={token:this.cache.token},[4,this.api.registrationOptions(e)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(t=i.sent()))return[2,T(t)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,b({optionsJSON:t})];case 3:return n=i.sent(),[4,this.api.addAuthenticator({registrationCredential:n,token:this.cache.token})];case 4:return"error"in(o=i.sent())?[2,T(o)]:(o.accessToken&&(this.cache.token=o.accessToken),[2,{data:{token:o.accessToken,registrationResponse:n}}]);case 5:throw A(r=i.sent()),r;case 6:return[2]}}))}))},e.prototype.verify=function(){return c(this,void 0,void 0,(function(){var e,t,n,o,r;return u(this,(function(i){switch(i.label){case 0:return this.cache.token?[4,this.api.authenticationOptions({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(e=i.sent()))return[2,T(e)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,g({optionsJSON:e})];case 3:return t=i.sent(),[4,this.api.verify({authenticationCredential:t,token:this.cache.token})];case 4:return"error"in(n=i.sent())?[2,T(n)]:(n.accessToken&&(this.cache.token=n.accessToken),o=n.accessToken,[2,{data:{isVerified:n.isVerified,token:o,authenticationResponse:t}}]);case 5:throw A(r=i.sent()),r;case 6:return[2]}}))}))},e}(),he="4a08uqve",le=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,o=void 0===n?"__as_aid":n,r=e.baseUrl,i=void 0===r?"https://api.authsignal.com/v1":r,a=e.tenantId,c=e.onTokenExpired;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=o,!a)throw new Error("tenantId is required");var u,h=(u=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(u).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;h?this.anonymousId=h:(this.anonymousId=s(),E({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.passkey=new U({tenantId:a,baseUrl:i,anonymousId:this.anonymousId,onTokenExpired:c}),this.totp=new te({tenantId:a,baseUrl:i,onTokenExpired:c}),this.email=new oe({tenantId:a,baseUrl:i,onTokenExpired:c}),this.emailML=new ae({tenantId:a,baseUrl:i,onTokenExpired:c}),this.sms=new ie({tenantId:a,baseUrl:i,onTokenExpired:c}),this.securityKey=new ue({tenantId:a,baseUrl:i,onTokenExpired:c})}return t.prototype.setToken=function(e){x.shared.token=e},t.prototype.launch=function(e,t){switch(null==t?void 0:t.mode){case"window":return this.launchWithWindow(e,t);case"popup":return this.launchWithPopup(e,t);default:this.launchWithRedirect(e)}},t.prototype.initAdvancedProfiling=function(e){var t=s();this.profilingId=t,E({name:"__as_pid",value:t,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol});var n=e?"".concat(e,"/fp/tags.js?org_id=").concat(he,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(he,"&session_id=").concat(t),o=document.createElement("script");o.src=n,o.async=!1,o.id="as_adv_profile",document.head.appendChild(o);var r=document.createElement("noscript");r.setAttribute("id","as_adv_profile_pixel"),r.setAttribute("aria-hidden","true");var i=document.createElement("iframe"),a=e?"".concat(e,"/fp/tags?org_id=").concat(he,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(he,"&session_id=").concat(t);i.setAttribute("id","as_adv_profile_pixel"),i.setAttribute("src",a),i.setAttribute("style","width: 100px; height: 100px; border: 0; position: absolute; top: -5000px;"),r&&(r.appendChild(i),document.body.prepend(r))},t.prototype.launchWithRedirect=function(e){window.location.href=e},t.prototype.launchWithPopup=function(t,n){var o=n.popupOptions,r=new Q({width:null==o?void 0:o.width,isClosable:null==o?void 0:o.isClosable}),i="".concat(t,"&mode=popup");return r.show({url:i}),new Promise((function(t){var n=void 0;r.on("hide",(function(){t({token:n})})),window.addEventListener("message",(function(t){var o=null;try{o=JSON.parse(t.data)}catch(e){}(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n=o.token,r.close())}),!1)}))},t.prototype.launchWithWindow=function(t,n){var o=n.windowOptions,r=new N,i="".concat(t,"&mode=popup");return r.show({url:i,width:null==o?void 0:o.width,height:null==o?void 0:o.height}),new Promise((function(t){window.addEventListener("message",(function(n){var o=null;try{o=JSON.parse(n.data)}catch(e){}(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(r.close(),t({token:o.token}))}),!1)}))},t}();return e.Authsignal=le,e.WebAuthnError=y,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
1
+ var authsignal=function(e){"use strict";let t;const n=new Uint8Array(16);function o(){if(!t&&(t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!t))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(n)}const r=[];for(let e=0;e<256;++e)r.push((e+256).toString(16).slice(1));var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function s(e,t,n){if(i.randomUUID&&!t&&!e)return i.randomUUID();const s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=s[e];return t}return function(e,t=0){return(r[e[t+0]]+r[e[t+1]]+r[e[t+2]]+r[e[t+3]]+"-"+r[e[t+4]]+r[e[t+5]]+"-"+r[e[t+6]]+r[e[t+7]]+"-"+r[e[t+8]]+r[e[t+9]]+"-"+r[e[t+10]]+r[e[t+11]]+r[e[t+12]]+r[e[t+13]]+r[e[t+14]]+r[e[t+15]]).toLowerCase()}(s)}var a=function(){return a=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},a.apply(this,arguments)};function c(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{c(o.next(e))}catch(e){i(e)}}function a(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((o=o.apply(e,t||[])).next())}))}function u(e,t){var n,o,r,i,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,o=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(r=s.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){s.label=i[1];break}if(6===i[0]&&s.label<r[1]){s.label=r[1],r=i;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(i);break}r[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],o=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function h(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function l(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,o=t.padEnd(t.length+n,"="),r=atob(o),i=new ArrayBuffer(r.length),s=new Uint8Array(i);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return i}function d(){return p.stubThis(void 0!==globalThis?.PublicKeyCredential&&"function"==typeof globalThis.PublicKeyCredential)}const p={stubThis:e=>e};function f(e){const{id:t}=e;return{...e,id:l(t),transports:e.transports}}function y(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}class m extends Error{constructor({message:e,code:t,cause:n,name:o}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=o??n.name,this.code=t}}const b=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},v=["cross-platform","platform"];function g(e){if(e&&!(v.indexOf(e)<0))return e}async function w(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:t,useAutoRegister:n=!1}=e;if(!d())throw new Error("WebAuthn is not supported in this browser");const o={...t,challenge:l(t.challenge),user:{...t.user,id:l(t.user.id)},excludeCredentials:t.excludeCredentials?.map(f)},r={};let i;n&&(r.mediation="conditional"),r.publicKey=o,r.signal=b.createNewAbortSignal();try{i=await navigator.credentials.create(r)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new m({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===n.authenticatorSelection?.requireResidentKey)return new m({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===n.authenticatorSelection?.userVerification)return new m({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===n.authenticatorSelection?.userVerification)return new m({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new m({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new m({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===n.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new m({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new m({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!y(t))return new m({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new m({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new m({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new m({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:r})}if(!i)throw new Error("Registration was not completed");const{id:s,rawId:a,response:c,type:u}=i;let p,v,w,E;if("function"==typeof c.getTransports&&(p=c.getTransports()),"function"==typeof c.getPublicKeyAlgorithm)try{v=c.getPublicKeyAlgorithm()}catch(e){k("getPublicKeyAlgorithm()",e)}if("function"==typeof c.getPublicKey)try{const e=c.getPublicKey();null!==e&&(w=h(e))}catch(e){k("getPublicKey()",e)}if("function"==typeof c.getAuthenticatorData)try{E=h(c.getAuthenticatorData())}catch(e){k("getAuthenticatorData()",e)}return{id:s,rawId:h(a),response:{attestationObject:h(c.attestationObject),clientDataJSON:h(c.clientDataJSON),transports:p,publicKeyAlgorithm:v,publicKey:w,authenticatorData:E},type:u,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:g(i.authenticatorAttachment)}}function k(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}const E={stubThis:e=>e};async function T(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:o=!0}=e;if(!d())throw new Error("WebAuthn is not supported in this browser");let r;0!==t.allowCredentials?.length&&(r=t.allowCredentials?.map(f));const i={...t,challenge:l(t.challenge),allowCredentials:r},s={};if(n){if(!await function(){if(!d())return E.stubThis(new Promise((e=>e(!1))));const e=globalThis.PublicKeyCredential;return void 0===e?.isConditionalMediationAvailable?E.stubThis(new Promise((e=>e(!1)))):E.stubThis(e.isConditionalMediationAvailable())}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&o)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');s.mediation="conditional",i.allowCredentials=[]}let a;s.publicKey=i,s.signal=b.createNewAbortSignal();try{a=await navigator.credentials.get(s)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new m({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new m({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!y(t))return new m({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new m({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new m({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:s})}if(!a)throw new Error("Authentication was not completed");const{id:c,rawId:u,response:p,type:v}=a;let w;return p.userHandle&&(w=h(p.userHandle)),{id:c,rawId:h(u),response:{authenticatorData:h(p.authenticatorData),clientDataJSON:h(p.clientDataJSON),signature:h(p.signature),userHandle:w},type:v,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:g(a.authenticatorAttachment)}}function I(e){var t=e.name,n=e.value,o=e.expire,r=e.domain,i=e.secure,s=o===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+o;document.cookie=encodeURIComponent(t)+"="+n+"; path=/;"+s+(r?"; domain="+r:"")+(i?"; secure":"")}function A(e){var t,n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}function S(e){var t;if(e&&"object"==typeof e&&"error"in e){var n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}if(e&&"object"==typeof e&&"accessToken"in e&&"string"==typeof e.accessToken){var o=e.accessToken,r=function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}(e,["accessToken"]);return{data:a(a({},r),{token:o})}}return{data:e}}function O(e){var t,n;if(e instanceof m&&"ERROR_INVALID_RP_ID"===e.code){var o=(null===(n=null===(t=e.message)||void 0===t?void 0:t.match(/"([^"]*)"/))||void 0===n?void 0:n[1])||"";console.error('[Authsignal] The Relying Party ID "'.concat(o,'" is invalid for this domain.\n To learn more, visit https://docs.authsignal.com/scenarios/passkeys-prebuilt-ui#defining-the-relying-party'))}}function R(e){var t=e.token,n=e.tenantId;return{"Content-Type":"application/json",Authorization:t?"Bearer ".concat(t):"Basic ".concat(window.btoa(encodeURIComponent(n)))}}function x(e){var t=e.response,n=e.onTokenExpired;"error"in t&&"expired_token"===t.errorCode&&n&&n()}e.AuthsignalWindowMessage=void 0,(e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP";var _=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.registrationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.username,i=e.authenticatorAttachment;return u(this,(function(e){switch(e.label){case 0:return t=Boolean(i)?{username:r,authenticatorAttachment:i}:{username:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/registration-options"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.authenticationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.challengeId;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.addAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.challengeId,i=e.registrationCredential,s=e.conditionalCreate;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:r,registrationCredential:i,conditionalCreate:s},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.challengeId,i=e.authenticationCredential,s=e.deviceId;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:r,authenticationCredential:i,deviceId:s},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.getPasskeyAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.credentialIds;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey?credentialIds=").concat(n),{method:"GET",headers:R({tenantId:this.tenantId})})];case 1:if(!(t=e.sent()).ok)throw new Error(t.statusText);return[2,t.json()]}}))}))},e.prototype.challenge=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){switch(n.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge"),{method:"POST",headers:R({tenantId:this.tenantId}),body:JSON.stringify({action:e})})];case 1:return[4,n.sent().json()];case 2:return x({response:t=n.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),N=function(){function e(){this.token=null}return e.prototype.handleTokenNotSetError=function(){var e="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(e)),{error:"TOKEN_NOT_SET",errorDescription:e}},e.shared=new e,e}(),U=!1,C=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.anonymousId,r=e.onTokenExpired;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=N.shared,this.api=new _({baseUrl:t,tenantId:n,onTokenExpired:r}),this.anonymousId=o}return e.prototype.signUp=function(e){return c(this,arguments,void 0,(function(e){var t,n,o,r,i,s,c=e.username,h=e.displayName,l=e.token,d=e.authenticatorAttachment,p=void 0===d?"platform":d,f=e.useAutoRegister,y=void 0!==f&&f;return u(this,(function(e){switch(e.label){case 0:return(t=null!=l?l:this.cache.token)?(n={username:c,displayName:h,token:t,authenticatorAttachment:p},[4,this.api.registrationOptions(n)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(o=e.sent()))return[2,A(o)];e.label=2;case 2:return e.trys.push([2,5,,6]),[4,w({optionsJSON:o.options,useAutoRegister:y})];case 3:return r=e.sent(),[4,this.api.addAuthenticator({challengeId:o.challengeId,registrationCredential:r,token:t,conditionalCreate:y})];case 4:return"error"in(i=e.sent())?[2,A(i)]:(i.isVerified&&this.storeCredentialAgainstDevice(a(a({},r),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),[2,{data:{token:i.accessToken,userAuthenticator:i.userAuthenticator,registrationResponse:r}}]);case 5:throw s=e.sent(),U=!1,O(s),s;case 6:return[2]}}))}))},e.prototype.signIn=function(e){return c(this,void 0,void 0,(function(){var t,n,o,r,i,s,c,h,l,d,p,f;return u(this,(function(u){switch(u.label){case 0:if((null==e?void 0:e.token)&&e.autofill)throw new Error("autofill is not supported when providing a token");if((null==e?void 0:e.action)&&e.token)throw new Error("action is not supported when providing a token");if(null==e?void 0:e.autofill){if(U)return[2,{}];U=!0}return(null==e?void 0:e.action)?[4,this.api.challenge(e.action)]:[3,2];case 1:return n=u.sent(),[3,3];case 2:n=null,u.label=3;case 3:return(t=n)&&"error"in t?(U=!1,[2,A(t)]):[4,this.api.authenticationOptions({token:null==e?void 0:e.token,challengeId:null==t?void 0:t.challengeId})];case 4:if("error"in(o=u.sent()))return U=!1,[2,A(o)];u.label=5;case 5:return u.trys.push([5,8,,9]),[4,T({optionsJSON:o.options,useBrowserAutofill:null==e?void 0:e.autofill})];case 6:return r=u.sent(),(null==e?void 0:e.onVerificationStarted)&&e.onVerificationStarted(),[4,this.api.verify({challengeId:o.challengeId,authenticationCredential:r,token:null==e?void 0:e.token,deviceId:this.anonymousId})];case 7:return"error"in(i=u.sent())?(U=!1,[2,A(i)]):(i.isVerified&&this.storeCredentialAgainstDevice(a(a({},r),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),s=i.accessToken,c=i.userId,h=i.userAuthenticatorId,l=i.username,d=i.userDisplayName,p=i.isVerified,U=!1,[2,{data:{isVerified:p,token:s,userId:c,userAuthenticatorId:h,username:l,displayName:d,authenticationResponse:r}}]);case 8:throw f=u.sent(),U=!1,O(f),f;case 9:return[2]}}))}))},e.prototype.isAvailableOnDevice=function(e){return c(this,arguments,void 0,(function(e){var t,n,o,r,i=e.userId;return u(this,(function(e){switch(e.label){case 0:if(!i)throw new Error("userId is required");if(!(t=localStorage.getItem(this.passkeyLocalStorageKey)))return[2,!1];if(n=JSON.parse(t),0===(o=null!==(r=n[i])&&void 0!==r?r:[]).length)return[2,!1];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.api.getPasskeyAuthenticator({credentialIds:o})];case 2:return e.sent(),[2,!0];case 3:return e.sent(),[2,!1];case 4:return[2]}}))}))},e.prototype.storeCredentialAgainstDevice=function(e){var t=e.id,n=e.authenticatorAttachment,o=e.userId,r=void 0===o?"":o;if("cross-platform"!==n){var i=localStorage.getItem(this.passkeyLocalStorageKey),s=i?JSON.parse(i):{};s[r]?s[r].includes(t)||s[r].push(t):s[r]=[t],localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(s))}},e}(),P=function(){function e(){this.windowRef=null}return e.prototype.show=function(e){var t=e.url,n=e.width,o=void 0===n?400:n,r=e.height,i=function(e){var t=e.url,n=e.width,o=e.height,r=e.win;if(!r.top)return null;var i=r.top.outerHeight/2+r.top.screenY-o/2,s=r.top.outerWidth/2+r.top.screenX-n/2;return window.open(t,"","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=".concat(n,", height=").concat(o,", top=").concat(i,", left=").concat(s))}({url:t,width:o,height:void 0===r?500:r,win:window});if(!i)throw new Error("Window is not initialized");return this.windowRef=i,i},e.prototype.close=function(){if(!this.windowRef)throw new Error("Window is not initialized");this.windowRef.close()},e}();const $=":not([inert]):not([inert] *)",D=':not([tabindex^="-"])',L=":not(:disabled)";var j=[`a[href]${$}${D}`,`area[href]${$}${D}`,`input:not([type="hidden"]):not([type="radio"])${$}${D}${L}`,`input[type="radio"]${$}${D}${L}`,`select${$}${D}${L}`,`textarea${$}${D}${L}`,`button${$}${D}${L}`,`details${$} > summary:first-of-type${D}`,`iframe${$}${D}`,`audio[controls]${$}${D}`,`video[controls]${$}${D}`,`[contenteditable]${$}${D}`,`[tabindex]${$}${D}`];function K(e){(e.querySelector("[autofocus]")||e).focus()}function J(e,t){if(t&&M(e))return e;if(!((n=e).shadowRoot&&"-1"===n.getAttribute("tabindex")||n.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let n=V(e.shadowRoot,t);for(;n;){const e=J(n,t);if(e)return e;n=W(n,t)}}else if("slot"===e.localName){const n=e.assignedElements({flatten:!0});t||n.reverse();for(const e of n){const n=J(e,t);if(n)return n}}else{let n=V(e,t);for(;n;){const e=J(n,t);if(e)return e;n=W(n,t)}}var n;return!t&&M(e)?e:null}function V(e,t){return t?e.firstElementChild:e.lastElementChild}function W(e,t){return t?e.nextElementSibling:e.previousElementSibling}const M=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(j.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function q(e=document){const t=e.activeElement;return t?t.shadowRoot?q(t.shadowRoot)||document.activeElement:t:null}function H(e,t){const[n,o]=function(e){const t=J(e,!0);return[t,t?J(e,!1)||t:null]}(e);if(!n)return t.preventDefault();const r=q();t.shiftKey&&r===n?(o.focus(),t.preventDefault()):t.shiftKey||r!==o||(n.focus(),t.preventDefault())}class F{$el;id;previouslyFocused;shown;constructor(e){this.$el=e,this.id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this.previouslyFocused=null,this.shown=!1,this.maintainFocus=this.maintainFocus.bind(this),this.bindKeypress=this.bindKeypress.bind(this),this.handleTriggerClicks=this.handleTriggerClicks.bind(this),this.show=this.show.bind(this),this.hide=this.hide.bind(this),this.$el.setAttribute("aria-hidden","true"),this.$el.setAttribute("aria-modal","true"),this.$el.setAttribute("tabindex","-1"),this.$el.hasAttribute("role")||this.$el.setAttribute("role","dialog"),document.addEventListener("click",this.handleTriggerClicks,!0)}destroy(){return this.hide(),document.removeEventListener("click",this.handleTriggerClicks,!0),this.$el.replaceWith(this.$el.cloneNode(!0)),this.fire("destroy"),this}show(e){return this.shown||(this.shown=!0,this.$el.removeAttribute("aria-hidden"),this.previouslyFocused=q(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):K(this.$el),document.body.addEventListener("focus",this.maintainFocus,!0),this.$el.addEventListener("keydown",this.bindKeypress,!0),this.fire("show",e)),this}hide(e){return this.shown?(this.shown=!1,this.$el.setAttribute("aria-hidden","true"),this.previouslyFocused?.focus?.(),document.body.removeEventListener("focus",this.maintainFocus,!0),this.$el.removeEventListener("keydown",this.bindKeypress,!0),this.fire("hide",e),this):this}on(e,t,n){return this.$el.addEventListener(e,t,n),this}off(e,t,n){return this.$el.removeEventListener(e,t,n),this}fire(e,t){this.$el.dispatchEvent(new CustomEvent(e,{detail:t,cancelable:!0}))}handleTriggerClicks(e){const t=e.target;t.closest(`[data-a11y-dialog-show="${this.id}"]`)&&this.show(e),(t.closest(`[data-a11y-dialog-hide="${this.id}"]`)||t.closest("[data-a11y-dialog-hide]")&&t.closest('[aria-modal="true"]')===this.$el)&&this.hide(e)}bindKeypress(e){if(document.activeElement?.closest('[aria-modal="true"]')!==this.$el)return;let t=!1;try{t=!!this.$el.querySelector('[popover]:not([popover="manual"]):popover-open')}catch{}"Escape"!==e.key||"alertdialog"===this.$el.getAttribute("role")||t||(e.preventDefault(),this.hide(e)),"Tab"===e.key&&H(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||K(this.$el)}}function G(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new F(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",G):G());var B="__authsignal-popup-container",z="__authsignal-popup-content",Y="__authsignal-popup-overlay",X="__authsignal-popup-style",Q="__authsignal-popup-iframe",Z="385px",ee=function(){function e(e){var t=e.width,n=e.isClosable;if(this.popup=null,document.querySelector("#".concat(B)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:t,isClosable:n})}return e.prototype.create=function(e){var t=this,n=e.width,o=void 0===n?Z:n,r=e.isClosable,i=void 0===r||r,s=o;CSS.supports("width",o)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),s=Z);var a=document.createElement("div");a.setAttribute("id",B),a.setAttribute("aria-hidden","true"),i||a.setAttribute("role","alertdialog");var c=document.createElement("div");c.setAttribute("id",Y),i&&c.setAttribute("data-a11y-dialog-hide","true");var u=document.createElement("div");u.setAttribute("id",z),document.body.appendChild(a);var h=document.createElement("style");h.setAttribute("id",X),h.textContent="\n #".concat(B,",\n #").concat(Y," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(B," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(B,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(Y," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(z," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(s,";\n }\n\n #").concat(z," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: 95vh;\n height: ").concat("384px",";\n }\n "),document.head.insertAdjacentElement("beforeend",h),a.appendChild(c),a.appendChild(u),this.popup=new F(a),a.focus(),this.popup.on("hide",(function(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(B)),t=document.querySelector("#".concat(X));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),window.removeEventListener("message",te)},e.prototype.show=function(e){var t,n=e.url;if(!this.popup)throw new Error("Popup is not initialized");var o=document.createElement("iframe");o.setAttribute("id",Q),o.setAttribute("name","authsignal"),o.setAttribute("title","Authsignal multi-factor authentication"),o.setAttribute("src",n),o.setAttribute("frameborder","0"),o.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write");var r=document.querySelector("#".concat(z));r&&r.appendChild(o),window.addEventListener("message",te),null===(t=this.popup)||void 0===t||t.show()},e.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},e.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},e}();function te(e){var t=document.querySelector("#".concat(Q));t&&e.data.height&&(t.style.height=e.data.height+"px")}var ne=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/totp"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/totp"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),oe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=N.shared,this.api=new ne({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,S(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,S(t)]}}))}))},e}(),re=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.email;return u(this,(function(e){switch(e.label){case 0:return t={email:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-otp"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-otp"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/email-otp"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ie=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=N.shared,this.api=new re({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.email;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,S(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,S(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,S(t)]}}))}))},e}(),se=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.phoneNumber;return u(this,(function(e){switch(e.label){case 0:return t={phoneNumber:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/sms"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/sms"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/sms"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ae=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=N.shared,this.api=new se({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.phoneNumber;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,phoneNumber:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,S(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,S(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,S(t)]}}))}))},e}(),ce=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.email;return u(this,(function(e){switch(e.label){case 0:return t={email:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-magic-link"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-magic-link"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.checkVerificationStatus=function(e){return c(this,arguments,void 0,(function(e){var t,n=this,o=e.token;return u(this,(function(e){switch(e.label){case 0:return t=function(){return c(n,void 0,void 0,(function(){var e,n=this;return u(this,(function(r){switch(r.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/email-magic-link/finalize"),{method:"POST",headers:R({token:o,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,r.sent().json()];case 2:return x({response:e=r.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return c(n,void 0,void 0,(function(){var n;return u(this,(function(o){switch(o.label){case 0:return n=e,[4,t()];case 1:return n.apply(void 0,[o.sent()]),[2]}}))}))}),1e3)}))]}}))}))},[4,t()];case 1:return[2,e.sent()]}}))}))},e}(),ue=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=N.shared,this.api=new ce({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.email;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,S(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,S(e.sent())]}}))}))},e.prototype.checkVerificationStatus=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return this.cache.token?[4,this.api.checkVerificationStatus({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(e=t.sent())&&e.accessToken&&(this.cache.token=e.accessToken),[2,S(e)]}}))}))},e}(),he=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=o}return e.prototype.registrationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/registration-options"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/authentication-options"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token,o=e.registrationCredential;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify(o)})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token,o=e.authenticationCredential;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/security-key"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify(o)})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),le=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired;this.cache=N.shared,this.api=new he({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(){return c(this,void 0,void 0,(function(){var e,t,n,o,r;return u(this,(function(i){switch(i.label){case 0:return this.cache.token?(e={token:this.cache.token},[4,this.api.registrationOptions(e)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(t=i.sent()))return[2,A(t)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,w({optionsJSON:t})];case 3:return n=i.sent(),[4,this.api.addAuthenticator({registrationCredential:n,token:this.cache.token})];case 4:return"error"in(o=i.sent())?[2,A(o)]:(o.accessToken&&(this.cache.token=o.accessToken),[2,{data:{token:o.accessToken,registrationResponse:n}}]);case 5:throw O(r=i.sent()),r;case 6:return[2]}}))}))},e.prototype.verify=function(){return c(this,void 0,void 0,(function(){var e,t,n,o,r;return u(this,(function(i){switch(i.label){case 0:return this.cache.token?[4,this.api.authenticationOptions({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(e=i.sent()))return[2,A(e)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,T({optionsJSON:e})];case 3:return t=i.sent(),[4,this.api.verify({authenticationCredential:t,token:this.cache.token})];case 4:return"error"in(n=i.sent())?[2,A(n)]:(n.accessToken&&(this.cache.token=n.accessToken),o=n.accessToken,[2,{data:{isVerified:n.isVerified,token:o,authenticationResponse:t}}]);case 5:throw O(r=i.sent()),r;case 6:return[2]}}))}))},e}(),de="4a08uqve",pe=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,o=void 0===n?"__as_aid":n,r=e.baseUrl,i=void 0===r?"https://api.authsignal.com/v1":r,a=e.tenantId,c=e.onTokenExpired;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=o,!a)throw new Error("tenantId is required");var u,h=(u=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(u).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;h?this.anonymousId=h:(this.anonymousId=s(),I({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.passkey=new C({tenantId:a,baseUrl:i,anonymousId:this.anonymousId,onTokenExpired:c}),this.totp=new oe({tenantId:a,baseUrl:i,onTokenExpired:c}),this.email=new ie({tenantId:a,baseUrl:i,onTokenExpired:c}),this.emailML=new ue({tenantId:a,baseUrl:i,onTokenExpired:c}),this.sms=new ae({tenantId:a,baseUrl:i,onTokenExpired:c}),this.securityKey=new le({tenantId:a,baseUrl:i,onTokenExpired:c})}return t.prototype.setToken=function(e){N.shared.token=e},t.prototype.launch=function(e,t){switch(null==t?void 0:t.mode){case"window":return this.launchWithWindow(e,t);case"popup":return this.launchWithPopup(e,t);default:this.launchWithRedirect(e)}},t.prototype.initAdvancedProfiling=function(e){var t=s();this.profilingId=t,I({name:"__as_pid",value:t,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol});var n=e?"".concat(e,"/fp/tags.js?org_id=").concat(de,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(de,"&session_id=").concat(t),o=document.createElement("script");o.src=n,o.async=!1,o.id="as_adv_profile",document.head.appendChild(o);var r=document.createElement("noscript");r.setAttribute("id","as_adv_profile_pixel"),r.setAttribute("aria-hidden","true");var i=document.createElement("iframe"),a=e?"".concat(e,"/fp/tags?org_id=").concat(de,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(de,"&session_id=").concat(t);i.setAttribute("id","as_adv_profile_pixel"),i.setAttribute("src",a),i.setAttribute("style","width: 100px; height: 100px; border: 0; position: absolute; top: -5000px;"),r&&(r.appendChild(i),document.body.prepend(r))},t.prototype.launchWithRedirect=function(e){window.location.href=e},t.prototype.launchWithPopup=function(t,n){var o=n.popupOptions,r=new ee({width:null==o?void 0:o.width,isClosable:null==o?void 0:o.isClosable}),i="".concat(t,"&mode=popup");return r.show({url:i}),new Promise((function(t){var n=void 0;r.on("hide",(function(){t({token:n})})),window.addEventListener("message",(function(t){var o=null;try{o=JSON.parse(t.data)}catch(e){}(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n=o.token,r.close())}),!1)}))},t.prototype.launchWithWindow=function(t,n){var o=n.windowOptions,r=new P,i="".concat(t,"&mode=popup");return r.show({url:i,width:null==o?void 0:o.width,height:null==o?void 0:o.height}),new Promise((function(t){window.addEventListener("message",(function(n){var o=null;try{o=JSON.parse(n.data)}catch(e){}(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(r.close(),t({token:o.token}))}),!1)}))},t}();return e.Authsignal=pe,e.WebAuthnError=m,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
package/dist/passkey.d.ts CHANGED
@@ -1,5 +1,5 @@
1
+ import { AuthenticationResponseJSON, RegistrationResponseJSON, AuthenticatorAttachment } from "@simplewebauthn/browser";
1
2
  import { PasskeyApiClient } from "./api/passkey-api-client";
2
- import { AuthenticationResponseJSON, RegistrationResponseJSON, AuthenticatorAttachment } from "@simplewebauthn/types";
3
3
  import { AuthsignalResponse } from "./types";
4
4
  import { Authenticator } from "./api/types/shared";
5
5
  type PasskeyOptions = {
@@ -1,4 +1,4 @@
1
- import { AuthenticationResponseJSON, RegistrationResponseJSON } from "@simplewebauthn/types";
1
+ import { AuthenticationResponseJSON, RegistrationResponseJSON } from "@simplewebauthn/browser";
2
2
  import { AuthsignalResponse } from "./types";
3
3
  import { SecurityKeyApiClient } from "./api/security-key-api-client";
4
4
  type SecurityKeyOptions = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authsignal/browser",
3
- "version": "1.5.1",
3
+ "version": "1.5.2",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -28,8 +28,7 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@fingerprintjs/fingerprintjs": "^3.3.6",
31
- "@simplewebauthn/browser": "^11.0.0",
32
- "@simplewebauthn/types": "^11.0.0",
31
+ "@simplewebauthn/browser": "^13.1.0",
33
32
  "a11y-dialog": "8.0.4",
34
33
  "uuid": "^9.0.0"
35
34
  },