@authsignal/browser 1.15.0 → 1.17.0

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.
@@ -1,5 +1,5 @@
1
1
  import { AddAuthenticatorRequest, AddAuthenticatorResponse, AuthenticationOptsRequest, AuthenticationOptsResponse, ChallengeRequest, ChallengeResponse, ErrorResponse, PasskeyAuthenticatorResponse, RegistrationOptsRequest, RegistrationOptsResponse, VerifyRequest, VerifyResponse } from "./types/passkey";
2
- import { ApiClientOptions } from "./types/shared";
2
+ import { ApiClientOptions, Authenticator } from "./types/shared";
3
3
  export declare class PasskeyApiClient {
4
4
  tenantId: string;
5
5
  baseUrl: string;
@@ -20,6 +20,10 @@ export declare class PasskeyApiClient {
20
20
  verify({ authenticationCredential, token, deviceId, challengeId, useCookies, }: {
21
21
  token?: string;
22
22
  } & VerifyRequest): Promise<VerifyResponse | ErrorResponse>;
23
+ getAuthenticators({ token, useCookies, }: {
24
+ token?: string;
25
+ useCookies?: boolean;
26
+ }): Promise<Authenticator[] | ErrorResponse>;
23
27
  getPasskeyAuthenticator({ credentialIds, }: {
24
28
  credentialIds: string[];
25
29
  }): Promise<PasskeyAuthenticatorResponse | ErrorResponse>;
@@ -1,5 +1,6 @@
1
1
  import { AuthenticationResponseJSON, AuthenticatorAttachment, PublicKeyCredentialCreationOptionsJSON, RegistrationResponseJSON } from "@simplewebauthn/browser";
2
2
  import { Authenticator } from "./shared";
3
+ import { ErrorCode } from "../../types";
3
4
  export type RegistrationOptsRequest = {
4
5
  username?: string;
5
6
  authenticatorAttachment?: AuthenticatorAttachment | null;
@@ -57,5 +58,6 @@ export type ChallengeResponse = {
57
58
  };
58
59
  export type ErrorResponse = {
59
60
  error: string;
61
+ errorCode?: ErrorCode;
60
62
  errorDescription?: string;
61
63
  };
@@ -12,11 +12,22 @@ export declare class PopupHandler {
12
12
  private popup;
13
13
  private height;
14
14
  private resizeListener;
15
+ private fallbackTimer;
16
+ private iframeReady;
17
+ private containerEl;
18
+ private contentEl;
19
+ private styleEl;
20
+ private iframeEl;
21
+ private previousOverflow;
15
22
  constructor({ width, height, isClosable }: PopupHandlerOptions);
16
- create({ width, height, isClosable }: PopupHandlerOptions): void;
17
- destroy(): void;
23
+ private init;
24
+ private destroy;
18
25
  show({ url, expectedOrigin }: PopupShowInput): void;
19
26
  close(): void;
20
27
  on(event: A11yDialogEvent, listener: EventListener): void;
28
+ /**
29
+ * Resize the iframe to the height of the pre-built UI's (#widget_container)
30
+ */
31
+ private resizeIframe;
21
32
  }
22
33
  export {};
package/dist/index.js CHANGED
@@ -153,6 +153,16 @@ function __generator(thisArg, body) {
153
153
  } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
154
154
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
155
155
  }
156
+ }
157
+
158
+ function __spreadArray(to, from, pack) {
159
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
160
+ if (ar || !(i in from)) {
161
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
162
+ ar[i] = from[i];
163
+ }
164
+ }
165
+ return to.concat(ar || Array.prototype.slice.call(from));
156
166
  }
157
167
 
158
168
  /**
@@ -818,6 +828,7 @@ var AuthsignalWindowMessage;
818
828
  (function (AuthsignalWindowMessage) {
819
829
  AuthsignalWindowMessage["AUTHSIGNAL_CLOSE_POPUP"] = "AUTHSIGNAL_CLOSE_POPUP";
820
830
  AuthsignalWindowMessage["AUTHSIGNAL_API_ERROR"] = "AUTHSIGNAL_API_ERROR";
831
+ AuthsignalWindowMessage["AUTHSIGNAL_READY"] = "AUTHSIGNAL_READY";
821
832
  })(AuthsignalWindowMessage || (AuthsignalWindowMessage = {}));
822
833
  var ErrorCode;
823
834
  (function (ErrorCode) {
@@ -826,6 +837,7 @@ var ErrorCode;
826
837
  ErrorCode["network_error"] = "network_error";
827
838
  ErrorCode["too_many_requests"] = "too_many_requests";
828
839
  ErrorCode["invalid_credential"] = "invalid_credential";
840
+ ErrorCode["unknown_credential"] = "unknown_credential";
829
841
  })(ErrorCode || (ErrorCode = {}));
830
842
 
831
843
  function buildHeaders(_a) {
@@ -981,6 +993,28 @@ var PasskeyApiClient = /** @class */ (function () {
981
993
  });
982
994
  });
983
995
  };
996
+ PasskeyApiClient.prototype.getAuthenticators = function (_a) {
997
+ return __awaiter(this, arguments, void 0, function (_b) {
998
+ var response, responseJson;
999
+ var token = _b.token, useCookies = _b.useCookies;
1000
+ return __generator(this, function (_c) {
1001
+ switch (_c.label) {
1002
+ case 0: return [4 /*yield*/, fetch("".concat(this.baseUrl, "/client/user-authenticators"), {
1003
+ method: "GET",
1004
+ headers: buildHeaders({ token: token, tenantId: this.tenantId }),
1005
+ credentials: useCookies ? "include" : "same-origin",
1006
+ })];
1007
+ case 1:
1008
+ response = _c.sent();
1009
+ return [4 /*yield*/, response.json()];
1010
+ case 2:
1011
+ responseJson = _c.sent();
1012
+ handleTokenExpired({ response: responseJson, onTokenExpired: this.onTokenExpired });
1013
+ return [2 /*return*/, responseJson];
1014
+ }
1015
+ });
1016
+ });
1017
+ };
984
1018
  PasskeyApiClient.prototype.getPasskeyAuthenticator = function (_a) {
985
1019
  return __awaiter(this, arguments, void 0, function (_b) {
986
1020
  var response;
@@ -1047,6 +1081,104 @@ var TokenCache = /** @class */ (function () {
1047
1081
  return TokenCache;
1048
1082
  }());
1049
1083
 
1084
+ function getSignalApi() {
1085
+ if (typeof window === "undefined" || typeof window.PublicKeyCredential === "undefined") {
1086
+ return null;
1087
+ }
1088
+ return window.PublicKeyCredential;
1089
+ }
1090
+ function signalAllAcceptedCredentials(_a, enableLogging_1) {
1091
+ return __awaiter(this, arguments, void 0, function (_b, enableLogging) {
1092
+ var api, e_1;
1093
+ var rpId = _b.rpId, userId = _b.userId, credentialIds = _b.credentialIds;
1094
+ return __generator(this, function (_c) {
1095
+ switch (_c.label) {
1096
+ case 0:
1097
+ api = getSignalApi();
1098
+ if (!(api === null || api === void 0 ? void 0 : api.signalAllAcceptedCredentials)) {
1099
+ return [2 /*return*/];
1100
+ }
1101
+ _c.label = 1;
1102
+ case 1:
1103
+ _c.trys.push([1, 3, , 4]);
1104
+ return [4 /*yield*/, api.signalAllAcceptedCredentials({
1105
+ rpId: rpId,
1106
+ userId: userId,
1107
+ allAcceptedCredentialIds: credentialIds,
1108
+ })];
1109
+ case 2:
1110
+ _c.sent();
1111
+ return [3 /*break*/, 4];
1112
+ case 3:
1113
+ e_1 = _c.sent();
1114
+ if (enableLogging) {
1115
+ console.warn("[Authsignal] signalAllAcceptedCredentials failed", e_1);
1116
+ }
1117
+ return [3 /*break*/, 4];
1118
+ case 4: return [2 /*return*/];
1119
+ }
1120
+ });
1121
+ });
1122
+ }
1123
+ function signalUnknownCredential(_a, enableLogging_1) {
1124
+ return __awaiter(this, arguments, void 0, function (_b, enableLogging) {
1125
+ var api, e_2;
1126
+ var rpId = _b.rpId, credentialId = _b.credentialId;
1127
+ return __generator(this, function (_c) {
1128
+ switch (_c.label) {
1129
+ case 0:
1130
+ api = getSignalApi();
1131
+ if (!(api === null || api === void 0 ? void 0 : api.signalUnknownCredential)) {
1132
+ return [2 /*return*/];
1133
+ }
1134
+ _c.label = 1;
1135
+ case 1:
1136
+ _c.trys.push([1, 3, , 4]);
1137
+ return [4 /*yield*/, api.signalUnknownCredential({ rpId: rpId, credentialId: credentialId })];
1138
+ case 2:
1139
+ _c.sent();
1140
+ return [3 /*break*/, 4];
1141
+ case 3:
1142
+ e_2 = _c.sent();
1143
+ if (enableLogging) {
1144
+ console.warn("[Authsignal] signalUnknownCredential failed", e_2);
1145
+ }
1146
+ return [3 /*break*/, 4];
1147
+ case 4: return [2 /*return*/];
1148
+ }
1149
+ });
1150
+ });
1151
+ }
1152
+
1153
+ var VerificationMethod;
1154
+ (function (VerificationMethod) {
1155
+ VerificationMethod["SMS"] = "SMS";
1156
+ VerificationMethod["AUTHENTICATOR_APP"] = "AUTHENTICATOR_APP";
1157
+ VerificationMethod["RECOVERY_CODE"] = "RECOVERY_CODE";
1158
+ VerificationMethod["EMAIL_MAGIC_LINK"] = "EMAIL_MAGIC_LINK";
1159
+ VerificationMethod["EMAIL_OTP"] = "EMAIL_OTP";
1160
+ VerificationMethod["PUSH"] = "PUSH";
1161
+ VerificationMethod["SECURITY_KEY"] = "SECURITY_KEY";
1162
+ VerificationMethod["PASSKEY"] = "PASSKEY";
1163
+ VerificationMethod["VERIFF"] = "VERIFF";
1164
+ VerificationMethod["IPROOV"] = "IPROOV";
1165
+ VerificationMethod["PALM_BIOMETRICS_RR"] = "PALM_BIOMETRICS_RR";
1166
+ VerificationMethod["IDVERSE"] = "IDVERSE";
1167
+ VerificationMethod["DEVICE"] = "DEVICE";
1168
+ })(VerificationMethod || (VerificationMethod = {}));
1169
+ var SmsChannel;
1170
+ (function (SmsChannel) {
1171
+ SmsChannel["DEFAULT"] = "DEFAULT";
1172
+ SmsChannel["WHATSAPP"] = "WHATSAPP";
1173
+ SmsChannel["SMS"] = "SMS";
1174
+ })(SmsChannel || (SmsChannel = {}));
1175
+ var DevicePlatform;
1176
+ (function (DevicePlatform) {
1177
+ DevicePlatform["IOS"] = "IOS";
1178
+ DevicePlatform["ANDROID"] = "ANDROID";
1179
+ DevicePlatform["WEB"] = "WEB";
1180
+ })(DevicePlatform || (DevicePlatform = {}));
1181
+
1050
1182
  var autofillRequestPending = false;
1051
1183
  var Passkey = /** @class */ (function () {
1052
1184
  function Passkey(_a) {
@@ -1060,10 +1192,11 @@ var Passkey = /** @class */ (function () {
1060
1192
  }
1061
1193
  Passkey.prototype.signUp = function (_a) {
1062
1194
  return __awaiter(this, arguments, void 0, function (_b) {
1063
- var userToken, optionsInput, optionsResponse, optionsJSON, registrationResponse, addAuthenticatorResponse, e_1;
1064
- var username = _b.username, displayName = _b.displayName, token = _b.token, _c = _b.authenticatorAttachment, authenticatorAttachment = _c === void 0 ? "platform" : _c, hints = _b.hints, _d = _b.useAutoRegister, useAutoRegister = _d === void 0 ? false : _d, _e = _b.useCookies, useCookies = _e === void 0 ? false : _e;
1065
- return __generator(this, function (_f) {
1066
- switch (_f.label) {
1195
+ var userToken, optionsInput, optionsResponse, optionsJSON, registrationResponse, addAuthenticatorResponse, rpId, e_1;
1196
+ var _c;
1197
+ var username = _b.username, displayName = _b.displayName, token = _b.token, _d = _b.authenticatorAttachment, authenticatorAttachment = _d === void 0 ? "platform" : _d, hints = _b.hints, _e = _b.useAutoRegister, useAutoRegister = _e === void 0 ? false : _e, _f = _b.useCookies, useCookies = _f === void 0 ? false : _f, _g = _b.syncCredentials, syncCredentials = _g === void 0 ? true : _g;
1198
+ return __generator(this, function (_h) {
1199
+ switch (_h.label) {
1067
1200
  case 0:
1068
1201
  userToken = token !== null && token !== void 0 ? token : this.cache.token;
1069
1202
  if (!userToken) {
@@ -1072,10 +1205,10 @@ var Passkey = /** @class */ (function () {
1072
1205
  if (!useAutoRegister) return [3 /*break*/, 2];
1073
1206
  return [4 /*yield*/, this.doesBrowserSupportConditionalCreate()];
1074
1207
  case 1:
1075
- if (!(_f.sent())) {
1208
+ if (!(_h.sent())) {
1076
1209
  throw new Error("CONDITIONAL_CREATE_NOT_SUPPORTED");
1077
1210
  }
1078
- _f.label = 2;
1211
+ _h.label = 2;
1079
1212
  case 2:
1080
1213
  optionsInput = {
1081
1214
  username: username,
@@ -1086,17 +1219,17 @@ var Passkey = /** @class */ (function () {
1086
1219
  };
1087
1220
  return [4 /*yield*/, this.api.registrationOptions(optionsInput)];
1088
1221
  case 3:
1089
- optionsResponse = _f.sent();
1222
+ optionsResponse = _h.sent();
1090
1223
  if ("error" in optionsResponse) {
1091
1224
  return [2 /*return*/, handleErrorResponse({ errorResponse: optionsResponse, enableLogging: this.enableLogging })];
1092
1225
  }
1093
- _f.label = 4;
1226
+ _h.label = 4;
1094
1227
  case 4:
1095
- _f.trys.push([4, 7, , 8]);
1228
+ _h.trys.push([4, 7, , 8]);
1096
1229
  optionsJSON = hints ? __assign(__assign({}, optionsResponse.options), { hints: hints }) : optionsResponse.options;
1097
1230
  return [4 /*yield*/, startRegistration({ optionsJSON: optionsJSON, useAutoRegister: useAutoRegister })];
1098
1231
  case 5:
1099
- registrationResponse = _f.sent();
1232
+ registrationResponse = _h.sent();
1100
1233
  return [4 /*yield*/, this.api.addAuthenticator({
1101
1234
  registrationCredential: registrationResponse,
1102
1235
  token: userToken,
@@ -1105,7 +1238,7 @@ var Passkey = /** @class */ (function () {
1105
1238
  useCookies: useCookies,
1106
1239
  })];
1107
1240
  case 6:
1108
- addAuthenticatorResponse = _f.sent();
1241
+ addAuthenticatorResponse = _h.sent();
1109
1242
  if ("error" in addAuthenticatorResponse) {
1110
1243
  return [2 /*return*/, handleErrorResponse({ errorResponse: addAuthenticatorResponse, enableLogging: this.enableLogging })];
1111
1244
  }
@@ -1115,6 +1248,18 @@ var Passkey = /** @class */ (function () {
1115
1248
  if (addAuthenticatorResponse.accessToken) {
1116
1249
  this.cache.token = addAuthenticatorResponse.accessToken;
1117
1250
  }
1251
+ if (syncCredentials &&
1252
+ addAuthenticatorResponse.isVerified &&
1253
+ (addAuthenticatorResponse.accessToken || useCookies)) {
1254
+ rpId = (_c = optionsResponse.options.rp.id) !== null && _c !== void 0 ? _c : window.location.hostname;
1255
+ void this.syncPasskeysWithCredentialManager({
1256
+ rpId: rpId,
1257
+ userHandle: optionsResponse.options.user.id,
1258
+ credentialId: registrationResponse.id,
1259
+ token: addAuthenticatorResponse.accessToken,
1260
+ useCookies: useCookies,
1261
+ });
1262
+ }
1118
1263
  return [2 /*return*/, {
1119
1264
  data: {
1120
1265
  token: addAuthenticatorResponse.accessToken,
@@ -1123,7 +1268,7 @@ var Passkey = /** @class */ (function () {
1123
1268
  },
1124
1269
  }];
1125
1270
  case 7:
1126
- e_1 = _f.sent();
1271
+ e_1 = _h.sent();
1127
1272
  autofillRequestPending = false;
1128
1273
  handleWebAuthnError(e_1);
1129
1274
  throw e_1;
@@ -1134,9 +1279,10 @@ var Passkey = /** @class */ (function () {
1134
1279
  };
1135
1280
  Passkey.prototype.signIn = function (params) {
1136
1281
  return __awaiter(this, void 0, void 0, function () {
1137
- var challengeResponse, _a, optionsResponse, _b, authenticationResponse, verifyResponse, token, userId, userAuthenticatorId, username, userDisplayName, isVerified, e_2;
1138
- return __generator(this, function (_c) {
1139
- switch (_c.label) {
1282
+ var syncCredentials, challengeResponse, _a, optionsResponse, _b, authenticationResponse, verifyResponse, rpId, userHandle, rpId, token, userId, userAuthenticatorId, username, userDisplayName, isVerified, e_2;
1283
+ var _c;
1284
+ return __generator(this, function (_d) {
1285
+ switch (_d.label) {
1140
1286
  case 0:
1141
1287
  if ((params === null || params === void 0 ? void 0 : params.token) && params.autofill) {
1142
1288
  throw new Error("autofill is not supported when providing a token");
@@ -1144,6 +1290,7 @@ var Passkey = /** @class */ (function () {
1144
1290
  if ((params === null || params === void 0 ? void 0 : params.action) && params.token) {
1145
1291
  throw new Error("action is not supported when providing a token");
1146
1292
  }
1293
+ syncCredentials = (_c = params === null || params === void 0 ? void 0 : params.syncCredentials) !== null && _c !== void 0 ? _c : true;
1147
1294
  if (params === null || params === void 0 ? void 0 : params.autofill) {
1148
1295
  if (autofillRequestPending) {
1149
1296
  return [2 /*return*/, {}];
@@ -1155,11 +1302,11 @@ var Passkey = /** @class */ (function () {
1155
1302
  if (!(params === null || params === void 0 ? void 0 : params.action)) return [3 /*break*/, 2];
1156
1303
  return [4 /*yield*/, this.api.challenge({ action: params === null || params === void 0 ? void 0 : params.action, useCookies: params === null || params === void 0 ? void 0 : params.useCookies })];
1157
1304
  case 1:
1158
- _a = _c.sent();
1305
+ _a = _d.sent();
1159
1306
  return [3 /*break*/, 3];
1160
1307
  case 2:
1161
1308
  _a = null;
1162
- _c.label = 3;
1309
+ _d.label = 3;
1163
1310
  case 3:
1164
1311
  challengeResponse = _a;
1165
1312
  if (challengeResponse && "error" in challengeResponse) {
@@ -1173,27 +1320,27 @@ var Passkey = /** @class */ (function () {
1173
1320
  useCookies: params === null || params === void 0 ? void 0 : params.useCookies,
1174
1321
  })];
1175
1322
  case 4:
1176
- _b = _c.sent();
1323
+ _b = _d.sent();
1177
1324
  return [3 /*break*/, 7];
1178
1325
  case 5: return [4 /*yield*/, this.api.authenticationOptionsWeb({ token: params === null || params === void 0 ? void 0 : params.token })];
1179
1326
  case 6:
1180
- _b = _c.sent();
1181
- _c.label = 7;
1327
+ _b = _d.sent();
1328
+ _d.label = 7;
1182
1329
  case 7:
1183
1330
  optionsResponse = _b;
1184
1331
  if ("error" in optionsResponse) {
1185
1332
  autofillRequestPending = false;
1186
1333
  return [2 /*return*/, handleErrorResponse({ errorResponse: optionsResponse, enableLogging: this.enableLogging })];
1187
1334
  }
1188
- _c.label = 8;
1335
+ _d.label = 8;
1189
1336
  case 8:
1190
- _c.trys.push([8, 11, , 12]);
1337
+ _d.trys.push([8, 14, , 15]);
1191
1338
  return [4 /*yield*/, startAuthentication({
1192
1339
  optionsJSON: optionsResponse.options,
1193
1340
  useBrowserAutofill: params === null || params === void 0 ? void 0 : params.autofill,
1194
1341
  })];
1195
1342
  case 9:
1196
- authenticationResponse = _c.sent();
1343
+ authenticationResponse = _d.sent();
1197
1344
  if (params === null || params === void 0 ? void 0 : params.onVerificationStarted) {
1198
1345
  params.onVerificationStarted();
1199
1346
  }
@@ -1205,17 +1352,38 @@ var Passkey = /** @class */ (function () {
1205
1352
  useCookies: params === null || params === void 0 ? void 0 : params.useCookies,
1206
1353
  })];
1207
1354
  case 10:
1208
- verifyResponse = _c.sent();
1209
- if ("error" in verifyResponse) {
1210
- autofillRequestPending = false;
1211
- return [2 /*return*/, handleErrorResponse({ errorResponse: verifyResponse, enableLogging: this.enableLogging })];
1212
- }
1355
+ verifyResponse = _d.sent();
1356
+ if (!("error" in verifyResponse)) return [3 /*break*/, 13];
1357
+ autofillRequestPending = false;
1358
+ if (!(syncCredentials && verifyResponse.errorCode === ErrorCode.unknown_credential)) return [3 /*break*/, 12];
1359
+ rpId = this.getAuthOptionsRpId(optionsResponse.options);
1360
+ return [4 /*yield*/, signalUnknownCredential({ rpId: rpId, credentialId: authenticationResponse.id }, this.enableLogging)];
1361
+ case 11:
1362
+ _d.sent();
1363
+ this.removeCredentialFromLocalCache(authenticationResponse.id);
1364
+ _d.label = 12;
1365
+ case 12: return [2 /*return*/, handleErrorResponse({ errorResponse: verifyResponse, enableLogging: this.enableLogging })];
1366
+ case 13:
1213
1367
  if (verifyResponse.isVerified) {
1214
1368
  this.storeCredentialAgainstDevice(__assign(__assign({}, authenticationResponse), { userId: verifyResponse.userId }));
1215
1369
  }
1216
1370
  if (verifyResponse.accessToken) {
1217
1371
  this.cache.token = verifyResponse.accessToken;
1218
1372
  }
1373
+ userHandle = authenticationResponse.response.userHandle;
1374
+ if (syncCredentials &&
1375
+ verifyResponse.isVerified &&
1376
+ (verifyResponse.accessToken || (params === null || params === void 0 ? void 0 : params.useCookies)) &&
1377
+ userHandle) {
1378
+ rpId = this.getAuthOptionsRpId(optionsResponse.options);
1379
+ void this.syncPasskeysWithCredentialManager({
1380
+ rpId: rpId,
1381
+ userHandle: userHandle,
1382
+ credentialId: authenticationResponse.id,
1383
+ token: verifyResponse.accessToken,
1384
+ useCookies: params === null || params === void 0 ? void 0 : params.useCookies,
1385
+ });
1386
+ }
1219
1387
  token = verifyResponse.accessToken, userId = verifyResponse.userId, userAuthenticatorId = verifyResponse.userAuthenticatorId, username = verifyResponse.username, userDisplayName = verifyResponse.userDisplayName, isVerified = verifyResponse.isVerified;
1220
1388
  autofillRequestPending = false;
1221
1389
  return [2 /*return*/, {
@@ -1229,12 +1397,12 @@ var Passkey = /** @class */ (function () {
1229
1397
  authenticationResponse: authenticationResponse,
1230
1398
  },
1231
1399
  }];
1232
- case 11:
1233
- e_2 = _c.sent();
1400
+ case 14:
1401
+ e_2 = _d.sent();
1234
1402
  autofillRequestPending = false;
1235
1403
  handleWebAuthnError(e_2);
1236
1404
  throw e_2;
1237
- case 12: return [2 /*return*/];
1405
+ case 15: return [2 /*return*/];
1238
1406
  }
1239
1407
  });
1240
1408
  });
@@ -1293,12 +1461,13 @@ var Passkey = /** @class */ (function () {
1293
1461
  };
1294
1462
  Passkey.prototype.doesBrowserSupportConditionalCreate = function () {
1295
1463
  return __awaiter(this, void 0, void 0, function () {
1296
- var capabilities;
1464
+ var publicKeyCredential, capabilities;
1297
1465
  return __generator(this, function (_a) {
1298
1466
  switch (_a.label) {
1299
1467
  case 0:
1300
- if (!(window.PublicKeyCredential && PublicKeyCredential.getClientCapabilities)) return [3 /*break*/, 2];
1301
- return [4 /*yield*/, PublicKeyCredential.getClientCapabilities()];
1468
+ publicKeyCredential = window.PublicKeyCredential;
1469
+ if (!(publicKeyCredential === null || publicKeyCredential === void 0 ? void 0 : publicKeyCredential.getClientCapabilities)) return [3 /*break*/, 2];
1470
+ return [4 /*yield*/, publicKeyCredential.getClientCapabilities()];
1302
1471
  case 1:
1303
1472
  capabilities = _a.sent();
1304
1473
  if (capabilities.conditionalCreate) {
@@ -1310,6 +1479,69 @@ var Passkey = /** @class */ (function () {
1310
1479
  });
1311
1480
  });
1312
1481
  };
1482
+ Passkey.prototype.getAuthOptionsRpId = function (options) {
1483
+ var rpId = options === null || options === void 0 ? void 0 : options.rpId;
1484
+ return rpId !== null && rpId !== void 0 ? rpId : window.location.hostname;
1485
+ };
1486
+ Passkey.prototype.syncPasskeysWithCredentialManager = function (_a) {
1487
+ return __awaiter(this, arguments, void 0, function (_b) {
1488
+ var result, credentialIds, e_3;
1489
+ var rpId = _b.rpId, userHandle = _b.userHandle, credentialId = _b.credentialId, token = _b.token, useCookies = _b.useCookies;
1490
+ return __generator(this, function (_c) {
1491
+ switch (_c.label) {
1492
+ case 0:
1493
+ _c.trys.push([0, 3, , 4]);
1494
+ return [4 /*yield*/, this.api.getAuthenticators({ token: token, useCookies: useCookies })];
1495
+ case 1:
1496
+ result = _c.sent();
1497
+ if (!Array.isArray(result)) {
1498
+ if (this.enableLogging) {
1499
+ console.warn("[Authsignal] Could not fetch authenticators for passkey sync", result);
1500
+ }
1501
+ return [2 /*return*/];
1502
+ }
1503
+ credentialIds = result
1504
+ .filter(function (a) { var _a; return a.verificationMethod === VerificationMethod.PASSKEY && Boolean((_a = a.webauthnCredential) === null || _a === void 0 ? void 0 : _a.credentialId); })
1505
+ .map(function (a) { return a.webauthnCredential.credentialId; });
1506
+ return [4 /*yield*/, signalAllAcceptedCredentials({ rpId: rpId, userId: userHandle, credentialIds: Array.from(new Set(__spreadArray(__spreadArray([], credentialIds, true), [credentialId], false))) }, this.enableLogging)];
1507
+ case 2:
1508
+ _c.sent();
1509
+ return [3 /*break*/, 4];
1510
+ case 3:
1511
+ e_3 = _c.sent();
1512
+ if (this.enableLogging) {
1513
+ console.warn("[Authsignal] Passkey sync failed", e_3);
1514
+ }
1515
+ return [3 /*break*/, 4];
1516
+ case 4: return [2 /*return*/];
1517
+ }
1518
+ });
1519
+ });
1520
+ };
1521
+ Passkey.prototype.removeCredentialFromLocalCache = function (credentialId) {
1522
+ var storedCredentials = localStorage.getItem(this.passkeyLocalStorageKey);
1523
+ if (!storedCredentials)
1524
+ return;
1525
+ var credentialsMap;
1526
+ try {
1527
+ credentialsMap = JSON.parse(storedCredentials);
1528
+ }
1529
+ catch (_a) {
1530
+ return;
1531
+ }
1532
+ var changed = false;
1533
+ for (var _i = 0, _b = Object.keys(credentialsMap); _i < _b.length; _i++) {
1534
+ var userId = _b[_i];
1535
+ var filtered = credentialsMap[userId].filter(function (id) { return id !== credentialId; });
1536
+ if (filtered.length !== credentialsMap[userId].length) {
1537
+ credentialsMap[userId] = filtered;
1538
+ changed = true;
1539
+ }
1540
+ }
1541
+ if (changed) {
1542
+ localStorage.setItem(this.passkeyLocalStorageKey, JSON.stringify(credentialsMap));
1543
+ }
1544
+ };
1313
1545
  return Passkey;
1314
1546
  }());
1315
1547
 
@@ -1777,13 +2009,19 @@ var PopupHandler = /** @class */ (function () {
1777
2009
  var width = _a.width, height = _a.height, isClosable = _a.isClosable;
1778
2010
  this.popup = null;
1779
2011
  this.resizeListener = null;
2012
+ this.fallbackTimer = null;
2013
+ this.iframeReady = false;
2014
+ this.containerEl = null;
2015
+ this.contentEl = null;
2016
+ this.styleEl = null;
2017
+ this.iframeEl = null;
1780
2018
  if (document.querySelector("#".concat(CONTAINER_ID))) {
1781
2019
  throw new Error("Multiple instances of Authsignal popup is not supported.");
1782
2020
  }
1783
2021
  this.height = height;
1784
- this.create({ width: width, height: height, isClosable: isClosable });
2022
+ this.init({ width: width, height: height, isClosable: isClosable });
1785
2023
  }
1786
- PopupHandler.prototype.create = function (_a) {
2024
+ PopupHandler.prototype.init = function (_a) {
1787
2025
  var _this = this;
1788
2026
  var _b = _a.width, width = _b === void 0 ? DEFAULT_WIDTH : _b, height = _a.height, _c = _a.isClosable, isClosable = _c === void 0 ? true : _c;
1789
2027
  var isWidthValidCSSValue = CSS.supports("width", width);
@@ -1812,11 +2050,14 @@ var PopupHandler = /** @class */ (function () {
1812
2050
  // Create CSS for dialog
1813
2051
  var style = document.createElement("style");
1814
2052
  style.setAttribute("id", STYLE_ID);
1815
- style.textContent = "\n #".concat(CONTAINER_ID, ",\n #").concat(OVERLAY_ID, " {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(CONTAINER_ID, " {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(CONTAINER_ID, "[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(OVERLAY_ID, " {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(CONTENT_ID, " {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(popupWidth, ";\n }\n\n #").concat(CONTENT_ID, " iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: ").concat(height ? "100%" : "95vh", ";\n height: ").concat(height !== null && height !== void 0 ? height : INITIAL_HEIGHT, ";\n }\n ");
2053
+ style.textContent = "\n #".concat(CONTAINER_ID, ",\n #").concat(OVERLAY_ID, " {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(CONTAINER_ID, " {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(CONTAINER_ID, "[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(OVERLAY_ID, " {\n background-color: rgba(0, 0, 0, 0.18);\n opacity: 0;\n transition: opacity 150ms ease-out;\n }\n\n #").concat(CONTAINER_ID, ".as-popup-visible #").concat(OVERLAY_ID, " {\n opacity: 1;\n }\n\n #").concat(CONTAINER_ID, ".as-popup-closing #").concat(OVERLAY_ID, " {\n opacity: 0;\n transition-duration: 120ms;\n transition-timing-function: ease-in;\n }\n\n #").concat(CONTENT_ID, " {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n overflow: hidden;\n width: ").concat(popupWidth, ";\n opacity: 0;\n transform: scale(0.95);\n transition: opacity 150ms ease-out, transform 150ms ease-out;\n }\n\n #").concat(CONTAINER_ID, ".as-popup-visible #").concat(CONTENT_ID, " {\n opacity: 1;\n transform: scale(1);\n }\n\n #").concat(CONTAINER_ID, ".as-popup-closing #").concat(CONTENT_ID, " {\n opacity: 0;\n transform: scale(0.95);\n transition-duration: 120ms;\n transition-timing-function: ease-in;\n }\n\n #").concat(CONTENT_ID, " iframe {\n width: 1px;\n min-width: 100%;\n border: 0;\n border-radius: inherit;\n max-height: ").concat(height ? "100%" : "95vh", ";\n height: ").concat(height !== null && height !== void 0 ? height : INITIAL_HEIGHT, ";\n opacity: 0;\n transition: opacity 200ms ease-out;\n }\n\n #").concat(CONTENT_ID, " iframe.as-iframe-ready {\n opacity: 1;\n }\n\n @media (prefers-reduced-motion: reduce) {\n #").concat(OVERLAY_ID, ",\n #").concat(CONTENT_ID, ",\n #").concat(CONTENT_ID, " iframe {\n transition: none !important;\n }\n }\n ");
1816
2054
  // Attach the created elements
1817
2055
  document.head.insertAdjacentElement("beforeend", style);
1818
2056
  container.appendChild(overlay);
1819
2057
  container.appendChild(content);
2058
+ this.containerEl = container;
2059
+ this.contentEl = content;
2060
+ this.styleEl = style;
1820
2061
  this.popup = new A11yDialog(container);
1821
2062
  // Safari and Firefox will fail the WebAuthn request if the document making
1822
2063
  // the request does not have focus. This will reduce the chances of that
@@ -1828,21 +2069,35 @@ var PopupHandler = /** @class */ (function () {
1828
2069
  });
1829
2070
  };
1830
2071
  PopupHandler.prototype.destroy = function () {
1831
- var dialogEl = document.querySelector("#".concat(CONTAINER_ID));
1832
- var styleEl = document.querySelector("#".concat(STYLE_ID));
1833
- if (dialogEl && styleEl) {
1834
- document.body.removeChild(dialogEl);
1835
- document.head.removeChild(styleEl);
2072
+ var _a, _b;
2073
+ if ((_a = this.containerEl) === null || _a === void 0 ? void 0 : _a.parentNode) {
2074
+ this.containerEl.parentNode.removeChild(this.containerEl);
1836
2075
  }
2076
+ this.containerEl = null;
2077
+ this.contentEl = null;
2078
+ this.iframeEl = null;
2079
+ if ((_b = this.styleEl) === null || _b === void 0 ? void 0 : _b.parentNode) {
2080
+ this.styleEl.parentNode.removeChild(this.styleEl);
2081
+ }
2082
+ this.styleEl = null;
1837
2083
  if (this.resizeListener) {
1838
2084
  window.removeEventListener("message", this.resizeListener);
1839
2085
  this.resizeListener = null;
1840
2086
  }
2087
+ if (this.fallbackTimer) {
2088
+ clearTimeout(this.fallbackTimer);
2089
+ this.fallbackTimer = null;
2090
+ }
2091
+ // Restore body scroll
2092
+ if (this.previousOverflow !== undefined) {
2093
+ document.body.style.overflow = this.previousOverflow;
2094
+ this.previousOverflow = undefined;
2095
+ }
1841
2096
  };
1842
2097
  PopupHandler.prototype.show = function (_a) {
1843
- var _b;
2098
+ var _this = this;
1844
2099
  var url = _a.url, expectedOrigin = _a.expectedOrigin;
1845
- if (!this.popup) {
2100
+ if (!this.popup || !this.contentEl || !this.containerEl) {
1846
2101
  throw new Error("Popup is not initialized");
1847
2102
  }
1848
2103
  var iframe = document.createElement("iframe");
@@ -1850,28 +2105,92 @@ var PopupHandler = /** @class */ (function () {
1850
2105
  iframe.setAttribute("name", "authsignal");
1851
2106
  iframe.setAttribute("title", "Authsignal multi-factor authentication");
1852
2107
  iframe.setAttribute("src", url);
1853
- iframe.setAttribute("frameborder", "0");
1854
2108
  iframe.setAttribute("allow", "publickey-credentials-get *; publickey-credentials-create *; clipboard-write");
1855
- var dialogContent = document.querySelector("#".concat(CONTENT_ID));
1856
- if (dialogContent) {
1857
- dialogContent.appendChild(iframe);
1858
- }
2109
+ // Disable scrolling in dynamic height mode — the iframe resizes to fit
2110
+ // content, so scrollbars are never needed and would flash during load.
2111
+ if (!this.height) {
2112
+ iframe.style.overflow = "hidden";
2113
+ }
2114
+ this.contentEl.appendChild(iframe);
2115
+ this.iframeEl = iframe;
2116
+ // Lock body scroll while popup is open
2117
+ this.previousOverflow = document.body.style.overflow;
2118
+ document.body.style.overflow = "hidden";
2119
+ this.popup.show();
2120
+ var container = this.containerEl;
2121
+ var triggerOpenAnimation = function () {
2122
+ requestAnimationFrame(function () {
2123
+ requestAnimationFrame(function () {
2124
+ container.classList.add("as-popup-visible");
2125
+ });
2126
+ });
2127
+ };
1859
2128
  // Dynamic resizing if no height is set.
1860
2129
  if (!this.height) {
2130
+ var revealPopup_1 = function () {
2131
+ if (_this.iframeReady)
2132
+ return;
2133
+ _this.iframeReady = true;
2134
+ iframe.classList.add("as-iframe-ready");
2135
+ triggerOpenAnimation();
2136
+ };
2137
+ // Fallback: reveal after 3s if AUTHSIGNAL_READY is never received
2138
+ // (e.g. due to a network issue or unexpected error in the pre-built UI)
2139
+ this.fallbackTimer = setTimeout(revealPopup_1, 3000);
1861
2140
  this.resizeListener = function (event) {
1862
2141
  if (event.origin !== expectedOrigin)
1863
2142
  return;
1864
- resizeIframe(event);
2143
+ // Handle resize messages (raw objects with height property)
2144
+ _this.resizeIframe(event);
2145
+ // Wait for explicit ready signal from the pre-built UI
2146
+ if (!_this.iframeReady) {
2147
+ var eventName = void 0;
2148
+ try {
2149
+ var data = JSON.parse(event.data);
2150
+ eventName = data === null || data === void 0 ? void 0 : data.event;
2151
+ }
2152
+ catch (_a) {
2153
+ // Resize messages are raw objects, not JSON-stringified
2154
+ }
2155
+ if (eventName === AuthsignalWindowMessage.AUTHSIGNAL_READY) {
2156
+ if (_this.fallbackTimer) {
2157
+ clearTimeout(_this.fallbackTimer);
2158
+ _this.fallbackTimer = null;
2159
+ }
2160
+ revealPopup_1();
2161
+ }
2162
+ }
1865
2163
  };
1866
2164
  window.addEventListener("message", this.resizeListener);
1867
2165
  }
1868
- (_b = this.popup) === null || _b === void 0 ? void 0 : _b.show();
2166
+ else {
2167
+ // Fixed height mode: animate in immediately, reveal iframe on load
2168
+ triggerOpenAnimation();
2169
+ iframe.addEventListener("load", function () {
2170
+ setTimeout(function () {
2171
+ iframe.classList.add("as-iframe-ready");
2172
+ }, 50);
2173
+ });
2174
+ }
1869
2175
  };
1870
2176
  PopupHandler.prototype.close = function () {
1871
- if (!this.popup) {
2177
+ var _this = this;
2178
+ if (!this.popup || !this.containerEl || !this.contentEl) {
1872
2179
  throw new Error("Popup is not initialized");
1873
2180
  }
1874
- this.popup.hide();
2181
+ this.containerEl.classList.remove("as-popup-visible");
2182
+ this.containerEl.classList.add("as-popup-closing");
2183
+ var hidden = false;
2184
+ var hide = function () {
2185
+ var _a;
2186
+ if (hidden)
2187
+ return;
2188
+ hidden = true;
2189
+ (_a = _this.popup) === null || _a === void 0 ? void 0 : _a.hide();
2190
+ };
2191
+ this.contentEl.addEventListener("transitionend", hide, { once: true });
2192
+ // Fallback in case transitionend doesn't fire
2193
+ setTimeout(hide, 150);
1875
2194
  };
1876
2195
  PopupHandler.prototype.on = function (event, listener) {
1877
2196
  if (!this.popup) {
@@ -1879,18 +2198,16 @@ var PopupHandler = /** @class */ (function () {
1879
2198
  }
1880
2199
  this.popup.on(event, listener);
1881
2200
  };
2201
+ /**
2202
+ * Resize the iframe to the height of the pre-built UI's (#widget_container)
2203
+ */
2204
+ PopupHandler.prototype.resizeIframe = function (event) {
2205
+ if (this.iframeEl && event.data.height) {
2206
+ this.iframeEl.style.height = event.data.height + "px";
2207
+ }
2208
+ };
1882
2209
  return PopupHandler;
1883
2210
  }());
1884
- /**
1885
- * Resize the iframe to the height of the pre-built UI's (#widget_container)
1886
- * @param event MessageEvent
1887
- */
1888
- function resizeIframe(event) {
1889
- var iframeEl = document.querySelector("#".concat(IFRAME_ID));
1890
- if (iframeEl && event.data.height) {
1891
- iframeEl.style.height = event.data.height + "px";
1892
- }
1893
- }
1894
2211
 
1895
2212
  var TotpApiClient = /** @class */ (function () {
1896
2213
  function TotpApiClient(_a) {
@@ -3610,6 +3927,7 @@ var Authsignal = /** @class */ (function () {
3610
3927
  }
3611
3928
  };
3612
3929
  popupHandler.on("hide", function () {
3930
+ window.removeEventListener("message", onMessage);
3613
3931
  resolve({ token: token });
3614
3932
  });
3615
3933
  window.addEventListener("message", onMessage, false);
@@ -3636,6 +3954,7 @@ var Authsignal = /** @class */ (function () {
3636
3954
  onError === null || onError === void 0 ? void 0 : onError({ errorCode: data.errorCode, statusCode: data.statusCode });
3637
3955
  }
3638
3956
  if ((data === null || data === void 0 ? void 0 : data.event) === AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP) {
3957
+ window.removeEventListener("message", onMessage);
3639
3958
  windowHandler.close();
3640
3959
  resolve({ token: data.token });
3641
3960
  }
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(e,t){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},a(e,t)};function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var l=function(){return l=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},l.apply(this,arguments)};function h(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}function u(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 d(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 p(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 g(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 f(){return b.stubThis(void 0!==globalThis?.PublicKeyCredential&&"function"==typeof globalThis.PublicKeyCredential)}const b={stubThis:e=>e};function v(e){const{id:t}=e;return{...e,id:g(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 k=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}}},w=["cross-platform","platform"];function E(e){if(e&&!(w.indexOf(e)<0))return e}async function I(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(!f())throw new Error("WebAuthn is not supported in this browser");const o={...t,challenge:g(t.challenge),user:{...t.user,id:g(t.user.id)},excludeCredentials:t.excludeCredentials?.map(v)},r={};let i;n&&(r.mediation="conditional"),r.publicKey=o,r.signal=k.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:l}=i;let h,u,d,b;if("function"==typeof c.getTransports&&(h=c.getTransports()),"function"==typeof c.getPublicKeyAlgorithm)try{u=c.getPublicKeyAlgorithm()}catch(e){T("getPublicKeyAlgorithm()",e)}if("function"==typeof c.getPublicKey)try{const e=c.getPublicKey();null!==e&&(d=p(e))}catch(e){T("getPublicKey()",e)}if("function"==typeof c.getAuthenticatorData)try{b=p(c.getAuthenticatorData())}catch(e){T("getAuthenticatorData()",e)}return{id:s,rawId:p(a),response:{attestationObject:p(c.attestationObject),clientDataJSON:p(c.clientDataJSON),transports:h,publicKeyAlgorithm:u,publicKey:d,authenticatorData:b},type:l,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:E(i.authenticatorAttachment)}}function T(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 C={stubThis:e=>e};async function S(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(!f())throw new Error("WebAuthn is not supported in this browser");let r;0!==t.allowCredentials?.length&&(r=t.allowCredentials?.map(v));const i={...t,challenge:g(t.challenge),allowCredentials:r},s={};if(n){if(!await function(){if(!f())return C.stubThis(new Promise((e=>e(!1))));const e=globalThis.PublicKeyCredential;return void 0===e?.isConditionalMediationAvailable?C.stubThis(new Promise((e=>e(!1)))):C.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=k.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:l,response:h,type:u}=a;let d;return h.userHandle&&(d=p(h.userHandle)),{id:c,rawId:p(l),response:{authenticatorData:p(h.authenticatorData),clientDataJSON:p(h.clientDataJSON),signature:p(h.signature),userHandle:d},type:u,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:E(a.authenticatorAttachment)}}function R(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=e.errorResponse;return e.enableLogging&&console.error("[Authsignal] ".concat(n.errorCode).concat(n.errorDescription?": ".concat(n.errorDescription):"")),{error:null!==(t=n.errorDescription)&&void 0!==t?t:n.error,errorCode:n.errorCode,errorDescription:n.errorDescription}}function L(e){var t,n=e.response,o=e.enableLogging;if(n&&"object"==typeof n&&"error"in n){var r=null!==(t=n.errorDescription)&&void 0!==t?t:n.error;return o&&console.error("[Authsignal] ".concat(n.errorCode).concat(n.errorDescription?": ".concat(n.errorDescription):"")),{error:r,errorCode:n.errorCode,errorDescription:n.errorDescription}}if(n&&"object"==typeof n&&"accessToken"in n&&"string"==typeof n.accessToken){var i=n.accessToken,s=h(n,["accessToken"]);return{data:l(l({},s),{token:i})}}return{data:n}}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'))}}var x,_;function U(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 P(e){var t=e.response,n=e.onTokenExpired;"error"in t&&"expired_token"===t.errorCode&&n&&n()}e.AuthsignalWindowMessage=void 0,(x=e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP",x.AUTHSIGNAL_API_ERROR="AUTHSIGNAL_API_ERROR",e.ErrorCode=void 0,(_=e.ErrorCode||(e.ErrorCode={})).token_not_set="token_not_set",_.expired_token="expired_token",_.network_error="network_error",_.too_many_requests="too_many_requests",_.invalid_credential="invalid_credential";var N=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 u(this,arguments,void 0,(function(e){var t,n,o,r,i=e.token,s=e.username,a=e.authenticatorAttachment,c=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t=Boolean(a)?{username:s,authenticatorAttachment:a}:{username:s},n="".concat(this.baseUrl,c?"/client/user-authenticators/passkey/registration-options/web":"/client/user-authenticators/passkey/registration-options"),o=c?"include":"same-origin",[4,fetch(n,{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:o})];case 1:return[4,e.sent().json()];case 2:return P({response:r=e.sent(),onTokenExpired:this.onTokenExpired}),[2,r]}}))}))},e.prototype.authenticationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,o=e.challengeId,r=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({challengeId:o}),credentials:r?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptionsWeb=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options/web"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({}),credentials:"include"})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.registrationCredential,i=e.conditionalCreate,s=e.challengeId,a=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t={registrationCredential:r,conditionalCreate:i,challengeId:s},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:a?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.authenticationCredential,r=e.token,i=e.deviceId,s=e.challengeId,a=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t={authenticationCredential:o,deviceId:i,challengeId:s},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:a?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.getPasskeyAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.credentialIds;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey?credentialIds=").concat(n),{method:"GET",headers:U({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 u(this,arguments,void 0,(function(e){var t,n,o=e.action,r=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t="".concat(this.baseUrl,r?"/client/challenge/web":"/client/challenge"),[4,fetch(t,{method:"POST",headers:U({tenantId:this.tenantId}),body:JSON.stringify({action:o}),credentials:r?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),D=function(){function t(){this.token=null}return t.prototype.handleTokenNotSetError=function(){var t=e.ErrorCode.token_not_set,n="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(n)),{error:t,errorCode:t,errorDescription:n}},t.shared=new t,t}(),$=!1,j=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.anonymousId,r=e.onTokenExpired,i=e.enableLogging;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=D.shared,this.enableLogging=!1,this.api=new N({baseUrl:t,tenantId:n,onTokenExpired:r}),this.anonymousId=o,this.enableLogging=i}return e.prototype.signUp=function(e){return u(this,arguments,void 0,(function(e){var t,n,o,r,i,s,a=e.username,c=e.displayName,h=e.token,u=e.authenticatorAttachment,p=void 0===u?"platform":u,g=e.hints,f=e.useAutoRegister,b=void 0!==f&&f,v=e.useCookies,y=void 0!==v&&v;return d(this,(function(e){switch(e.label){case 0:return(t=null!=h?h:this.cache.token)?b?[4,this.doesBrowserSupportConditionalCreate()]:[3,2]:[2,this.cache.handleTokenNotSetError()];case 1:if(!e.sent())throw new Error("CONDITIONAL_CREATE_NOT_SUPPORTED");e.label=2;case 2:return n={username:a,displayName:c,token:t,authenticatorAttachment:p,useCookies:y},[4,this.api.registrationOptions(n)];case 3:if("error"in(o=e.sent()))return[2,A({errorResponse:o,enableLogging:this.enableLogging})];e.label=4;case 4:return e.trys.push([4,7,,8]),[4,I({optionsJSON:g?l(l({},o.options),{hints:g}):o.options,useAutoRegister:b})];case 5:return r=e.sent(),[4,this.api.addAuthenticator({registrationCredential:r,token:t,conditionalCreate:b,challengeId:o.challengeId,useCookies:y})];case 6:return"error"in(i=e.sent())?[2,A({errorResponse:i,enableLogging:this.enableLogging})]:(i.isVerified&&this.storeCredentialAgainstDevice(l(l({},r),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),[2,{data:{token:i.accessToken,userAuthenticator:i.userAuthenticator,registrationResponse:r}}]);case 7:throw s=e.sent(),$=!1,O(s),s;case 8:return[2]}}))}))},e.prototype.signIn=function(e){return u(this,void 0,void 0,(function(){var t,n,o,r,i,s,a,c,h,u,p,g,f;return d(this,(function(d){switch(d.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({action:null==e?void 0:e.action,useCookies:null==e?void 0:e.useCookies})]:[3,2];case 1:return n=d.sent(),[3,3];case 2:n=null,d.label=3;case 3:return(t=n)&&"error"in t?($=!1,[2,A({errorResponse:t,enableLogging:this.enableLogging})]):!(null==e?void 0:e.action)&&(null==e?void 0:e.useCookies)?[3,5]:[4,this.api.authenticationOptions({token:null==e?void 0:e.token,challengeId:null==t?void 0:t.challengeId,useCookies:null==e?void 0:e.useCookies})];case 4:return r=d.sent(),[3,7];case 5:return[4,this.api.authenticationOptionsWeb({token:null==e?void 0:e.token})];case 6:r=d.sent(),d.label=7;case 7:if("error"in(o=r))return $=!1,[2,A({errorResponse:o,enableLogging:this.enableLogging})];d.label=8;case 8:return d.trys.push([8,11,,12]),[4,S({optionsJSON:o.options,useBrowserAutofill:null==e?void 0:e.autofill})];case 9:return i=d.sent(),(null==e?void 0:e.onVerificationStarted)&&e.onVerificationStarted(),[4,this.api.verify({authenticationCredential:i,token:null==e?void 0:e.token,deviceId:this.anonymousId,challengeId:o.challengeId,useCookies:null==e?void 0:e.useCookies})];case 10:return"error"in(s=d.sent())?($=!1,[2,A({errorResponse:s,enableLogging:this.enableLogging})]):(s.isVerified&&this.storeCredentialAgainstDevice(l(l({},i),{userId:s.userId})),s.accessToken&&(this.cache.token=s.accessToken),a=s.accessToken,c=s.userId,h=s.userAuthenticatorId,u=s.username,p=s.userDisplayName,g=s.isVerified,$=!1,[2,{data:{isVerified:g,token:a,userId:c,userAuthenticatorId:h,username:u,displayName:p,authenticationResponse:i}}]);case 11:throw f=d.sent(),$=!1,O(f),f;case 12:return[2]}}))}))},e.prototype.isAvailableOnDevice=function(e){return u(this,arguments,void 0,(function(e){var t,n,o,r,i=e.userId;return d(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.prototype.doesBrowserSupportConditionalCreate=function(){return u(this,void 0,void 0,(function(){return d(this,(function(e){switch(e.label){case 0:return window.PublicKeyCredential&&PublicKeyCredential.getClientCapabilities?[4,PublicKeyCredential.getClientCapabilities()]:[3,2];case 1:if(e.sent().conditionalCreate)return[2,!0];e.label=2;case 2:return[2,!1]}}))}))},e}(),J=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 H=":not([inert]):not([inert] *)",W=':not([tabindex^="-"])',K=":not(:disabled)";var M=[`a[href]${H}${W}`,`area[href]${H}${W}`,`input:not([type="hidden"]):not([type="radio"])${H}${W}${K}`,`input[type="radio"]${H}${W}${K}`,`select${H}${W}${K}`,`textarea${H}${W}${K}`,`button${H}${W}${K}`,`details${H} > summary:first-of-type${W}`,`iframe${H}${W}`,`audio[controls]${H}${W}`,`video[controls]${H}${W}`,`[contenteditable]${H}${W}`,`[tabindex]${H}${W}`];function V(e){(e.querySelector("[autofocus]")||e).focus()}function q(e,t){if(t&&z(e))return e;if(!((n=e).shadowRoot&&"-1"===n.getAttribute("tabindex")||n.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let n=G(e.shadowRoot,t);for(;n;){const e=q(n,t);if(e)return e;n=F(n,t)}}else if("slot"===e.localName){const n=e.assignedElements({flatten:!0});t||n.reverse();for(const e of n){const n=q(e,t);if(n)return n}}else{let n=G(e,t);for(;n;){const e=q(n,t);if(e)return e;n=F(n,t)}}var n;return!t&&z(e)?e:null}function G(e,t){return t?e.firstElementChild:e.lastElementChild}function F(e,t){return t?e.nextElementSibling:e.previousElementSibling}const z=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(M.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function B(e=document){const t=e.activeElement;return t?t.shadowRoot?B(t.shadowRoot)||document.activeElement:t:null}function Y(e,t){const[n,o]=function(e){const t=q(e,!0);return[t,t?q(e,!1)||t:null]}(e);if(!n)return t.preventDefault();const r=B();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=B(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):V(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&&Y(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||V(this.$el)}}function X(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new Q(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",X):X());var Z="__authsignal-popup-container",ee="__authsignal-popup-content",te="__authsignal-popup-overlay",ne="__authsignal-popup-style",oe="__authsignal-popup-iframe",re="385px",ie=function(){function e(e){var t=e.width,n=e.height,o=e.isClosable;if(this.popup=null,this.resizeListener=null,document.querySelector("#".concat(Z)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.height=n,this.create({width:t,height:n,isClosable:o})}return e.prototype.create=function(e){var t=this,n=e.width,o=void 0===n?re:n,r=e.height,i=e.isClosable,s=void 0===i||i,a=o;CSS.supports("width",o)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),a=re);var c=document.createElement("div");c.setAttribute("id",Z),c.setAttribute("aria-hidden","true"),s||c.setAttribute("role","alertdialog");var l=document.createElement("div");l.setAttribute("id",te),s&&l.setAttribute("data-a11y-dialog-hide","true");var h=document.createElement("div");h.setAttribute("id",ee),document.body.appendChild(c);var u=document.createElement("style");u.setAttribute("id",ne),u.textContent="\n #".concat(Z,",\n #").concat(te," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(Z," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(Z,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(te," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(ee," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(a,";\n }\n\n #").concat(ee," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: ").concat(r?"100%":"95vh",";\n height: ").concat(null!=r?r:"384px",";\n }\n "),document.head.insertAdjacentElement("beforeend",u),c.appendChild(l),c.appendChild(h),this.popup=new Q(c),c.focus(),this.popup.on("hide",(function(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(Z)),t=document.querySelector("#".concat(ne));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),this.resizeListener&&(window.removeEventListener("message",this.resizeListener),this.resizeListener=null)},e.prototype.show=function(e){var t,n=e.url,o=e.expectedOrigin;if(!this.popup)throw new Error("Popup is not initialized");var r=document.createElement("iframe");r.setAttribute("id",oe),r.setAttribute("name","authsignal"),r.setAttribute("title","Authsignal multi-factor authentication"),r.setAttribute("src",n),r.setAttribute("frameborder","0"),r.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write");var i=document.querySelector("#".concat(ee));i&&i.appendChild(r),this.height||(this.resizeListener=function(e){e.origin===o&&function(e){var t=document.querySelector("#".concat(oe));t&&e.data.height&&(t.style.height=e.data.height+"px")}(e)},window.addEventListener("message",this.resizeListener)),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}();var 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 u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/totp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/totp"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({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,r=e.enableLogging;this.cache=D.shared,this.enableLogging=!1,this.enableLogging=r,this.api=new se({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(){return u(this,void 0,void 0,(function(){return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,L({response:t,enableLogging:this.enableLogging})]}}))}))},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 u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.email;return d(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:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-otp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/email-otp"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),le=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired,r=e.enableLogging;this.cache=D.shared,this.enableLogging=!1,this.enableLogging=r,this.api=new ce({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.email;return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,L({response:t,enableLogging:this.enableLogging})]}}))}))},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.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.phoneNumber;return d(this,(function(e){switch(e.label){case 0:return t={phoneNumber:r},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/sms"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/sms"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/sms"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ue=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired,r=e.enableLogging;this.cache=D.shared,this.enableLogging=!1,this.enableLogging=r,this.api=new he({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.phoneNumber;return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,L({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),de=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 u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.email;return d(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:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-magic-link"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.checkVerificationStatus=function(e){return u(this,arguments,void 0,(function(e){var t,n=this,o=e.token;return d(this,(function(e){switch(e.label){case 0:return t=function(){return u(n,void 0,void 0,(function(){var e,n=this;return d(this,(function(r){switch(r.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/email-magic-link/finalize"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,r.sent().json()];case 2:return P({response:e=r.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return u(n,void 0,void 0,(function(){var n;return d(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}(),pe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired,r=e.enableLogging;this.cache=D.shared,this.enableLogging=!1,this.enableLogging=r,this.api=new de({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.email;return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.checkVerificationStatus=function(){return u(this,void 0,void 0,(function(){var e;return d(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,L({response:e,enableLogging:this.enableLogging})]}}))}))},e}(),ge=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 u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/registration-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/authentication-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,o=e.registrationCredential;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify(o)})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,o=e.authenticationCredential;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/security-key"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify(o)})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),fe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired,r=e.enableLogging;this.cache=D.shared,this.enableLogging=!1,this.api=new ge({baseUrl:t,tenantId:n,onTokenExpired:o}),this.enableLogging=r}return e.prototype.enroll=function(){return u(this,arguments,void 0,(function(e){var t,n,o,r,i,s=(void 0===e?{}:e).hints;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?(t={token:this.cache.token},[4,this.api.registrationOptions(t)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(n=e.sent()))return[2,A({errorResponse:n,enableLogging:this.enableLogging})];e.label=2;case 2:return e.trys.push([2,5,,6]),[4,I({optionsJSON:s?l(l({},n),{hints:s}):n})];case 3:return o=e.sent(),[4,this.api.addAuthenticator({registrationCredential:o,token:this.cache.token})];case 4:return"error"in(r=e.sent())?[2,A({errorResponse:r,enableLogging:this.enableLogging})]:(r.accessToken&&(this.cache.token=r.accessToken),[2,{data:{token:r.accessToken,registrationResponse:o}}]);case 5:throw O(i=e.sent()),i;case 6:return[2]}}))}))},e.prototype.verify=function(){return u(this,void 0,void 0,(function(){var e,t,n,o,r;return d(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({errorResponse:e,enableLogging:this.enableLogging})];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,S({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({errorResponse:n,enableLogging:this.enableLogging})]:(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}(),be=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.baseUrl=t}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.action,o=e.token,r=e.custom;return d(this,(function(e){switch(e.label){case 0:return t={action:n,custom:r},[4,fetch("".concat(this.baseUrl,"/client/challenge/qr-code"),{method:"POST",headers:U({tenantId:this.tenantId,token:o}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.challengeId,o=e.deviceCode;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:n,deviceCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/qr-code"),{method:"POST",headers:U({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e}(),ve=function(){},ye=54e4,me=3e3,ke=function(e){function t(t){var n=t.baseUrl,o=t.tenantId,r=t.enableLogging,i=e.call(this)||this;return i.cache=D.shared,i.enableLogging=!1,i.enableLogging=r,i.api=new be({baseUrl:n,tenantId:o}),i}return c(t,e),t.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t,n,o,r,i,s=this;return d(this,(function(a){switch(a.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:e.action,custom:e.custom})];case 1:return t=a.sent(),(n=L({response:t,enableLogging:this.enableLogging})).data&&(this.currentChallengeParams=e,this.clearPolling(),o=e.pollInterval||me,r=e.refreshInterval||ye,n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:e.onStateChange,pollInterval:o}),e.onRefresh&&(i=e.onRefresh,this.startRefreshTimer((function(){return s.performRefresh({action:e.action,custom:e.custom,onRefresh:i,onStateChange:e.onStateChange,pollInterval:o})}),r))),[2,n]}}))}))},t.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t,n,o,r,i,s,a,c,l,h=this,u=(void 0===e?{}:e).custom;return d(this,(function(e){switch(e.label){case 0:return this.currentChallengeParams?[4,this.api.challenge({token:this.cache.token||void 0,action:this.currentChallengeParams.action,custom:u||this.currentChallengeParams.custom})]:[2];case 1:return t=e.sent(),(n=L({response:t,enableLogging:this.enableLogging})).data&&(this.clearPolling(),this.currentChallengeParams.onRefresh&&this.currentChallengeParams.onRefresh(n.data.challengeId,n.data.expiresAt),n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:this.currentChallengeParams.onStateChange,pollInterval:this.currentChallengeParams.pollInterval||me}),this.currentChallengeParams.onRefresh&&(o=this.currentChallengeParams.refreshInterval||ye,r=this.currentChallengeParams,i=r.action,s=r.custom,a=r.onRefresh,c=r.onStateChange,l=r.pollInterval,this.startRefreshTimer((function(){return h.performRefresh({action:i,custom:s,onRefresh:a,onStateChange:c,pollInterval:l||me})}),o))),[2]}}))}))},t.prototype.disconnect=function(){this.clearPolling(),this.clearRefreshTimer(),this.currentChallengeParams=void 0},t.prototype.startRefreshTimer=function(e,t){var n=this;this.clearRefreshTimer(),this.refreshTimeout=setTimeout((function(){return u(n,void 0,void 0,(function(){return d(this,(function(n){switch(n.label){case 0:return[4,e()];case 1:return n.sent(),this.startRefreshTimer(e,t),[2]}}))}))}),t)},t.prototype.clearRefreshTimer=function(){this.refreshTimeout&&(clearTimeout(this.refreshTimeout),this.refreshTimeout=void 0)},t.prototype.performRefresh=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.action,r=e.custom,i=e.onRefresh,s=e.onStateChange,a=e.pollInterval;return d(this,(function(e){switch(e.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:o,custom:r})];case 1:return t=e.sent(),(n=L({response:t,enableLogging:this.enableLogging})).data&&(this.clearPolling(),i(n.data.challengeId,n.data.expiresAt),n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:s,pollInterval:a})),[2]}}))}))},t.prototype.startPolling=function(e){var t=this,n=e.challengeId,o=e.deviceCode,r=e.onStateChange,i=e.pollInterval;this.pollingInterval=setInterval((function(){return u(t,void 0,void 0,(function(){var e,t;return d(this,(function(i){switch(i.label){case 0:return[4,this.api.verify({challengeId:n,deviceCode:o})];case 1:return e=i.sent(),(t=L({response:e,enableLogging:this.enableLogging})).data&&(t.data.isVerified?(r("approved",t.data.token),this.clearPolling()):t.data.isClaimed&&!t.data.isConsumed?r("claimed"):t.data.isClaimed&&t.data.isConsumed&&(r("rejected"),this.clearPolling())),[2]}}))}))}),i)},t.prototype.clearPolling=function(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0)},t}(ve),we="CHALLENGE_CREATED_HANDLER",Ee=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.ws=null,this.messageHandlers=new Map,this.options=null,this.refreshInterval=null,this.tokenCache=D.shared;var o=t.replace("https://","wss://").replace("http://","ws://").replace("v1","ws-v1-challenge").replace("api","api-ws");this.baseUrl=o,this.tenantId=n}return e.prototype.connect=function(){return u(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return[2,new Promise((function(t,n){try{var o=["authsignal-ws"];e.tokenCache.token?o.push("x.authsignal.token.".concat(e.tokenCache.token)):o.push("x.authsignal.tenant.".concat(e.tenantId)),e.ws=new WebSocket(e.baseUrl,o),e.ws.onopen=function(){t()},e.ws.onerror=function(e){n(new Error("WebSocket connection error: ".concat(e)))},e.ws.onclose=function(){e.refreshInterval&&(clearInterval(e.refreshInterval),e.refreshInterval=null),e.messageHandlers.clear(),e.ws=null},e.ws.onmessage=function(t){try{var n=JSON.parse(t.data);e.handleMessage(n)}catch(e){console.error("Failed to parse WebSocket message:",e)}}}catch(e){n(e)}}))]}))}))},e.prototype.handleMessage=function(e){if("CHALLENGE_CREATED"===e.type){if(!(t=this.messageHandlers.get(we)))throw new Error("Challenge created handler not found");t(e)}else if("STATE_CHANGE"===e.type){var t;(t=this.messageHandlers.get(e.data.challengeId))&&t(e)}},e.prototype.createQrCodeChallenge=function(e){return u(this,void 0,void 0,(function(){var t=this;return d(this,(function(n){switch(n.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:n.sent(),n.label=2;case 2:return this.refreshInterval&&clearInterval(this.refreshInterval),this.options=e,[2,new Promise((function(n,o){t.messageHandlers.set(we,(function(o){if("CHALLENGE_CREATED"===o.type){var r=o;t.messageHandlers.delete(we),t.monitorChallengeState(r.data.challengeId,e),t.startRefreshCycle(r.data.challengeId,e),n({challengeId:r.data.challengeId,expiresAt:r.data.expiresAt,state:r.data.state})}})),t.sendChallengeRequest(e).catch(o)}))]}}))}))},e.prototype.monitorChallengeState=function(e,t){var n=this;this.messageHandlers.set(e,(function(o){var r;if("STATE_CHANGE"===o.type){var i=o;null===(r=t.onStateChange)||void 0===r||r.call(t,i.data.state,i.data.accessToken),"approved"!==i.data.state&&"rejected"!==i.data.state||n.messageHandlers.delete(e)}}))},e.prototype.startRefreshCycle=function(e,t){var n=this,o=t.refreshInterval||54e4,r=e;this.refreshInterval=setInterval((function(){return u(n,void 0,void 0,(function(){var e,n,o;return d(this,(function(i){switch(i.label){case 0:this.messageHandlers.delete(r),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.createQrCodeChallenge(t)];case 2:return e=i.sent(),r=e.challengeId,null===(o=t.onRefresh)||void 0===o||o.call(t,e.challengeId,e.expiresAt),[3,4];case 3:return n=i.sent(),console.error("Failed to refresh QR code challenge:",n),this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=null),[3,4];case 4:return[2]}}))}))}),o)},e.prototype.sendChallengeRequest=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:t.sent(),t.label=2;case 2:if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket connection could not be established");return this.sendMessage({type:"CREATE_CHALLENGE",data:{challengeType:"QR_CODE",actionCode:e.action,custom:e.custom}}),[2]}}))}))},e.prototype.sendMessage=function(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(JSON.stringify(e))},e.prototype.refreshQrCodeChallenge=function(e){return u(this,arguments,void 0,(function(e){var t,n,o,r=e.custom;return d(this,(function(e){switch(e.label){case 0:if(!this.options)throw new Error("Call createQrCodeChallenge first");return[4,this.createQrCodeChallenge(l(l({},this.options),void 0!==r&&{custom:r}))];case 1:return t=e.sent(),null===(o=(n=this.options).onRefresh)||void 0===o||o.call(n,t.challengeId,t.expiresAt),[2,t]}}))}))},e.prototype.disconnect=function(){this.ws&&this.ws.close()},e}(),Ie=function(e){function t(t){var n=t.baseUrl,o=t.tenantId,r=t.enableLogging,i=e.call(this)||this;return i.cache=D.shared,i.enableLogging=!1,i.enableLogging=r,i.wsClient=new Ee({baseUrl:n,tenantId:o}),i}return c(t,e),t.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return[4,this.wsClient.createQrCodeChallenge({token:this.cache.token||void 0,action:e.action,custom:e.custom,refreshInterval:e.refreshInterval,onRefresh:e.onRefresh,onStateChange:e.onStateChange})];case 1:return[2,{data:{challengeId:(t=n.sent()).challengeId,expiresAt:t.expiresAt}}]}}))}))},t.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return d(this,(function(e){switch(e.label){case 0:return[4,this.wsClient.refreshQrCodeChallenge({custom:t})];case 1:return e.sent(),[2]}}))}))},t.prototype.disconnect=function(){this.wsClient.disconnect()},t}(ve),Te=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.enableLogging;this.handler=null,this.enableLogging=!1,this.baseUrl=t,this.tenantId=n,this.enableLogging=o}return e.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t,n,o;return d(this,(function(r){return t=e.polling,n=void 0!==t&&t,o=h(e,["polling"]),this.handler&&this.handler.disconnect(),this.handler=n?new ke({baseUrl:this.baseUrl,tenantId:this.tenantId,enableLogging:this.enableLogging}):new Ie({baseUrl:this.baseUrl,tenantId:this.tenantId,enableLogging:this.enableLogging}),[2,this.handler.challenge(o)]}))}))},e.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return d(this,(function(e){if(!this.handler)throw new Error("challenge() must be called before refresh()");return[2,this.handler.refresh({custom:t})]}))}))},e.prototype.disconnect=function(){this.handler&&(this.handler.disconnect(),this.handler=null)},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.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.action,r=e.token;return d(this,(function(e){switch(e.label){case 0:return t={action:o},[4,fetch("".concat(this.baseUrl,"/client/challenge/push"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.challengeId,r=e.token;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:o},[4,fetch("".concat(this.baseUrl,"/client/verify/push"),{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),Se=function(){function e(e){var t=e.baseUrl,n=e.tenantId,o=e.onTokenExpired,r=e.enableLogging;this.cache=D.shared,this.enableLogging=!1,this.enableLogging=r,this.api=new Ce({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t=e.action;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({action:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t=e.challengeId;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({challengeId:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},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.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/whatsapp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return P({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,o=e.token,r=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/whatsapp"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return P({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,r=e.enableLogging;this.cache=D.shared,this.enableLogging=!1,this.enableLogging=r,this.api=new Re({baseUrl:t,tenantId:n,onTokenExpired:o})}return e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,L({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,L({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),Le="4a08uqve",Oe=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,l=e.enableLogging,h=void 0!==l&&l;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.enableLogging=!1,this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=o,!a)throw new Error("tenantId is required");var u,d=(u=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(u).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;d?this.anonymousId=d:(this.anonymousId=s(),R({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.enableLogging=h,this.passkey=new j({tenantId:a,baseUrl:i,anonymousId:this.anonymousId,onTokenExpired:c,enableLogging:this.enableLogging}),this.totp=new ae({tenantId:a,baseUrl:i,onTokenExpired:c,enableLogging:this.enableLogging}),this.email=new le({tenantId:a,baseUrl:i,onTokenExpired:c,enableLogging:this.enableLogging}),this.emailML=new pe({tenantId:a,baseUrl:i,onTokenExpired:c,enableLogging:this.enableLogging}),this.sms=new ue({tenantId:a,baseUrl:i,onTokenExpired:c,enableLogging:this.enableLogging}),this.securityKey=new fe({tenantId:a,baseUrl:i,onTokenExpired:c,enableLogging:this.enableLogging}),this.qrCode=new Te({tenantId:a,baseUrl:i,enableLogging:this.enableLogging}),this.push=new Se({tenantId:a,baseUrl:i,onTokenExpired:c,enableLogging:this.enableLogging}),this.whatsapp=new Ae({tenantId:a,baseUrl:i,onTokenExpired:c,enableLogging:this.enableLogging})}return t.prototype.setToken=function(e){D.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,R({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(Le,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(Le,"&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(Le,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(Le,"&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=n.onError,i=new ie({width:null==o?void 0:o.width,height:null==o?void 0:o.height,isClosable:null==o?void 0:o.isClosable}),s="".concat(t,"&mode=popup"),a=new URL(t).origin;return i.show({url:s,expectedOrigin:a}),new Promise((function(t){var n=void 0;i.on("hide",(function(){t({token:n})})),window.addEventListener("message",(function(t){if(t.origin===a){var o=null;try{o=JSON.parse(t.data)}catch(e){}(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_API_ERROR&&(null==r||r({errorCode:o.errorCode,statusCode:o.statusCode})),(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n=o.token,i.close())}}),!1)}))},t.prototype.launchWithWindow=function(t,n){var o=n.windowOptions,r=n.onError,i=new J,s="".concat(t,"&mode=popup"),a=new URL(t).origin;return i.show({url:s,width:null==o?void 0:o.width,height:null==o?void 0:o.height}),new Promise((function(t){window.addEventListener("message",(function(n){if(n.origin===a){var o=null;try{o=JSON.parse(n.data)}catch(e){}(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_API_ERROR&&(null==r||r({errorCode:o.errorCode,statusCode:o.statusCode})),(null==o?void 0:o.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(i.close(),t({token:o.token}))}}),!1)}))},t}();return e.Authsignal=Oe,e.WebAuthnError=m,e.Whatsapp=Ae,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
1
+ var authsignal=function(e){"use strict";let t;const n=new Uint8Array(16);function i(){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 o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));var r={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function s(e,t,n){if(r.randomUUID&&!t&&!e)return r.randomUUID();const s=(e=e||{}).random||(e.rng||i)();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(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}(s)}var a=function(e,t){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},a(e,t)};function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var l=function(){return l=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},l.apply(this,arguments)};function h(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}function u(e,t,n,i){return new(n||(n=Promise))((function(o,r){function s(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function d(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(o=2&r[0]?i.return:r[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,r[1])).done)return o;switch(i=0,o&&(r=[2&r[0],o.value]),r[0]){case 0:case 1:o=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,i=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!o||r[1]>o[0]&&r[1]<o[3])){s.label=r[1];break}if(6===r[0]&&s.label<o[1]){s.label=o[1],o=r;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(r);break}o[2]&&s.ops.pop(),s.trys.pop();continue}r=t.call(e,s)}catch(e){r=[6,e],i=0}finally{n=o=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,a])}}}function p(e,t,n){if(n||2===arguments.length)for(var i,o=0,r=t.length;o<r;o++)!i&&o in t||(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))}function g(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 f(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,i=t.padEnd(t.length+n,"="),o=atob(i),r=new ArrayBuffer(o.length),s=new Uint8Array(r);for(let e=0;e<o.length;e++)s[e]=o.charCodeAt(e);return r}function v(){return b.stubThis(void 0!==globalThis?.PublicKeyCredential&&"function"==typeof globalThis.PublicKeyCredential)}const b={stubThis:e=>e};function y(e){const{id:t}=e;return{...e,id:f(t),transports:e.transports}}function m(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}class k extends Error{constructor({message:e,code:t,cause:n,name:i}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??n.name,this.code=t}}const w=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}}},E=["cross-platform","platform"];function I(e){if(e&&!(E.indexOf(e)<0))return e}async function T(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(!v())throw new Error("WebAuthn is not supported in this browser");const i={...t,challenge:f(t.challenge),user:{...t.user,id:f(t.user.id)},excludeCredentials:t.excludeCredentials?.map(y)},o={};let r;n&&(o.mediation="conditional"),o.publicKey=i,o.signal=w.createNewAbortSignal();try{r=await navigator.credentials.create(o)}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 k({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 k({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 k({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 k({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 k({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new k({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 k({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new k({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(!m(t))return new k({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new k({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 k({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 k({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:o})}if(!r)throw new Error("Registration was not completed");const{id:s,rawId:a,response:c,type:l}=r;let h,u,d,p;if("function"==typeof c.getTransports&&(h=c.getTransports()),"function"==typeof c.getPublicKeyAlgorithm)try{u=c.getPublicKeyAlgorithm()}catch(e){C("getPublicKeyAlgorithm()",e)}if("function"==typeof c.getPublicKey)try{const e=c.getPublicKey();null!==e&&(d=g(e))}catch(e){C("getPublicKey()",e)}if("function"==typeof c.getAuthenticatorData)try{p=g(c.getAuthenticatorData())}catch(e){C("getAuthenticatorData()",e)}return{id:s,rawId:g(a),response:{attestationObject:g(c.attestationObject),clientDataJSON:g(c.clientDataJSON),transports:h,publicKeyAlgorithm:u,publicKey:d,authenticatorData:p},type:l,clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:I(r.authenticatorAttachment)}}function C(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 A={stubThis:e=>e};async function S(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:i=!0}=e;if(!v())throw new Error("WebAuthn is not supported in this browser");let o;0!==t.allowCredentials?.length&&(o=t.allowCredentials?.map(y));const r={...t,challenge:f(t.challenge),allowCredentials:o},s={};if(n){if(!await function(){if(!v())return A.stubThis(new Promise((e=>e(!1))));const e=globalThis.PublicKeyCredential;return void 0===e?.isConditionalMediationAvailable?A.stubThis(new Promise((e=>e(!1)))):A.stubThis(e.isConditionalMediationAvailable())}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&i)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');s.mediation="conditional",r.allowCredentials=[]}let a;s.publicKey=r,s.signal=w.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 k({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new k({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!m(t))return new k({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new k({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 k({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:l,response:h,type:u}=a;let d;return h.userHandle&&(d=g(h.userHandle)),{id:c,rawId:g(l),response:{authenticatorData:g(h.authenticatorData),clientDataJSON:g(h.clientDataJSON),signature:g(h.signature),userHandle:d},type:u,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:I(a.authenticatorAttachment)}}function R(e){var t=e.name,n=e.value,i=e.expire,o=e.domain,r=e.secure,s=i===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+i;document.cookie=encodeURIComponent(t)+"="+n+"; path=/;"+s+(o?"; domain="+o:"")+(r?"; secure":"")}function L(e){var t,n=e.errorResponse;return e.enableLogging&&console.error("[Authsignal] ".concat(n.errorCode).concat(n.errorDescription?": ".concat(n.errorDescription):"")),{error:null!==(t=n.errorDescription)&&void 0!==t?t:n.error,errorCode:n.errorCode,errorDescription:n.errorDescription}}function O(e){var t,n=e.response,i=e.enableLogging;if(n&&"object"==typeof n&&"error"in n){var o=null!==(t=n.errorDescription)&&void 0!==t?t:n.error;return i&&console.error("[Authsignal] ".concat(n.errorCode).concat(n.errorDescription?": ".concat(n.errorDescription):"")),{error:o,errorCode:n.errorCode,errorDescription:n.errorDescription}}if(n&&"object"==typeof n&&"accessToken"in n&&"string"==typeof n.accessToken){var r=n.accessToken,s=h(n,["accessToken"]);return{data:l(l({},s),{token:r})}}return{data:n}}function _(e){var t,n;if(e instanceof k&&"ERROR_INVALID_RP_ID"===e.code){var i=(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(i,'" is invalid for this domain.\n To learn more, visit https://docs.authsignal.com/scenarios/passkeys-prebuilt-ui#defining-the-relying-party'))}}var x,P;function U(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 N(e){var t=e.response,n=e.onTokenExpired;"error"in t&&"expired_token"===t.errorCode&&n&&n()}e.AuthsignalWindowMessage=void 0,(x=e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP",x.AUTHSIGNAL_API_ERROR="AUTHSIGNAL_API_ERROR",x.AUTHSIGNAL_READY="AUTHSIGNAL_READY",e.ErrorCode=void 0,(P=e.ErrorCode||(e.ErrorCode={})).token_not_set="token_not_set",P.expired_token="expired_token",P.network_error="network_error",P.too_many_requests="too_many_requests",P.invalid_credential="invalid_credential",P.unknown_credential="unknown_credential";var D,$,j,H=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.registrationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n,i,o,r=e.token,s=e.username,a=e.authenticatorAttachment,c=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t=Boolean(a)?{username:s,authenticatorAttachment:a}:{username:s},n="".concat(this.baseUrl,c?"/client/user-authenticators/passkey/registration-options/web":"/client/user-authenticators/passkey/registration-options"),i=c?"include":"same-origin",[4,fetch(n,{method:"POST",headers:U({token:r,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:i})];case 1:return[4,e.sent().json()];case 2:return N({response:o=e.sent(),onTokenExpired:this.onTokenExpired}),[2,o]}}))}))},e.prototype.authenticationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,i=e.challengeId,o=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({challengeId:i}),credentials:o?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptionsWeb=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options/web"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({}),credentials:"include"})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.registrationCredential,r=e.conditionalCreate,s=e.challengeId,a=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t={registrationCredential:o,conditionalCreate:r,challengeId:s},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:a?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.authenticationCredential,o=e.token,r=e.deviceId,s=e.challengeId,a=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t={authenticationCredential:i,deviceId:r,challengeId:s},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t),credentials:a?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.getAuthenticators=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,i=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators"),{method:"GET",headers:U({token:n,tenantId:this.tenantId}),credentials:i?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.getPasskeyAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.credentialIds;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey?credentialIds=").concat(n),{method:"GET",headers:U({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 u(this,arguments,void 0,(function(e){var t,n,i=e.action,o=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return t="".concat(this.baseUrl,o?"/client/challenge/web":"/client/challenge"),[4,fetch(t,{method:"POST",headers:U({tenantId:this.tenantId}),body:JSON.stringify({action:i}),credentials:o?"include":"same-origin"})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),M=function(){function t(){this.token=null}return t.prototype.handleTokenNotSetError=function(){var t=e.ErrorCode.token_not_set,n="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(n)),{error:t,errorCode:t,errorDescription:n}},t.shared=new t,t}();function K(){return"undefined"==typeof window||void 0===window.PublicKeyCredential?null:window.PublicKeyCredential}function W(e,t){return u(this,arguments,void 0,(function(e,t){var n,i,o=e.rpId,r=e.userId,s=e.credentialIds;return d(this,(function(e){switch(e.label){case 0:if(!(null==(n=K())?void 0:n.signalAllAcceptedCredentials))return[2];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,n.signalAllAcceptedCredentials({rpId:o,userId:r,allAcceptedCredentialIds:s})];case 2:return e.sent(),[3,4];case 3:return i=e.sent(),t&&console.warn("[Authsignal] signalAllAcceptedCredentials failed",i),[3,4];case 4:return[2]}}))}))}function J(e,t){return u(this,arguments,void 0,(function(e,t){var n,i,o=e.rpId,r=e.credentialId;return d(this,(function(e){switch(e.label){case 0:if(!(null==(n=K())?void 0:n.signalUnknownCredential))return[2];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,n.signalUnknownCredential({rpId:o,credentialId:r})];case 2:return e.sent(),[3,4];case 3:return i=e.sent(),t&&console.warn("[Authsignal] signalUnknownCredential failed",i),[3,4];case 4:return[2]}}))}))}!function(e){e.SMS="SMS",e.AUTHENTICATOR_APP="AUTHENTICATOR_APP",e.RECOVERY_CODE="RECOVERY_CODE",e.EMAIL_MAGIC_LINK="EMAIL_MAGIC_LINK",e.EMAIL_OTP="EMAIL_OTP",e.PUSH="PUSH",e.SECURITY_KEY="SECURITY_KEY",e.PASSKEY="PASSKEY",e.VERIFF="VERIFF",e.IPROOV="IPROOV",e.PALM_BIOMETRICS_RR="PALM_BIOMETRICS_RR",e.IDVERSE="IDVERSE",e.DEVICE="DEVICE"}(D||(D={})),function(e){e.DEFAULT="DEFAULT",e.WHATSAPP="WHATSAPP",e.SMS="SMS"}($||($={})),function(e){e.IOS="IOS",e.ANDROID="ANDROID",e.WEB="WEB"}(j||(j={}));var V=!1,G=function(){function t(e){var t=e.baseUrl,n=e.tenantId,i=e.anonymousId,o=e.onTokenExpired,r=e.enableLogging;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=M.shared,this.enableLogging=!1,this.api=new H({baseUrl:t,tenantId:n,onTokenExpired:o}),this.anonymousId=i,this.enableLogging=r}return t.prototype.signUp=function(e){return u(this,arguments,void 0,(function(e){var t,n,i,o,r,s,a,c,h=e.username,u=e.displayName,p=e.token,g=e.authenticatorAttachment,f=void 0===g?"platform":g,v=e.hints,b=e.useAutoRegister,y=void 0!==b&&b,m=e.useCookies,k=void 0!==m&&m,w=e.syncCredentials,E=void 0===w||w;return d(this,(function(e){switch(e.label){case 0:return(t=null!=p?p:this.cache.token)?y?[4,this.doesBrowserSupportConditionalCreate()]:[3,2]:[2,this.cache.handleTokenNotSetError()];case 1:if(!e.sent())throw new Error("CONDITIONAL_CREATE_NOT_SUPPORTED");e.label=2;case 2:return n={username:h,displayName:u,token:t,authenticatorAttachment:f,useCookies:k},[4,this.api.registrationOptions(n)];case 3:if("error"in(i=e.sent()))return[2,L({errorResponse:i,enableLogging:this.enableLogging})];e.label=4;case 4:return e.trys.push([4,7,,8]),[4,T({optionsJSON:v?l(l({},i.options),{hints:v}):i.options,useAutoRegister:y})];case 5:return o=e.sent(),[4,this.api.addAuthenticator({registrationCredential:o,token:t,conditionalCreate:y,challengeId:i.challengeId,useCookies:k})];case 6:return"error"in(r=e.sent())?[2,L({errorResponse:r,enableLogging:this.enableLogging})]:(r.isVerified&&this.storeCredentialAgainstDevice(l(l({},o),{userId:r.userId})),r.accessToken&&(this.cache.token=r.accessToken),E&&r.isVerified&&(r.accessToken||k)&&(s=null!==(c=i.options.rp.id)&&void 0!==c?c:window.location.hostname,this.syncPasskeysWithCredentialManager({rpId:s,userHandle:i.options.user.id,credentialId:o.id,token:r.accessToken,useCookies:k})),[2,{data:{token:r.accessToken,userAuthenticator:r.userAuthenticator,registrationResponse:o}}]);case 7:throw a=e.sent(),V=!1,_(a),a;case 8:return[2]}}))}))},t.prototype.signIn=function(t){return u(this,void 0,void 0,(function(){var n,i,o,r,s,a,c,h,u,p,g,f,v,b,y,m,k;return d(this,(function(d){switch(d.label){case 0:if((null==t?void 0:t.token)&&t.autofill)throw new Error("autofill is not supported when providing a token");if((null==t?void 0:t.action)&&t.token)throw new Error("action is not supported when providing a token");if(n=null===(k=null==t?void 0:t.syncCredentials)||void 0===k||k,null==t?void 0:t.autofill){if(V)return[2,{}];V=!0}return(null==t?void 0:t.action)?[4,this.api.challenge({action:null==t?void 0:t.action,useCookies:null==t?void 0:t.useCookies})]:[3,2];case 1:return o=d.sent(),[3,3];case 2:o=null,d.label=3;case 3:return(i=o)&&"error"in i?(V=!1,[2,L({errorResponse:i,enableLogging:this.enableLogging})]):!(null==t?void 0:t.action)&&(null==t?void 0:t.useCookies)?[3,5]:[4,this.api.authenticationOptions({token:null==t?void 0:t.token,challengeId:null==i?void 0:i.challengeId,useCookies:null==t?void 0:t.useCookies})];case 4:return s=d.sent(),[3,7];case 5:return[4,this.api.authenticationOptionsWeb({token:null==t?void 0:t.token})];case 6:s=d.sent(),d.label=7;case 7:if("error"in(r=s))return V=!1,[2,L({errorResponse:r,enableLogging:this.enableLogging})];d.label=8;case 8:return d.trys.push([8,14,,15]),[4,S({optionsJSON:r.options,useBrowserAutofill:null==t?void 0:t.autofill})];case 9:return a=d.sent(),(null==t?void 0:t.onVerificationStarted)&&t.onVerificationStarted(),[4,this.api.verify({authenticationCredential:a,token:null==t?void 0:t.token,deviceId:this.anonymousId,challengeId:r.challengeId,useCookies:null==t?void 0:t.useCookies})];case 10:return"error"in(c=d.sent())?(V=!1,n&&c.errorCode===e.ErrorCode.unknown_credential?[4,J({rpId:u=this.getAuthOptionsRpId(r.options),credentialId:a.id},this.enableLogging)]:[3,12]):[3,13];case 11:d.sent(),this.removeCredentialFromLocalCache(a.id),d.label=12;case 12:return[2,L({errorResponse:c,enableLogging:this.enableLogging})];case 13:return c.isVerified&&this.storeCredentialAgainstDevice(l(l({},a),{userId:c.userId})),c.accessToken&&(this.cache.token=c.accessToken),h=a.response.userHandle,n&&c.isVerified&&(c.accessToken||(null==t?void 0:t.useCookies))&&h&&(u=this.getAuthOptionsRpId(r.options),this.syncPasskeysWithCredentialManager({rpId:u,userHandle:h,credentialId:a.id,token:c.accessToken,useCookies:null==t?void 0:t.useCookies})),p=c.accessToken,g=c.userId,f=c.userAuthenticatorId,v=c.username,b=c.userDisplayName,y=c.isVerified,V=!1,[2,{data:{isVerified:y,token:p,userId:g,userAuthenticatorId:f,username:v,displayName:b,authenticationResponse:a}}];case 14:throw m=d.sent(),V=!1,_(m),m;case 15:return[2]}}))}))},t.prototype.isAvailableOnDevice=function(e){return u(this,arguments,void 0,(function(e){var t,n,i,o,r=e.userId;return d(this,(function(e){switch(e.label){case 0:if(!r)throw new Error("userId is required");if(!(t=localStorage.getItem(this.passkeyLocalStorageKey)))return[2,!1];if(n=JSON.parse(t),0===(i=null!==(o=n[r])&&void 0!==o?o:[]).length)return[2,!1];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.api.getPasskeyAuthenticator({credentialIds:i})];case 2:return e.sent(),[2,!0];case 3:return e.sent(),[2,!1];case 4:return[2]}}))}))},t.prototype.storeCredentialAgainstDevice=function(e){var t=e.id,n=e.authenticatorAttachment,i=e.userId,o=void 0===i?"":i;if("cross-platform"!==n){var r=localStorage.getItem(this.passkeyLocalStorageKey),s=r?JSON.parse(r):{};s[o]?s[o].includes(t)||s[o].push(t):s[o]=[t],localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(s))}},t.prototype.doesBrowserSupportConditionalCreate=function(){return u(this,void 0,void 0,(function(){var e;return d(this,(function(t){switch(t.label){case 0:return(null==(e=window.PublicKeyCredential)?void 0:e.getClientCapabilities)?[4,e.getClientCapabilities()]:[3,2];case 1:if(t.sent().conditionalCreate)return[2,!0];t.label=2;case 2:return[2,!1]}}))}))},t.prototype.getAuthOptionsRpId=function(e){var t=null==e?void 0:e.rpId;return null!=t?t:window.location.hostname},t.prototype.syncPasskeysWithCredentialManager=function(e){return u(this,arguments,void 0,(function(e){var t,n,i,o=e.rpId,r=e.userHandle,s=e.credentialId,a=e.token,c=e.useCookies;return d(this,(function(e){switch(e.label){case 0:return e.trys.push([0,3,,4]),[4,this.api.getAuthenticators({token:a,useCookies:c})];case 1:return t=e.sent(),Array.isArray(t)?(n=t.filter((function(e){var t;return e.verificationMethod===D.PASSKEY&&Boolean(null===(t=e.webauthnCredential)||void 0===t?void 0:t.credentialId)})).map((function(e){return e.webauthnCredential.credentialId})),[4,W({rpId:o,userId:r,credentialIds:Array.from(new Set(p(p([],n,!0),[s],!1)))},this.enableLogging)]):(this.enableLogging&&console.warn("[Authsignal] Could not fetch authenticators for passkey sync",t),[2]);case 2:return e.sent(),[3,4];case 3:return i=e.sent(),this.enableLogging&&console.warn("[Authsignal] Passkey sync failed",i),[3,4];case 4:return[2]}}))}))},t.prototype.removeCredentialFromLocalCache=function(e){var t=localStorage.getItem(this.passkeyLocalStorageKey);if(t){var n;try{n=JSON.parse(t)}catch(e){return}for(var i=!1,o=0,r=Object.keys(n);o<r.length;o++){var s=r[o],a=n[s].filter((function(t){return t!==e}));a.length!==n[s].length&&(n[s]=a,i=!0)}i&&localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(n))}},t}(),F=function(){function e(){this.windowRef=null}return e.prototype.show=function(e){var t=e.url,n=e.width,i=void 0===n?400:n,o=e.height,r=function(e){var t=e.url,n=e.width,i=e.height,o=e.win;if(!o.top)return null;var r=o.top.outerHeight/2+o.top.screenY-i/2,s=o.top.outerWidth/2+o.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(i,", top=").concat(r,", left=").concat(s))}({url:t,width:i,height:void 0===o?500:o,win:window});if(!r)throw new Error("Window is not initialized");return this.windowRef=r,r},e.prototype.close=function(){if(!this.windowRef)throw new Error("Window is not initialized");this.windowRef.close()},e}();const q=":not([inert]):not([inert] *)",Y=':not([tabindex^="-"])',z=":not(:disabled)";var B=[`a[href]${q}${Y}`,`area[href]${q}${Y}`,`input:not([type="hidden"]):not([type="radio"])${q}${Y}${z}`,`input[type="radio"]${q}${Y}${z}`,`select${q}${Y}${z}`,`textarea${q}${Y}${z}`,`button${q}${Y}${z}`,`details${q} > summary:first-of-type${Y}`,`iframe${q}${Y}`,`audio[controls]${q}${Y}`,`video[controls]${q}${Y}`,`[contenteditable]${q}${Y}`,`[tabindex]${q}${Y}`];function Q(e){(e.querySelector("[autofocus]")||e).focus()}function X(e,t){if(t&&te(e))return e;if(!((n=e).shadowRoot&&"-1"===n.getAttribute("tabindex")||n.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let n=Z(e.shadowRoot,t);for(;n;){const e=X(n,t);if(e)return e;n=ee(n,t)}}else if("slot"===e.localName){const n=e.assignedElements({flatten:!0});t||n.reverse();for(const e of n){const n=X(e,t);if(n)return n}}else{let n=Z(e,t);for(;n;){const e=X(n,t);if(e)return e;n=ee(n,t)}}var n;return!t&&te(e)?e:null}function Z(e,t){return t?e.firstElementChild:e.lastElementChild}function ee(e,t){return t?e.nextElementSibling:e.previousElementSibling}const te=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(B.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function ne(e=document){const t=e.activeElement;return t?t.shadowRoot?ne(t.shadowRoot)||document.activeElement:t:null}function ie(e,t){const[n,i]=function(e){const t=X(e,!0);return[t,t?X(e,!1)||t:null]}(e);if(!n)return t.preventDefault();const o=ne();t.shiftKey&&o===n?(i.focus(),t.preventDefault()):t.shiftKey||o!==i||(n.focus(),t.preventDefault())}class oe{$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=ne(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):Q(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&&ie(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||Q(this.$el)}}function re(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new oe(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",re):re());var se="__authsignal-popup-container",ae="__authsignal-popup-content",ce="__authsignal-popup-overlay",le="385px",he=function(){function t(e){var t=e.width,n=e.height,i=e.isClosable;if(this.popup=null,this.resizeListener=null,this.fallbackTimer=null,this.iframeReady=!1,this.containerEl=null,this.contentEl=null,this.styleEl=null,this.iframeEl=null,document.querySelector("#".concat(se)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.height=n,this.init({width:t,height:n,isClosable:i})}return t.prototype.init=function(e){var t=this,n=e.width,i=void 0===n?le:n,o=e.height,r=e.isClosable,s=void 0===r||r,a=i;CSS.supports("width",i)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),a=le);var c=document.createElement("div");c.setAttribute("id",se),c.setAttribute("aria-hidden","true"),s||c.setAttribute("role","alertdialog");var l=document.createElement("div");l.setAttribute("id",ce),s&&l.setAttribute("data-a11y-dialog-hide","true");var h=document.createElement("div");h.setAttribute("id",ae),document.body.appendChild(c);var u=document.createElement("style");u.setAttribute("id","__authsignal-popup-style"),u.textContent="\n #".concat(se,",\n #").concat(ce," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(se," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(se,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(ce," {\n background-color: rgba(0, 0, 0, 0.18);\n opacity: 0;\n transition: opacity 150ms ease-out;\n }\n\n #").concat(se,".as-popup-visible #").concat(ce," {\n opacity: 1;\n }\n\n #").concat(se,".as-popup-closing #").concat(ce," {\n opacity: 0;\n transition-duration: 120ms;\n transition-timing-function: ease-in;\n }\n\n #").concat(ae," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n overflow: hidden;\n width: ").concat(a,";\n opacity: 0;\n transform: scale(0.95);\n transition: opacity 150ms ease-out, transform 150ms ease-out;\n }\n\n #").concat(se,".as-popup-visible #").concat(ae," {\n opacity: 1;\n transform: scale(1);\n }\n\n #").concat(se,".as-popup-closing #").concat(ae," {\n opacity: 0;\n transform: scale(0.95);\n transition-duration: 120ms;\n transition-timing-function: ease-in;\n }\n\n #").concat(ae," iframe {\n width: 1px;\n min-width: 100%;\n border: 0;\n border-radius: inherit;\n max-height: ").concat(o?"100%":"95vh",";\n height: ").concat(null!=o?o:"384px",";\n opacity: 0;\n transition: opacity 200ms ease-out;\n }\n\n #").concat(ae," iframe.as-iframe-ready {\n opacity: 1;\n }\n\n @media (prefers-reduced-motion: reduce) {\n #").concat(ce,",\n #").concat(ae,",\n #").concat(ae," iframe {\n transition: none !important;\n }\n }\n "),document.head.insertAdjacentElement("beforeend",u),c.appendChild(l),c.appendChild(h),this.containerEl=c,this.contentEl=h,this.styleEl=u,this.popup=new oe(c),c.focus(),this.popup.on("hide",(function(){t.destroy()}))},t.prototype.destroy=function(){var e,t;(null===(e=this.containerEl)||void 0===e?void 0:e.parentNode)&&this.containerEl.parentNode.removeChild(this.containerEl),this.containerEl=null,this.contentEl=null,this.iframeEl=null,(null===(t=this.styleEl)||void 0===t?void 0:t.parentNode)&&this.styleEl.parentNode.removeChild(this.styleEl),this.styleEl=null,this.resizeListener&&(window.removeEventListener("message",this.resizeListener),this.resizeListener=null),this.fallbackTimer&&(clearTimeout(this.fallbackTimer),this.fallbackTimer=null),void 0!==this.previousOverflow&&(document.body.style.overflow=this.previousOverflow,this.previousOverflow=void 0)},t.prototype.show=function(t){var n=this,i=t.url,o=t.expectedOrigin;if(!this.popup||!this.contentEl||!this.containerEl)throw new Error("Popup is not initialized");var r=document.createElement("iframe");r.setAttribute("id","__authsignal-popup-iframe"),r.setAttribute("name","authsignal"),r.setAttribute("title","Authsignal multi-factor authentication"),r.setAttribute("src",i),r.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write"),this.height||(r.style.overflow="hidden"),this.contentEl.appendChild(r),this.iframeEl=r,this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",this.popup.show();var s=this.containerEl,a=function(){requestAnimationFrame((function(){requestAnimationFrame((function(){s.classList.add("as-popup-visible")}))}))};if(this.height)a(),r.addEventListener("load",(function(){setTimeout((function(){r.classList.add("as-iframe-ready")}),50)}));else{var c=function(){n.iframeReady||(n.iframeReady=!0,r.classList.add("as-iframe-ready"),a())};this.fallbackTimer=setTimeout(c,3e3),this.resizeListener=function(t){if(t.origin===o&&(n.resizeIframe(t),!n.iframeReady)){var i=void 0;try{var r=JSON.parse(t.data);i=null==r?void 0:r.event}catch(e){}i===e.AuthsignalWindowMessage.AUTHSIGNAL_READY&&(n.fallbackTimer&&(clearTimeout(n.fallbackTimer),n.fallbackTimer=null),c())}},window.addEventListener("message",this.resizeListener)}},t.prototype.close=function(){var e=this;if(!this.popup||!this.containerEl||!this.contentEl)throw new Error("Popup is not initialized");this.containerEl.classList.remove("as-popup-visible"),this.containerEl.classList.add("as-popup-closing");var t=!1,n=function(){var n;t||(t=!0,null===(n=e.popup)||void 0===n||n.hide())};this.contentEl.addEventListener("transitionend",n,{once:!0}),setTimeout(n,150)},t.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},t.prototype.resizeIframe=function(e){this.iframeEl&&e.data.height&&(this.iframeEl.style.height=e.data.height+"px")},t}(),ue=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/totp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/totp"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),de=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired,o=e.enableLogging;this.cache=M.shared,this.enableLogging=!1,this.enableLogging=o,this.api=new ue({baseUrl:t,tenantId:n,onTokenExpired:i})}return e.prototype.enroll=function(){return u(this,void 0,void 0,(function(){return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,O({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),pe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.email;return d(this,(function(e){switch(e.label){case 0:return t={email:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-otp"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-otp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/email-otp"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ge=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired,o=e.enableLogging;this.cache=M.shared,this.enableLogging=!1,this.enableLogging=o,this.api=new pe({baseUrl:t,tenantId:n,onTokenExpired:i})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.email;return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,O({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),fe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.phoneNumber;return d(this,(function(e){switch(e.label){case 0:return t={phoneNumber:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/sms"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/sms"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/sms"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ve=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired,o=e.enableLogging;this.cache=M.shared,this.enableLogging=!1,this.enableLogging=o,this.api=new fe({baseUrl:t,tenantId:n,onTokenExpired:i})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.phoneNumber;return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,O({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),be=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.email;return d(this,(function(e){switch(e.label){case 0:return t={email:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/email-magic-link"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-magic-link"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.checkVerificationStatus=function(e){return u(this,arguments,void 0,(function(e){var t,n=this,i=e.token;return d(this,(function(e){switch(e.label){case 0:return t=function(){return u(n,void 0,void 0,(function(){var e,n=this;return d(this,(function(o){switch(o.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/email-magic-link/finalize"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,o.sent().json()];case 2:return N({response:e=o.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return u(n,void 0,void 0,(function(){var n;return d(this,(function(i){switch(i.label){case 0:return n=e,[4,t()];case 1:return n.apply(void 0,[i.sent()]),[2]}}))}))}),1e3)}))]}}))}))},[4,t()];case 1:return[2,e.sent()]}}))}))},e}(),ye=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired,o=e.enableLogging;this.cache=M.shared,this.enableLogging=!1,this.enableLogging=o,this.api=new be({baseUrl:t,tenantId:n,onTokenExpired:i})}return e.prototype.enroll=function(e){return u(this,arguments,void 0,(function(e){var t=e.email;return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.checkVerificationStatus=function(){return u(this,void 0,void 0,(function(){var e;return d(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,O({response:e,enableLogging:this.enableLogging})]}}))}))},e}(),me=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.registrationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/registration-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptions=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/authentication-options"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,i=e.registrationCredential;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify(i)})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token,i=e.authenticationCredential;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/security-key"),{method:"POST",headers:U({token:n,tenantId:this.tenantId}),body:JSON.stringify(i)})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),ke=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired,o=e.enableLogging;this.cache=M.shared,this.enableLogging=!1,this.api=new me({baseUrl:t,tenantId:n,onTokenExpired:i}),this.enableLogging=o}return e.prototype.enroll=function(){return u(this,arguments,void 0,(function(e){var t,n,i,o,r,s=(void 0===e?{}:e).hints;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?(t={token:this.cache.token},[4,this.api.registrationOptions(t)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(n=e.sent()))return[2,L({errorResponse:n,enableLogging:this.enableLogging})];e.label=2;case 2:return e.trys.push([2,5,,6]),[4,T({optionsJSON:s?l(l({},n),{hints:s}):n})];case 3:return i=e.sent(),[4,this.api.addAuthenticator({registrationCredential:i,token:this.cache.token})];case 4:return"error"in(o=e.sent())?[2,L({errorResponse:o,enableLogging:this.enableLogging})]:(o.accessToken&&(this.cache.token=o.accessToken),[2,{data:{token:o.accessToken,registrationResponse:i}}]);case 5:throw _(r=e.sent()),r;case 6:return[2]}}))}))},e.prototype.verify=function(){return u(this,void 0,void 0,(function(){var e,t,n,i,o;return d(this,(function(r){switch(r.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=r.sent()))return[2,L({errorResponse:e,enableLogging:this.enableLogging})];r.label=2;case 2:return r.trys.push([2,5,,6]),[4,S({optionsJSON:e})];case 3:return t=r.sent(),[4,this.api.verify({authenticationCredential:t,token:this.cache.token})];case 4:return"error"in(n=r.sent())?[2,L({errorResponse:n,enableLogging:this.enableLogging})]:(n.accessToken&&(this.cache.token=n.accessToken),i=n.accessToken,[2,{data:{isVerified:n.isVerified,token:i,authenticationResponse:t}}]);case 5:throw _(o=r.sent()),o;case 6:return[2]}}))}))},e}(),we=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.baseUrl=t}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.action,i=e.token,o=e.custom;return d(this,(function(e){switch(e.label){case 0:return t={action:n,custom:o},[4,fetch("".concat(this.baseUrl,"/client/challenge/qr-code"),{method:"POST",headers:U({tenantId:this.tenantId,token:i}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.challengeId,i=e.deviceCode;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:n,deviceCode:i},[4,fetch("".concat(this.baseUrl,"/client/verify/qr-code"),{method:"POST",headers:U({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e}(),Ee=function(){},Ie=54e4,Te=3e3,Ce=function(e){function t(t){var n=t.baseUrl,i=t.tenantId,o=t.enableLogging,r=e.call(this)||this;return r.cache=M.shared,r.enableLogging=!1,r.enableLogging=o,r.api=new we({baseUrl:n,tenantId:i}),r}return c(t,e),t.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t,n,i,o,r,s=this;return d(this,(function(a){switch(a.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:e.action,custom:e.custom})];case 1:return t=a.sent(),(n=O({response:t,enableLogging:this.enableLogging})).data&&(this.currentChallengeParams=e,this.clearPolling(),i=e.pollInterval||Te,o=e.refreshInterval||Ie,n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:e.onStateChange,pollInterval:i}),e.onRefresh&&(r=e.onRefresh,this.startRefreshTimer((function(){return s.performRefresh({action:e.action,custom:e.custom,onRefresh:r,onStateChange:e.onStateChange,pollInterval:i})}),o))),[2,n]}}))}))},t.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t,n,i,o,r,s,a,c,l,h=this,u=(void 0===e?{}:e).custom;return d(this,(function(e){switch(e.label){case 0:return this.currentChallengeParams?[4,this.api.challenge({token:this.cache.token||void 0,action:this.currentChallengeParams.action,custom:u||this.currentChallengeParams.custom})]:[2];case 1:return t=e.sent(),(n=O({response:t,enableLogging:this.enableLogging})).data&&(this.clearPolling(),this.currentChallengeParams.onRefresh&&this.currentChallengeParams.onRefresh(n.data.challengeId,n.data.expiresAt),n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:this.currentChallengeParams.onStateChange,pollInterval:this.currentChallengeParams.pollInterval||Te}),this.currentChallengeParams.onRefresh&&(i=this.currentChallengeParams.refreshInterval||Ie,o=this.currentChallengeParams,r=o.action,s=o.custom,a=o.onRefresh,c=o.onStateChange,l=o.pollInterval,this.startRefreshTimer((function(){return h.performRefresh({action:r,custom:s,onRefresh:a,onStateChange:c,pollInterval:l||Te})}),i))),[2]}}))}))},t.prototype.disconnect=function(){this.clearPolling(),this.clearRefreshTimer(),this.currentChallengeParams=void 0},t.prototype.startRefreshTimer=function(e,t){var n=this;this.clearRefreshTimer(),this.refreshTimeout=setTimeout((function(){return u(n,void 0,void 0,(function(){return d(this,(function(n){switch(n.label){case 0:return[4,e()];case 1:return n.sent(),this.startRefreshTimer(e,t),[2]}}))}))}),t)},t.prototype.clearRefreshTimer=function(){this.refreshTimeout&&(clearTimeout(this.refreshTimeout),this.refreshTimeout=void 0)},t.prototype.performRefresh=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.action,o=e.custom,r=e.onRefresh,s=e.onStateChange,a=e.pollInterval;return d(this,(function(e){switch(e.label){case 0:return[4,this.api.challenge({token:this.cache.token||void 0,action:i,custom:o})];case 1:return t=e.sent(),(n=O({response:t,enableLogging:this.enableLogging})).data&&(this.clearPolling(),r(n.data.challengeId,n.data.expiresAt),n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:s,pollInterval:a})),[2]}}))}))},t.prototype.startPolling=function(e){var t=this,n=e.challengeId,i=e.deviceCode,o=e.onStateChange,r=e.pollInterval;this.pollingInterval=setInterval((function(){return u(t,void 0,void 0,(function(){var e,t;return d(this,(function(r){switch(r.label){case 0:return[4,this.api.verify({challengeId:n,deviceCode:i})];case 1:return e=r.sent(),(t=O({response:e,enableLogging:this.enableLogging})).data&&(t.data.isVerified?(o("approved",t.data.token),this.clearPolling()):t.data.isClaimed&&!t.data.isConsumed?o("claimed"):t.data.isClaimed&&t.data.isConsumed&&(o("rejected"),this.clearPolling())),[2]}}))}))}),r)},t.prototype.clearPolling=function(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0)},t}(Ee),Ae="CHALLENGE_CREATED_HANDLER",Se=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.ws=null,this.messageHandlers=new Map,this.options=null,this.refreshInterval=null,this.tokenCache=M.shared;var i=t.replace("https://","wss://").replace("http://","ws://").replace("v1","ws-v1-challenge").replace("api","api-ws");this.baseUrl=i,this.tenantId=n}return e.prototype.connect=function(){return u(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return[2,new Promise((function(t,n){try{var i=["authsignal-ws"];e.tokenCache.token?i.push("x.authsignal.token.".concat(e.tokenCache.token)):i.push("x.authsignal.tenant.".concat(e.tenantId)),e.ws=new WebSocket(e.baseUrl,i),e.ws.onopen=function(){t()},e.ws.onerror=function(e){n(new Error("WebSocket connection error: ".concat(e)))},e.ws.onclose=function(){e.refreshInterval&&(clearInterval(e.refreshInterval),e.refreshInterval=null),e.messageHandlers.clear(),e.ws=null},e.ws.onmessage=function(t){try{var n=JSON.parse(t.data);e.handleMessage(n)}catch(e){console.error("Failed to parse WebSocket message:",e)}}}catch(e){n(e)}}))]}))}))},e.prototype.handleMessage=function(e){if("CHALLENGE_CREATED"===e.type){if(!(t=this.messageHandlers.get(Ae)))throw new Error("Challenge created handler not found");t(e)}else if("STATE_CHANGE"===e.type){var t;(t=this.messageHandlers.get(e.data.challengeId))&&t(e)}},e.prototype.createQrCodeChallenge=function(e){return u(this,void 0,void 0,(function(){var t=this;return d(this,(function(n){switch(n.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:n.sent(),n.label=2;case 2:return this.refreshInterval&&clearInterval(this.refreshInterval),this.options=e,[2,new Promise((function(n,i){t.messageHandlers.set(Ae,(function(i){if("CHALLENGE_CREATED"===i.type){var o=i;t.messageHandlers.delete(Ae),t.monitorChallengeState(o.data.challengeId,e),t.startRefreshCycle(o.data.challengeId,e),n({challengeId:o.data.challengeId,expiresAt:o.data.expiresAt,state:o.data.state})}})),t.sendChallengeRequest(e).catch(i)}))]}}))}))},e.prototype.monitorChallengeState=function(e,t){var n=this;this.messageHandlers.set(e,(function(i){var o;if("STATE_CHANGE"===i.type){var r=i;null===(o=t.onStateChange)||void 0===o||o.call(t,r.data.state,r.data.accessToken),"approved"!==r.data.state&&"rejected"!==r.data.state||n.messageHandlers.delete(e)}}))},e.prototype.startRefreshCycle=function(e,t){var n=this,i=t.refreshInterval||54e4,o=e;this.refreshInterval=setInterval((function(){return u(n,void 0,void 0,(function(){var e,n,i;return d(this,(function(r){switch(r.label){case 0:this.messageHandlers.delete(o),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.createQrCodeChallenge(t)];case 2:return e=r.sent(),o=e.challengeId,null===(i=t.onRefresh)||void 0===i||i.call(t,e.challengeId,e.expiresAt),[3,4];case 3:return n=r.sent(),console.error("Failed to refresh QR code challenge:",n),this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=null),[3,4];case 4:return[2]}}))}))}),i)},e.prototype.sendChallengeRequest=function(e){return u(this,void 0,void 0,(function(){return d(this,(function(t){switch(t.label){case 0:return this.ws&&this.ws.readyState===WebSocket.OPEN?[3,2]:[4,this.connect()];case 1:t.sent(),t.label=2;case 2:if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket connection could not be established");return this.sendMessage({type:"CREATE_CHALLENGE",data:{challengeType:"QR_CODE",actionCode:e.action,custom:e.custom}}),[2]}}))}))},e.prototype.sendMessage=function(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");this.ws.send(JSON.stringify(e))},e.prototype.refreshQrCodeChallenge=function(e){return u(this,arguments,void 0,(function(e){var t,n,i,o=e.custom;return d(this,(function(e){switch(e.label){case 0:if(!this.options)throw new Error("Call createQrCodeChallenge first");return[4,this.createQrCodeChallenge(l(l({},this.options),void 0!==o&&{custom:o}))];case 1:return t=e.sent(),null===(i=(n=this.options).onRefresh)||void 0===i||i.call(n,t.challengeId,t.expiresAt),[2,t]}}))}))},e.prototype.disconnect=function(){this.ws&&this.ws.close()},e}(),Re=function(e){function t(t){var n=t.baseUrl,i=t.tenantId,o=t.enableLogging,r=e.call(this)||this;return r.cache=M.shared,r.enableLogging=!1,r.enableLogging=o,r.wsClient=new Se({baseUrl:n,tenantId:i}),r}return c(t,e),t.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return[4,this.wsClient.createQrCodeChallenge({token:this.cache.token||void 0,action:e.action,custom:e.custom,refreshInterval:e.refreshInterval,onRefresh:e.onRefresh,onStateChange:e.onStateChange})];case 1:return[2,{data:{challengeId:(t=n.sent()).challengeId,expiresAt:t.expiresAt}}]}}))}))},t.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return d(this,(function(e){switch(e.label){case 0:return[4,this.wsClient.refreshQrCodeChallenge({custom:t})];case 1:return e.sent(),[2]}}))}))},t.prototype.disconnect=function(){this.wsClient.disconnect()},t}(Ee),Le=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.enableLogging;this.handler=null,this.enableLogging=!1,this.baseUrl=t,this.tenantId=n,this.enableLogging=i}return e.prototype.challenge=function(e){return u(this,void 0,void 0,(function(){var t,n,i;return d(this,(function(o){return t=e.polling,n=void 0!==t&&t,i=h(e,["polling"]),this.handler&&this.handler.disconnect(),this.handler=n?new Ce({baseUrl:this.baseUrl,tenantId:this.tenantId,enableLogging:this.enableLogging}):new Re({baseUrl:this.baseUrl,tenantId:this.tenantId,enableLogging:this.enableLogging}),[2,this.handler.challenge(i)]}))}))},e.prototype.refresh=function(){return u(this,arguments,void 0,(function(e){var t=(void 0===e?{}:e).custom;return d(this,(function(e){if(!this.handler)throw new Error("challenge() must be called before refresh()");return[2,this.handler.refresh({custom:t})]}))}))},e.prototype.disconnect=function(){this.handler&&(this.handler.disconnect(),this.handler=null)},e}(),Oe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.action,o=e.token;return d(this,(function(e){switch(e.label){case 0:return t={action:i},[4,fetch("".concat(this.baseUrl,"/client/challenge/push"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.challengeId,o=e.token;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:i},[4,fetch("".concat(this.baseUrl,"/client/verify/push"),{method:"POST",headers:U({token:o,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),_e=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired,o=e.enableLogging;this.cache=M.shared,this.enableLogging=!1,this.enableLogging=o,this.api=new Oe({baseUrl:t,tenantId:n,onTokenExpired:i})}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t=e.action;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({action:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t=e.challengeId;return d(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({challengeId:t,token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e}(),xe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=i}return e.prototype.challenge=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.token;return d(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/whatsapp"),{method:"POST",headers:U({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return N({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n,i=e.token,o=e.code;return d(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/whatsapp"),{method:"POST",headers:U({token:i,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return N({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),Pe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,i=e.onTokenExpired,o=e.enableLogging;this.cache=M.shared,this.enableLogging=!1,this.enableLogging=o,this.api=new xe({baseUrl:t,tenantId:n,onTokenExpired:i})}return e.prototype.challenge=function(){return u(this,void 0,void 0,(function(){return d(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,O({response:e.sent(),enableLogging:this.enableLogging})]}}))}))},e.prototype.verify=function(e){return u(this,arguments,void 0,(function(e){var t,n=e.code;return d(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,O({response:t,enableLogging:this.enableLogging})]}}))}))},e}(),Ue="4a08uqve",Ne=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,i=void 0===n?"__as_aid":n,o=e.baseUrl,r=void 0===o?"https://api.authsignal.com/v1":o,a=e.tenantId,c=e.onTokenExpired,l=e.enableLogging,h=void 0!==l&&l;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.enableLogging=!1,this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=i,!a)throw new Error("tenantId is required");var u,d=(u=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(u).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;d?this.anonymousId=d:(this.anonymousId=s(),R({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.enableLogging=h,this.passkey=new G({tenantId:a,baseUrl:r,anonymousId:this.anonymousId,onTokenExpired:c,enableLogging:this.enableLogging}),this.totp=new de({tenantId:a,baseUrl:r,onTokenExpired:c,enableLogging:this.enableLogging}),this.email=new ge({tenantId:a,baseUrl:r,onTokenExpired:c,enableLogging:this.enableLogging}),this.emailML=new ye({tenantId:a,baseUrl:r,onTokenExpired:c,enableLogging:this.enableLogging}),this.sms=new ve({tenantId:a,baseUrl:r,onTokenExpired:c,enableLogging:this.enableLogging}),this.securityKey=new ke({tenantId:a,baseUrl:r,onTokenExpired:c,enableLogging:this.enableLogging}),this.qrCode=new Le({tenantId:a,baseUrl:r,enableLogging:this.enableLogging}),this.push=new _e({tenantId:a,baseUrl:r,onTokenExpired:c,enableLogging:this.enableLogging}),this.whatsapp=new Pe({tenantId:a,baseUrl:r,onTokenExpired:c,enableLogging:this.enableLogging})}return t.prototype.setToken=function(e){M.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,R({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(Ue,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(Ue,"&session_id=").concat(t),i=document.createElement("script");i.src=n,i.async=!1,i.id="as_adv_profile",document.head.appendChild(i);var o=document.createElement("noscript");o.setAttribute("id","as_adv_profile_pixel"),o.setAttribute("aria-hidden","true");var r=document.createElement("iframe"),a=e?"".concat(e,"/fp/tags?org_id=").concat(Ue,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(Ue,"&session_id=").concat(t);r.setAttribute("id","as_adv_profile_pixel"),r.setAttribute("src",a),r.setAttribute("style","width: 100px; height: 100px; border: 0; position: absolute; top: -5000px;"),o&&(o.appendChild(r),document.body.prepend(o))},t.prototype.launchWithRedirect=function(e){window.location.href=e},t.prototype.launchWithPopup=function(t,n){var i=n.popupOptions,o=n.onError,r=new he({width:null==i?void 0:i.width,height:null==i?void 0:i.height,isClosable:null==i?void 0:i.isClosable}),s="".concat(t,"&mode=popup"),a=new URL(t).origin;return r.show({url:s,expectedOrigin:a}),new Promise((function(t){var n=void 0,i=function(t){if(t.origin===a){var i=null;try{i=JSON.parse(t.data)}catch(e){}(null==i?void 0:i.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_API_ERROR&&(null==o||o({errorCode:i.errorCode,statusCode:i.statusCode})),(null==i?void 0:i.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n=i.token,r.close())}};r.on("hide",(function(){window.removeEventListener("message",i),t({token:n})})),window.addEventListener("message",i,!1)}))},t.prototype.launchWithWindow=function(t,n){var i=n.windowOptions,o=n.onError,r=new F,s="".concat(t,"&mode=popup"),a=new URL(t).origin;return r.show({url:s,width:null==i?void 0:i.width,height:null==i?void 0:i.height}),new Promise((function(t){var n=function(i){if(i.origin===a){var s=null;try{s=JSON.parse(i.data)}catch(e){}(null==s?void 0:s.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_API_ERROR&&(null==o||o({errorCode:s.errorCode,statusCode:s.statusCode})),(null==s?void 0:s.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(window.removeEventListener("message",n),r.close(),t({token:s.token}))}};window.addEventListener("message",n,!1)}))},t}();return e.Authsignal=Ne,e.WebAuthnError=k,e.Whatsapp=Pe,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
@@ -0,0 +1,14 @@
1
+ type SignalAllAcceptedCredentialsParams = {
2
+ rpId: string;
3
+ userId: string;
4
+ credentialIds: string[];
5
+ };
6
+ type SignalUnknownCredentialParams = {
7
+ rpId: string;
8
+ credentialId: string;
9
+ };
10
+ export declare function isSignalAllAcceptedSupported(): boolean;
11
+ export declare function isSignalUnknownCredentialSupported(): boolean;
12
+ export declare function signalAllAcceptedCredentials({ rpId, userId, credentialIds }: SignalAllAcceptedCredentialsParams, enableLogging: boolean): Promise<void>;
13
+ export declare function signalUnknownCredential({ rpId, credentialId }: SignalUnknownCredentialParams, enableLogging: boolean): Promise<void>;
14
+ export {};
package/dist/passkey.d.ts CHANGED
@@ -17,6 +17,7 @@ type SignUpParams = {
17
17
  hints?: PublicKeyCredentialHint[];
18
18
  useAutoRegister?: boolean;
19
19
  useCookies?: boolean;
20
+ syncCredentials?: boolean;
20
21
  };
21
22
  type SignUpResponse = {
22
23
  token?: string;
@@ -29,6 +30,7 @@ type SignInParams = {
29
30
  token?: string;
30
31
  useCookies?: boolean;
31
32
  onVerificationStarted?: () => unknown;
33
+ syncCredentials?: boolean;
32
34
  };
33
35
  type SignInResponse = {
34
36
  isVerified: boolean;
@@ -46,12 +48,15 @@ export declare class Passkey {
46
48
  private cache;
47
49
  private enableLogging;
48
50
  constructor({ baseUrl, tenantId, anonymousId, onTokenExpired, enableLogging }: PasskeyOptions);
49
- signUp({ username, displayName, token, authenticatorAttachment, hints, useAutoRegister, useCookies, }: SignUpParams): Promise<AuthsignalResponse<SignUpResponse>>;
51
+ signUp({ username, displayName, token, authenticatorAttachment, hints, useAutoRegister, useCookies, syncCredentials, }: SignUpParams): Promise<AuthsignalResponse<SignUpResponse>>;
50
52
  signIn(params?: SignInParams): Promise<AuthsignalResponse<SignInResponse>>;
51
53
  isAvailableOnDevice({ userId }: {
52
54
  userId: string;
53
55
  }): Promise<boolean>;
54
56
  private storeCredentialAgainstDevice;
55
57
  private doesBrowserSupportConditionalCreate;
58
+ private getAuthOptionsRpId;
59
+ private syncPasskeysWithCredentialManager;
60
+ private removeCredentialFromLocalCache;
56
61
  }
57
62
  export {};
package/dist/types.d.ts CHANGED
@@ -70,7 +70,8 @@ export type AuthsignalOptions = {
70
70
  };
71
71
  export declare enum AuthsignalWindowMessage {
72
72
  AUTHSIGNAL_CLOSE_POPUP = "AUTHSIGNAL_CLOSE_POPUP",
73
- AUTHSIGNAL_API_ERROR = "AUTHSIGNAL_API_ERROR"
73
+ AUTHSIGNAL_API_ERROR = "AUTHSIGNAL_API_ERROR",
74
+ AUTHSIGNAL_READY = "AUTHSIGNAL_READY"
74
75
  }
75
76
  export type AuthsignalWindowMessageData = {
76
77
  event: AuthsignalWindowMessage;
@@ -86,7 +87,8 @@ export declare enum ErrorCode {
86
87
  expired_token = "expired_token",
87
88
  network_error = "network_error",
88
89
  too_many_requests = "too_many_requests",
89
- invalid_credential = "invalid_credential"
90
+ invalid_credential = "invalid_credential",
91
+ unknown_credential = "unknown_credential"
90
92
  }
91
93
  export type AuthsignalResponse<T> = {
92
94
  data?: T;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authsignal/browser",
3
- "version": "1.15.0",
3
+ "version": "1.17.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -29,7 +29,8 @@
29
29
  "typecheck": "tsc",
30
30
  "clean": "rm -rf ./dist",
31
31
  "lint": "eslint \"{cli,config,src,test}/**/*.ts\"",
32
- "build": "rollup -c rollup.config.js"
32
+ "build": "rollup -c rollup.config.js",
33
+ "test": "vitest run"
33
34
  },
34
35
  "dependencies": {
35
36
  "@fingerprintjs/fingerprintjs": "^3.3.6",
@@ -48,10 +49,12 @@
48
49
  "eslint": "^8.24.0",
49
50
  "eslint-config-prettier": "^8.5.0",
50
51
  "eslint-plugin-prettier": "^4.2.1",
52
+ "jsdom": "^29.0.0",
51
53
  "prettier": "^2.7.1",
52
54
  "rollup": "^2.79.2",
53
55
  "tslib": "^2.4.0",
54
- "typescript": "^5.6.2"
56
+ "typescript": "^5.6.2",
57
+ "vitest": "^4.1.0"
55
58
  },
56
59
  "files": [
57
60
  "dist"