@authsignal/browser 1.7.0 → 1.9.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.
@@ -7,7 +7,7 @@ export declare class PushApiClient {
7
7
  challenge({ action }: {
8
8
  action: string;
9
9
  }): Promise<PushChallengeResponse | ErrorResponse>;
10
- verify({ challengeId, }: {
10
+ verify({ challengeId }: {
11
11
  challengeId: string;
12
12
  }): Promise<PushVerifyResponse | ErrorResponse>;
13
13
  }
@@ -4,8 +4,10 @@ export declare class QrCodeApiClient {
4
4
  tenantId: string;
5
5
  baseUrl: string;
6
6
  constructor({ baseUrl, tenantId }: ApiClientOptions);
7
- challenge({ action }: {
7
+ challenge({ action, token, custom, }: {
8
8
  action: string;
9
+ token?: string;
10
+ custom?: Record<string, unknown>;
9
11
  }): Promise<QrCodeChallengeResponse | ErrorResponse>;
10
12
  verify({ challengeId, deviceCode, }: {
11
13
  challengeId: string;
@@ -1,6 +1,10 @@
1
1
  export type QrCodeChallengeResponse = {
2
2
  challengeId: string;
3
- deviceCode: string;
3
+ expiresAt: string;
4
+ /**
5
+ * Only available in polling mode
6
+ */
7
+ deviceCode?: string;
4
8
  };
5
9
  export type QrCodeVerifyResponse = {
6
10
  isClaimed: boolean;
@@ -0,0 +1,41 @@
1
+ export type WebSocketMessageType = "CREATE_CHALLENGE" | "CHALLENGE_CREATED" | "STATE_CHANGE";
2
+ export type ChallengeState = "unclaimed" | "claimed" | "approved" | "rejected";
3
+ export interface CreateChallengeMessage {
4
+ type: "CREATE_CHALLENGE";
5
+ data: {
6
+ challengeType: "QR_CODE";
7
+ actionCode: string;
8
+ custom?: Record<string, unknown>;
9
+ };
10
+ }
11
+ export interface ChallengeCreatedMessage {
12
+ type: "CHALLENGE_CREATED";
13
+ data: {
14
+ challengeId: string;
15
+ challengeType: "QR_CODE";
16
+ expiresAt: string;
17
+ state: ChallengeState;
18
+ };
19
+ }
20
+ export interface StateChangeMessage {
21
+ type: "STATE_CHANGE";
22
+ data: {
23
+ challengeId: string;
24
+ state: ChallengeState;
25
+ accessToken?: string;
26
+ };
27
+ }
28
+ export type WebSocketMessage = CreateChallengeMessage | ChallengeCreatedMessage | StateChangeMessage;
29
+ export interface WebSocketQrCodeOptions {
30
+ token?: string;
31
+ action: string;
32
+ custom?: Record<string, unknown>;
33
+ refreshInterval?: number;
34
+ onRefresh?: (challengeId: string, expiresAt: string) => void;
35
+ onStateChange?: (state: ChallengeState, accessToken?: string) => void;
36
+ }
37
+ export interface WebSocketQrCodeResponse {
38
+ challengeId: string;
39
+ expiresAt: string;
40
+ state: ChallengeState;
41
+ }
@@ -0,0 +1,25 @@
1
+ import { WebSocketQrCodeOptions, WebSocketQrCodeResponse } from "./types/websocket";
2
+ export declare class WebSocketClient {
3
+ private ws;
4
+ private baseUrl;
5
+ private tenantId;
6
+ private messageHandlers;
7
+ private options;
8
+ private refreshInterval;
9
+ private tokenCache;
10
+ constructor({ baseUrl, tenantId }: {
11
+ baseUrl: string;
12
+ tenantId: string;
13
+ });
14
+ connect(): Promise<void>;
15
+ private handleMessage;
16
+ createQrCodeChallenge(options: WebSocketQrCodeOptions): Promise<WebSocketQrCodeResponse>;
17
+ private monitorChallengeState;
18
+ private startRefreshCycle;
19
+ private sendChallengeRequest;
20
+ private sendMessage;
21
+ refreshQrCodeChallenge({ custom }: {
22
+ custom?: Record<string, unknown>;
23
+ }): Promise<WebSocketQrCodeResponse>;
24
+ disconnect(): void;
25
+ }
package/dist/index.d.ts CHANGED
@@ -4,3 +4,4 @@ export type { Authenticator, VerificationMethod, EnrollResponse, ChallengeRespon
4
4
  export type { EnrollTotpResponse } from "./api/types/totp";
5
5
  export type { QrCodeChallengeResponse, QrCodeVerifyResponse } from "./api/types/qr-code";
6
6
  export type { PushChallengeResponse, PushVerifyResponse } from "./api/types/push";
7
+ export type { WebSocketQrCodeOptions, WebSocketQrCodeResponse, ChallengeState } from "./api/types/websocket";
package/dist/index.js CHANGED
@@ -77,6 +77,22 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
77
77
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
78
78
  PERFORMANCE OF THIS SOFTWARE.
79
79
  ***************************************************************************** */
80
+ /* global Reflect, Promise */
81
+
82
+ var extendStatics = function(d, b) {
83
+ extendStatics = Object.setPrototypeOf ||
84
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
85
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
86
+ return extendStatics(d, b);
87
+ };
88
+
89
+ function __extends(d, b) {
90
+ if (typeof b !== "function" && b !== null)
91
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
92
+ extendStatics(d, b);
93
+ function __() { this.constructor = d; }
94
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
95
+ }
80
96
 
81
97
  var __assign = function() {
82
98
  __assign = Object.assign || function __assign(t) {
@@ -2574,14 +2590,14 @@ var QrCodeApiClient = /** @class */ (function () {
2574
2590
  QrCodeApiClient.prototype.challenge = function (_a) {
2575
2591
  return __awaiter(this, arguments, void 0, function (_b) {
2576
2592
  var body, response, responseJson;
2577
- var action = _b.action;
2593
+ var action = _b.action, token = _b.token, custom = _b.custom;
2578
2594
  return __generator(this, function (_c) {
2579
2595
  switch (_c.label) {
2580
2596
  case 0:
2581
- body = { action: action };
2597
+ body = { action: action, custom: custom };
2582
2598
  return [4 /*yield*/, fetch("".concat(this.baseUrl, "/client/challenge/qr-code"), {
2583
2599
  method: "POST",
2584
- headers: buildHeaders({ tenantId: this.tenantId }),
2600
+ headers: buildHeaders({ tenantId: this.tenantId, token: token }),
2585
2601
  body: JSON.stringify(body),
2586
2602
  })];
2587
2603
  case 1:
@@ -2620,39 +2636,523 @@ var QrCodeApiClient = /** @class */ (function () {
2620
2636
  return QrCodeApiClient;
2621
2637
  }());
2622
2638
 
2623
- var QrCode = /** @class */ (function () {
2624
- function QrCode(_a) {
2639
+ var BaseQrHandler = /** @class */ (function () {
2640
+ function BaseQrHandler() {
2641
+ }
2642
+ return BaseQrHandler;
2643
+ }());
2644
+
2645
+ var DEFAULT_REFRESH_INTERVAL = 9 * 60 * 1000;
2646
+ var DEFAULT_POLL_INTERVAL = 5 * 1000;
2647
+ var RestQrHandler = /** @class */ (function (_super) {
2648
+ __extends(RestQrHandler, _super);
2649
+ function RestQrHandler(_a) {
2625
2650
  var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
2626
- this.api = new QrCodeApiClient({ baseUrl: baseUrl, tenantId: tenantId });
2651
+ var _this = _super.call(this) || this;
2652
+ _this.cache = TokenCache.shared;
2653
+ _this.api = new QrCodeApiClient({ baseUrl: baseUrl, tenantId: tenantId });
2654
+ return _this;
2627
2655
  }
2628
- QrCode.prototype.challenge = function (_a) {
2656
+ RestQrHandler.prototype.challenge = function (params) {
2657
+ return __awaiter(this, void 0, void 0, function () {
2658
+ var response, result, pollInterval_1, refreshInterval, onRefresh_1;
2659
+ var _this = this;
2660
+ return __generator(this, function (_a) {
2661
+ switch (_a.label) {
2662
+ case 0: return [4 /*yield*/, this.api.challenge({
2663
+ token: this.cache.token || undefined,
2664
+ action: params.action,
2665
+ custom: params.custom,
2666
+ })];
2667
+ case 1:
2668
+ response = _a.sent();
2669
+ result = handleApiResponse(response);
2670
+ if (result.data) {
2671
+ this.currentChallengeParams = params;
2672
+ this.clearPolling();
2673
+ pollInterval_1 = params.pollInterval || DEFAULT_POLL_INTERVAL;
2674
+ refreshInterval = params.refreshInterval || DEFAULT_REFRESH_INTERVAL;
2675
+ if (result.data.deviceCode) {
2676
+ this.startPolling({
2677
+ challengeId: result.data.challengeId,
2678
+ deviceCode: result.data.deviceCode,
2679
+ onStateChange: params.onStateChange,
2680
+ pollInterval: pollInterval_1,
2681
+ });
2682
+ }
2683
+ if (params.onRefresh) {
2684
+ onRefresh_1 = params.onRefresh;
2685
+ this.startRefreshTimer(function () {
2686
+ return _this.performRefresh({
2687
+ action: params.action,
2688
+ custom: params.custom,
2689
+ onRefresh: onRefresh_1,
2690
+ onStateChange: params.onStateChange,
2691
+ pollInterval: pollInterval_1,
2692
+ });
2693
+ }, refreshInterval);
2694
+ }
2695
+ }
2696
+ return [2 /*return*/, result];
2697
+ }
2698
+ });
2699
+ });
2700
+ };
2701
+ RestQrHandler.prototype.refresh = function () {
2702
+ return __awaiter(this, arguments, void 0, function (_a) {
2703
+ var response, result, refreshInterval, _b, action_1, custom_1, onRefresh_2, onStateChange_1, pollInterval_2;
2704
+ var _this = this;
2705
+ var _c = _a === void 0 ? {} : _a, custom = _c.custom;
2706
+ return __generator(this, function (_d) {
2707
+ switch (_d.label) {
2708
+ case 0:
2709
+ if (!this.currentChallengeParams)
2710
+ return [2 /*return*/];
2711
+ return [4 /*yield*/, this.api.challenge({
2712
+ token: this.cache.token || undefined,
2713
+ action: this.currentChallengeParams.action,
2714
+ custom: custom || this.currentChallengeParams.custom,
2715
+ })];
2716
+ case 1:
2717
+ response = _d.sent();
2718
+ result = handleApiResponse(response);
2719
+ if (result.data) {
2720
+ this.clearPolling();
2721
+ if (this.currentChallengeParams.onRefresh) {
2722
+ this.currentChallengeParams.onRefresh(result.data.challengeId, result.data.expiresAt);
2723
+ }
2724
+ if (result.data.deviceCode) {
2725
+ this.startPolling({
2726
+ challengeId: result.data.challengeId,
2727
+ deviceCode: result.data.deviceCode,
2728
+ onStateChange: this.currentChallengeParams.onStateChange,
2729
+ pollInterval: this.currentChallengeParams.pollInterval || DEFAULT_POLL_INTERVAL,
2730
+ });
2731
+ }
2732
+ if (this.currentChallengeParams.onRefresh) {
2733
+ refreshInterval = this.currentChallengeParams.refreshInterval || DEFAULT_REFRESH_INTERVAL;
2734
+ _b = this.currentChallengeParams, action_1 = _b.action, custom_1 = _b.custom, onRefresh_2 = _b.onRefresh, onStateChange_1 = _b.onStateChange, pollInterval_2 = _b.pollInterval;
2735
+ this.startRefreshTimer(function () {
2736
+ return _this.performRefresh({
2737
+ action: action_1,
2738
+ custom: custom_1,
2739
+ onRefresh: onRefresh_2,
2740
+ onStateChange: onStateChange_1,
2741
+ pollInterval: pollInterval_2 || DEFAULT_POLL_INTERVAL,
2742
+ });
2743
+ }, refreshInterval);
2744
+ }
2745
+ }
2746
+ return [2 /*return*/];
2747
+ }
2748
+ });
2749
+ });
2750
+ };
2751
+ RestQrHandler.prototype.disconnect = function () {
2752
+ this.clearPolling();
2753
+ this.clearRefreshTimer();
2754
+ this.currentChallengeParams = undefined;
2755
+ };
2756
+ RestQrHandler.prototype.startRefreshTimer = function (callback, interval) {
2757
+ var _this = this;
2758
+ this.clearRefreshTimer();
2759
+ this.refreshTimeout = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
2760
+ return __generator(this, function (_a) {
2761
+ switch (_a.label) {
2762
+ case 0: return [4 /*yield*/, callback()];
2763
+ case 1:
2764
+ _a.sent();
2765
+ this.startRefreshTimer(callback, interval);
2766
+ return [2 /*return*/];
2767
+ }
2768
+ });
2769
+ }); }, interval);
2770
+ };
2771
+ RestQrHandler.prototype.clearRefreshTimer = function () {
2772
+ if (this.refreshTimeout) {
2773
+ clearTimeout(this.refreshTimeout);
2774
+ this.refreshTimeout = undefined;
2775
+ }
2776
+ };
2777
+ RestQrHandler.prototype.performRefresh = function (_a) {
2629
2778
  return __awaiter(this, arguments, void 0, function (_b) {
2630
- var response;
2631
- var action = _b.action;
2779
+ var response, result;
2780
+ var action = _b.action, custom = _b.custom, onRefresh = _b.onRefresh, onStateChange = _b.onStateChange, pollInterval = _b.pollInterval;
2632
2781
  return __generator(this, function (_c) {
2633
2782
  switch (_c.label) {
2634
- case 0: return [4 /*yield*/, this.api.challenge({ action: action })];
2783
+ case 0: return [4 /*yield*/, this.api.challenge({ token: this.cache.token || undefined, action: action, custom: custom })];
2635
2784
  case 1:
2636
2785
  response = _c.sent();
2637
- return [2 /*return*/, handleApiResponse(response)];
2786
+ result = handleApiResponse(response);
2787
+ if (result.data) {
2788
+ this.clearPolling();
2789
+ onRefresh(result.data.challengeId, result.data.expiresAt);
2790
+ if (result.data.deviceCode) {
2791
+ this.startPolling({
2792
+ challengeId: result.data.challengeId,
2793
+ deviceCode: result.data.deviceCode,
2794
+ onStateChange: onStateChange,
2795
+ pollInterval: pollInterval,
2796
+ });
2797
+ }
2798
+ }
2799
+ return [2 /*return*/];
2800
+ }
2801
+ });
2802
+ });
2803
+ };
2804
+ RestQrHandler.prototype.startPolling = function (_a) {
2805
+ var _this = this;
2806
+ var challengeId = _a.challengeId, deviceCode = _a.deviceCode, onStateChange = _a.onStateChange, pollInterval = _a.pollInterval;
2807
+ this.pollingInterval = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
2808
+ var response, result;
2809
+ return __generator(this, function (_a) {
2810
+ switch (_a.label) {
2811
+ case 0: return [4 /*yield*/, this.api.verify({ challengeId: challengeId, deviceCode: deviceCode })];
2812
+ case 1:
2813
+ response = _a.sent();
2814
+ result = handleApiResponse(response);
2815
+ if (result.data) {
2816
+ if (result.data.isVerified) {
2817
+ onStateChange("approved", result.data.token);
2818
+ this.clearPolling();
2819
+ }
2820
+ else if (result.data.isClaimed) {
2821
+ onStateChange("claimed");
2822
+ }
2823
+ }
2824
+ return [2 /*return*/];
2638
2825
  }
2639
2826
  });
2827
+ }); }, pollInterval);
2828
+ };
2829
+ RestQrHandler.prototype.clearPolling = function () {
2830
+ if (this.pollingInterval) {
2831
+ clearInterval(this.pollingInterval);
2832
+ this.pollingInterval = undefined;
2833
+ }
2834
+ };
2835
+ return RestQrHandler;
2836
+ }(BaseQrHandler));
2837
+
2838
+ var CHALLENGE_CREATED_HANDLER = "CHALLENGE_CREATED_HANDLER";
2839
+ var WebSocketClient = /** @class */ (function () {
2840
+ function WebSocketClient(_a) {
2841
+ var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
2842
+ this.ws = null;
2843
+ this.messageHandlers = new Map();
2844
+ this.options = null;
2845
+ this.refreshInterval = null;
2846
+ this.tokenCache = TokenCache.shared;
2847
+ var wsUrl = baseUrl
2848
+ .replace("https://", "wss://")
2849
+ .replace("http://", "ws://")
2850
+ .replace("v1", "ws-v1-challenge")
2851
+ .replace("api", "api-ws");
2852
+ this.baseUrl = wsUrl;
2853
+ this.tenantId = tenantId;
2854
+ }
2855
+ WebSocketClient.prototype.connect = function () {
2856
+ return __awaiter(this, void 0, void 0, function () {
2857
+ var _this = this;
2858
+ return __generator(this, function (_a) {
2859
+ return [2 /*return*/, new Promise(function (resolve, reject) {
2860
+ try {
2861
+ var protocols = ["authsignal-ws"];
2862
+ if (_this.tokenCache.token) {
2863
+ protocols.push("x.authsignal.token.".concat(_this.tokenCache.token));
2864
+ }
2865
+ else {
2866
+ protocols.push("x.authsignal.tenant.".concat(_this.tenantId));
2867
+ }
2868
+ _this.ws = new WebSocket(_this.baseUrl, protocols);
2869
+ _this.ws.onopen = function () {
2870
+ resolve();
2871
+ };
2872
+ _this.ws.onerror = function (error) {
2873
+ reject(new Error("WebSocket connection error: ".concat(error)));
2874
+ };
2875
+ _this.ws.onclose = function () {
2876
+ if (_this.refreshInterval) {
2877
+ clearInterval(_this.refreshInterval);
2878
+ _this.refreshInterval = null;
2879
+ }
2880
+ _this.messageHandlers.clear();
2881
+ _this.ws = null;
2882
+ };
2883
+ _this.ws.onmessage = function (event) {
2884
+ try {
2885
+ var message = JSON.parse(event.data);
2886
+ _this.handleMessage(message);
2887
+ }
2888
+ catch (error) {
2889
+ console.error("Failed to parse WebSocket message:", error);
2890
+ }
2891
+ };
2892
+ }
2893
+ catch (error) {
2894
+ reject(error);
2895
+ }
2896
+ })];
2897
+ });
2640
2898
  });
2641
2899
  };
2642
- QrCode.prototype.verify = function (_a) {
2900
+ WebSocketClient.prototype.handleMessage = function (message) {
2901
+ if (message.type === "CHALLENGE_CREATED") {
2902
+ var handler = this.messageHandlers.get(CHALLENGE_CREATED_HANDLER);
2903
+ if (handler) {
2904
+ handler(message);
2905
+ }
2906
+ else {
2907
+ throw new Error("Challenge created handler not found");
2908
+ }
2909
+ }
2910
+ else if (message.type === "STATE_CHANGE") {
2911
+ var handler = this.messageHandlers.get(message.data.challengeId);
2912
+ if (handler) {
2913
+ handler(message);
2914
+ }
2915
+ }
2916
+ };
2917
+ WebSocketClient.prototype.createQrCodeChallenge = function (options) {
2918
+ return __awaiter(this, void 0, void 0, function () {
2919
+ var _this = this;
2920
+ return __generator(this, function (_a) {
2921
+ switch (_a.label) {
2922
+ case 0:
2923
+ if (!(!this.ws || this.ws.readyState !== WebSocket.OPEN)) return [3 /*break*/, 2];
2924
+ return [4 /*yield*/, this.connect()];
2925
+ case 1:
2926
+ _a.sent();
2927
+ _a.label = 2;
2928
+ case 2:
2929
+ if (this.refreshInterval) {
2930
+ clearInterval(this.refreshInterval);
2931
+ }
2932
+ this.options = options;
2933
+ return [2 /*return*/, new Promise(function (resolve, reject) {
2934
+ var handler = function (message) {
2935
+ if (message.type === "CHALLENGE_CREATED") {
2936
+ var created = message;
2937
+ _this.messageHandlers.delete(CHALLENGE_CREATED_HANDLER);
2938
+ _this.monitorChallengeState(created.data.challengeId, options);
2939
+ _this.startRefreshCycle(created.data.challengeId, options);
2940
+ resolve({
2941
+ challengeId: created.data.challengeId,
2942
+ expiresAt: created.data.expiresAt,
2943
+ state: created.data.state,
2944
+ });
2945
+ }
2946
+ };
2947
+ _this.messageHandlers.set(CHALLENGE_CREATED_HANDLER, handler);
2948
+ _this.sendChallengeRequest(options).catch(reject);
2949
+ })];
2950
+ }
2951
+ });
2952
+ });
2953
+ };
2954
+ WebSocketClient.prototype.monitorChallengeState = function (challengeId, options) {
2955
+ var _this = this;
2956
+ this.messageHandlers.set(challengeId, function (message) {
2957
+ var _a;
2958
+ if (message.type === "STATE_CHANGE") {
2959
+ var stateMessage = message;
2960
+ (_a = options.onStateChange) === null || _a === void 0 ? void 0 : _a.call(options, stateMessage.data.state, stateMessage.data.accessToken);
2961
+ if (stateMessage.data.state === "approved" || stateMessage.data.state === "rejected") {
2962
+ _this.messageHandlers.delete(challengeId);
2963
+ }
2964
+ }
2965
+ });
2966
+ };
2967
+ WebSocketClient.prototype.startRefreshCycle = function (currentChallengeId, options) {
2968
+ var _this = this;
2969
+ var interval = options.refreshInterval || 9 * 60 * 1000;
2970
+ var challengeId = currentChallengeId;
2971
+ this.refreshInterval = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
2972
+ var newChallenge, error_1;
2973
+ var _a;
2974
+ return __generator(this, function (_b) {
2975
+ switch (_b.label) {
2976
+ case 0:
2977
+ this.messageHandlers.delete(challengeId);
2978
+ _b.label = 1;
2979
+ case 1:
2980
+ _b.trys.push([1, 3, , 4]);
2981
+ return [4 /*yield*/, this.createQrCodeChallenge(options)];
2982
+ case 2:
2983
+ newChallenge = _b.sent();
2984
+ challengeId = newChallenge.challengeId;
2985
+ (_a = options.onRefresh) === null || _a === void 0 ? void 0 : _a.call(options, newChallenge.challengeId, newChallenge.expiresAt);
2986
+ return [3 /*break*/, 4];
2987
+ case 3:
2988
+ error_1 = _b.sent();
2989
+ console.error("Failed to refresh QR code challenge:", error_1);
2990
+ if (this.refreshInterval) {
2991
+ clearInterval(this.refreshInterval);
2992
+ this.refreshInterval = null;
2993
+ }
2994
+ return [3 /*break*/, 4];
2995
+ case 4: return [2 /*return*/];
2996
+ }
2997
+ });
2998
+ }); }, interval);
2999
+ };
3000
+ WebSocketClient.prototype.sendChallengeRequest = function (options) {
3001
+ return __awaiter(this, void 0, void 0, function () {
3002
+ return __generator(this, function (_a) {
3003
+ switch (_a.label) {
3004
+ case 0:
3005
+ if (!(!this.ws || this.ws.readyState !== WebSocket.OPEN)) return [3 /*break*/, 2];
3006
+ return [4 /*yield*/, this.connect()];
3007
+ case 1:
3008
+ _a.sent();
3009
+ _a.label = 2;
3010
+ case 2:
3011
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
3012
+ throw new Error("WebSocket connection could not be established");
3013
+ }
3014
+ this.sendMessage({
3015
+ type: "CREATE_CHALLENGE",
3016
+ data: {
3017
+ challengeType: "QR_CODE",
3018
+ actionCode: options.action,
3019
+ custom: options.custom,
3020
+ },
3021
+ });
3022
+ return [2 /*return*/];
3023
+ }
3024
+ });
3025
+ });
3026
+ };
3027
+ WebSocketClient.prototype.sendMessage = function (message) {
3028
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
3029
+ throw new Error("WebSocket not connected");
3030
+ }
3031
+ this.ws.send(JSON.stringify(message));
3032
+ };
3033
+ WebSocketClient.prototype.refreshQrCodeChallenge = function (_a) {
2643
3034
  return __awaiter(this, arguments, void 0, function (_b) {
3035
+ var newChallenge;
3036
+ var _c, _d;
3037
+ var custom = _b.custom;
3038
+ return __generator(this, function (_e) {
3039
+ switch (_e.label) {
3040
+ case 0:
3041
+ if (!this.options) {
3042
+ throw new Error("Call createQrCodeChallenge first");
3043
+ }
3044
+ return [4 /*yield*/, this.createQrCodeChallenge(__assign(__assign({}, this.options), (custom !== undefined && { custom: custom })))];
3045
+ case 1:
3046
+ newChallenge = _e.sent();
3047
+ (_d = (_c = this.options).onRefresh) === null || _d === void 0 ? void 0 : _d.call(_c, newChallenge.challengeId, newChallenge.expiresAt);
3048
+ return [2 /*return*/, newChallenge];
3049
+ }
3050
+ });
3051
+ });
3052
+ };
3053
+ WebSocketClient.prototype.disconnect = function () {
3054
+ if (this.ws) {
3055
+ this.ws.close();
3056
+ }
3057
+ };
3058
+ return WebSocketClient;
3059
+ }());
3060
+
3061
+ var WebSocketQrHandler = /** @class */ (function (_super) {
3062
+ __extends(WebSocketQrHandler, _super);
3063
+ function WebSocketQrHandler(_a) {
3064
+ var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
3065
+ var _this = _super.call(this) || this;
3066
+ _this.cache = TokenCache.shared;
3067
+ _this.wsClient = new WebSocketClient({ baseUrl: baseUrl, tenantId: tenantId });
3068
+ return _this;
3069
+ }
3070
+ WebSocketQrHandler.prototype.challenge = function (params) {
3071
+ return __awaiter(this, void 0, void 0, function () {
2644
3072
  var response;
2645
- var challengeId = _b.challengeId, deviceCode = _b.deviceCode;
3073
+ return __generator(this, function (_a) {
3074
+ switch (_a.label) {
3075
+ case 0: return [4 /*yield*/, this.wsClient.createQrCodeChallenge({
3076
+ token: this.cache.token || undefined,
3077
+ action: params.action,
3078
+ custom: params.custom,
3079
+ refreshInterval: params.refreshInterval,
3080
+ onRefresh: params.onRefresh,
3081
+ onStateChange: params.onStateChange,
3082
+ })];
3083
+ case 1:
3084
+ response = _a.sent();
3085
+ return [2 /*return*/, {
3086
+ data: {
3087
+ challengeId: response.challengeId,
3088
+ expiresAt: response.expiresAt,
3089
+ },
3090
+ }];
3091
+ }
3092
+ });
3093
+ });
3094
+ };
3095
+ WebSocketQrHandler.prototype.refresh = function () {
3096
+ return __awaiter(this, arguments, void 0, function (_a) {
3097
+ var _b = _a === void 0 ? {} : _a, custom = _b.custom;
2646
3098
  return __generator(this, function (_c) {
2647
3099
  switch (_c.label) {
2648
- case 0: return [4 /*yield*/, this.api.verify({ challengeId: challengeId, deviceCode: deviceCode })];
3100
+ case 0: return [4 /*yield*/, this.wsClient.refreshQrCodeChallenge({ custom: custom })];
2649
3101
  case 1:
2650
- response = _c.sent();
2651
- return [2 /*return*/, handleApiResponse(response)];
3102
+ _c.sent();
3103
+ return [2 /*return*/];
3104
+ }
3105
+ });
3106
+ });
3107
+ };
3108
+ WebSocketQrHandler.prototype.disconnect = function () {
3109
+ this.wsClient.disconnect();
3110
+ };
3111
+ return WebSocketQrHandler;
3112
+ }(BaseQrHandler));
3113
+
3114
+ var QrCode = /** @class */ (function () {
3115
+ function QrCode(_a) {
3116
+ var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
3117
+ this.handler = null;
3118
+ this.baseUrl = baseUrl;
3119
+ this.tenantId = tenantId;
3120
+ }
3121
+ QrCode.prototype.challenge = function (params) {
3122
+ return __awaiter(this, void 0, void 0, function () {
3123
+ var _a, polling, challengeParams;
3124
+ return __generator(this, function (_b) {
3125
+ _a = params.polling, polling = _a === void 0 ? false : _a, challengeParams = __rest(params, ["polling"]);
3126
+ if (this.handler) {
3127
+ this.handler.disconnect();
3128
+ }
3129
+ if (polling) {
3130
+ this.handler = new RestQrHandler({ baseUrl: this.baseUrl, tenantId: this.tenantId });
3131
+ }
3132
+ else {
3133
+ this.handler = new WebSocketQrHandler({ baseUrl: this.baseUrl, tenantId: this.tenantId });
3134
+ }
3135
+ return [2 /*return*/, this.handler.challenge(challengeParams)];
3136
+ });
3137
+ });
3138
+ };
3139
+ QrCode.prototype.refresh = function () {
3140
+ return __awaiter(this, arguments, void 0, function (_a) {
3141
+ var _b = _a === void 0 ? {} : _a, custom = _b.custom;
3142
+ return __generator(this, function (_c) {
3143
+ if (!this.handler) {
3144
+ throw new Error("challenge() must be called before refresh()");
2652
3145
  }
3146
+ return [2 /*return*/, this.handler.refresh({ custom: custom })];
2653
3147
  });
2654
3148
  });
2655
3149
  };
3150
+ QrCode.prototype.disconnect = function () {
3151
+ if (this.handler) {
3152
+ this.handler.disconnect();
3153
+ this.handler = null;
3154
+ }
3155
+ };
2656
3156
  return QrCode;
2657
3157
  }());
2658
3158
 
package/dist/index.min.js CHANGED
@@ -1 +1 @@
1
- var authsignal=function(e){"use strict";let t;const n=new Uint8Array(16);function r(){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 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||r)();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(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},a.apply(this,arguments)};function c(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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((r=r.apply(e,t||[])).next())}))}function u(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[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,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function l(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 h(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,"="),o=atob(r),i=new ArrayBuffer(o.length),s=new Uint8Array(i);for(let e=0;e<o.length;e++)s[e]=o.charCodeAt(e);return i}function d(){return p.stubThis(void 0!==globalThis?.PublicKeyCredential&&"function"==typeof globalThis.PublicKeyCredential)}const p={stubThis:e=>e};function f(e){const{id:t}=e;return{...e,id:h(t),transports:e.transports}}function y(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}class b extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}}const v=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}}},m=["cross-platform","platform"];function g(e){if(e&&!(m.indexOf(e)<0))return e}async function w(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:t,useAutoRegister:n=!1}=e;if(!d())throw new Error("WebAuthn is not supported in this browser");const r={...t,challenge:h(t.challenge),user:{...t.user,id:h(t.user.id)},excludeCredentials:t.excludeCredentials?.map(f)},o={};let i;n&&(o.mediation="conditional"),o.publicKey=r,o.signal=v.createNewAbortSignal();try{i=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 b({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 b({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 b({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 b({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 b({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new b({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 b({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new b({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 b({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new b({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 b({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 b({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(!i)throw new Error("Registration was not completed");const{id:s,rawId:a,response:c,type:u}=i;let p,m,w,E;if("function"==typeof c.getTransports&&(p=c.getTransports()),"function"==typeof c.getPublicKeyAlgorithm)try{m=c.getPublicKeyAlgorithm()}catch(e){k("getPublicKeyAlgorithm()",e)}if("function"==typeof c.getPublicKey)try{const e=c.getPublicKey();null!==e&&(w=l(e))}catch(e){k("getPublicKey()",e)}if("function"==typeof c.getAuthenticatorData)try{E=l(c.getAuthenticatorData())}catch(e){k("getAuthenticatorData()",e)}return{id:s,rawId:l(a),response:{attestationObject:l(c.attestationObject),clientDataJSON:l(c.clientDataJSON),transports:p,publicKeyAlgorithm:m,publicKey:w,authenticatorData:E},type:u,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:g(i.authenticatorAttachment)}}function k(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}const E={stubThis:e=>e};async function I(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:r=!0}=e;if(!d())throw new Error("WebAuthn is not supported in this browser");let o;0!==t.allowCredentials?.length&&(o=t.allowCredentials?.map(f));const i={...t,challenge:h(t.challenge),allowCredentials:o},s={};if(n){if(!await function(){if(!d())return E.stubThis(new Promise((e=>e(!1))));const e=globalThis.PublicKeyCredential;return void 0===e?.isConditionalMediationAvailable?E.stubThis(new Promise((e=>e(!1)))):E.stubThis(e.isConditionalMediationAvailable())}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&r)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=v.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 b({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new b({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 b({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new b({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 b({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:s})}if(!a)throw new Error("Authentication was not completed");const{id:c,rawId:u,response:p,type:m}=a;let w;return p.userHandle&&(w=l(p.userHandle)),{id:c,rawId:l(u),response:{authenticatorData:l(p.authenticatorData),clientDataJSON:l(p.clientDataJSON),signature:l(p.signature),userHandle:w},type:m,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:g(a.authenticatorAttachment)}}function T(e){var t=e.name,n=e.value,r=e.expire,o=e.domain,i=e.secure,s=r===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+r;document.cookie=encodeURIComponent(t)+"="+n+"; path=/;"+s+(o?"; domain="+o:"")+(i?"; secure":"")}function S(e){var t,n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}function A(e){var t;if(e&&"object"==typeof e&&"error"in e){var n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}if(e&&"object"==typeof e&&"accessToken"in e&&"string"==typeof e.accessToken){var r=e.accessToken,o=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(e,["accessToken"]);return{data:a(a({},o),{token:r})}}return{data:e}}function O(e){var t,n;if(e instanceof b&&"ERROR_INVALID_RP_ID"===e.code){var r=(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(r,'" is invalid for this domain.\n To learn more, visit https://docs.authsignal.com/scenarios/passkeys-prebuilt-ui#defining-the-relying-party'))}}function R(e){var t=e.token,n=e.tenantId;return{"Content-Type":"application/json",Authorization:t?"Bearer ".concat(t):"Basic ".concat(window.btoa(encodeURIComponent(n)))}}function x(e){var t=e.response,n=e.onTokenExpired;"error"in t&&"expired_token"===t.errorCode&&n&&n()}e.AuthsignalWindowMessage=void 0,(e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP";var U=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.username,i=e.authenticatorAttachment;return u(this,(function(e){switch(e.label){case 0:return t=Boolean(i)?{username:o,authenticatorAttachment:i}:{username:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/registration-options"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.authenticationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.challengeId;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.addAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.challengeId,i=e.registrationCredential,s=e.conditionalCreate;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:o,registrationCredential:i,conditionalCreate:s},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.challengeId,i=e.authenticationCredential,s=e.deviceId;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:o,authenticationCredential:i,deviceId:s},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.getPasskeyAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.credentialIds;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey?credentialIds=").concat(n),{method:"GET",headers:R({tenantId:this.tenantId})})];case 1:if(!(t=e.sent()).ok)throw new Error(t.statusText);return[2,t.json()]}}))}))},e.prototype.challenge=function(e){return c(this,void 0,void 0,(function(){var t;return u(this,(function(n){switch(n.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge"),{method:"POST",headers:R({tenantId:this.tenantId}),body:JSON.stringify({action:e})})];case 1:return[4,n.sent().json()];case 2:return x({response:t=n.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),C=function(){function e(){this.token=null}return e.prototype.handleTokenNotSetError=function(){var e="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(e)),{error:"TOKEN_NOT_SET",errorDescription:e}},e.shared=new e,e}(),N=!1,_=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.anonymousId,o=e.onTokenExpired;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=C.shared,this.api=new U({baseUrl:t,tenantId:n,onTokenExpired:o}),this.anonymousId=r}return e.prototype.signUp=function(e){return c(this,arguments,void 0,(function(e){var t,n,r,o,i,s,c=e.username,l=e.displayName,h=e.token,d=e.authenticatorAttachment,p=void 0===d?"platform":d,f=e.useAutoRegister,y=void 0!==f&&f;return u(this,(function(e){switch(e.label){case 0:return(t=null!=h?h: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:c,displayName:l,token:t,authenticatorAttachment:p},[4,this.api.registrationOptions(n)];case 3:if("error"in(r=e.sent()))return[2,S(r)];e.label=4;case 4:return e.trys.push([4,7,,8]),[4,w({optionsJSON:r.options,useAutoRegister:y})];case 5:return o=e.sent(),[4,this.api.addAuthenticator({challengeId:r.challengeId,registrationCredential:o,token:t,conditionalCreate:y})];case 6:return"error"in(i=e.sent())?[2,S(i)]:(i.isVerified&&this.storeCredentialAgainstDevice(a(a({},o),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),[2,{data:{token:i.accessToken,userAuthenticator:i.userAuthenticator,registrationResponse:o}}]);case 7:throw s=e.sent(),N=!1,O(s),s;case 8:return[2]}}))}))},e.prototype.signIn=function(e){return c(this,void 0,void 0,(function(){var t,n,r,o,i,s,c,l,h,d,p,f;return u(this,(function(u){switch(u.label){case 0:if((null==e?void 0:e.token)&&e.autofill)throw new Error("autofill is not supported when providing a token");if((null==e?void 0:e.action)&&e.token)throw new Error("action is not supported when providing a token");if(null==e?void 0:e.autofill){if(N)return[2,{}];N=!0}return(null==e?void 0:e.action)?[4,this.api.challenge(e.action)]:[3,2];case 1:return n=u.sent(),[3,3];case 2:n=null,u.label=3;case 3:return(t=n)&&"error"in t?(N=!1,[2,S(t)]):[4,this.api.authenticationOptions({token:null==e?void 0:e.token,challengeId:null==t?void 0:t.challengeId})];case 4:if("error"in(r=u.sent()))return N=!1,[2,S(r)];u.label=5;case 5:return u.trys.push([5,8,,9]),[4,I({optionsJSON:r.options,useBrowserAutofill:null==e?void 0:e.autofill})];case 6:return o=u.sent(),(null==e?void 0:e.onVerificationStarted)&&e.onVerificationStarted(),[4,this.api.verify({challengeId:r.challengeId,authenticationCredential:o,token:null==e?void 0:e.token,deviceId:this.anonymousId})];case 7:return"error"in(i=u.sent())?(N=!1,[2,S(i)]):(i.isVerified&&this.storeCredentialAgainstDevice(a(a({},o),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),s=i.accessToken,c=i.userId,l=i.userAuthenticatorId,h=i.username,d=i.userDisplayName,p=i.isVerified,N=!1,[2,{data:{isVerified:p,token:s,userId:c,userAuthenticatorId:l,username:h,displayName:d,authenticationResponse:o}}]);case 8:throw f=u.sent(),N=!1,O(f),f;case 9:return[2]}}))}))},e.prototype.isAvailableOnDevice=function(e){return c(this,arguments,void 0,(function(e){var t,n,r,o,i=e.userId;return u(this,(function(e){switch(e.label){case 0:if(!i)throw new Error("userId is required");if(!(t=localStorage.getItem(this.passkeyLocalStorageKey)))return[2,!1];if(n=JSON.parse(t),0===(r=null!==(o=n[i])&&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:r})];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,r=e.userId,o=void 0===r?"":r;if("cross-platform"!==n){var i=localStorage.getItem(this.passkeyLocalStorageKey),s=i?JSON.parse(i):{};s[o]?s[o].includes(t)||s[o].push(t):s[o]=[t],localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(s))}},e.prototype.doesBrowserSupportConditionalCreate=function(){return c(this,void 0,void 0,(function(){return u(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}(),P=function(){function e(){this.windowRef=null}return e.prototype.show=function(e){var t=e.url,n=e.width,r=void 0===n?400:n,o=e.height,i=function(e){var t=e.url,n=e.width,r=e.height,o=e.win;if(!o.top)return null;var i=o.top.outerHeight/2+o.top.screenY-r/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(r,", top=").concat(i,", left=").concat(s))}({url:t,width:r,height:void 0===o?500:o,win:window});if(!i)throw new Error("Window is not initialized");return this.windowRef=i,i},e.prototype.close=function(){if(!this.windowRef)throw new Error("Window is not initialized");this.windowRef.close()},e}();const $=":not([inert]):not([inert] *)",D=':not([tabindex^="-"])',L=":not(:disabled)";var j=[`a[href]${$}${D}`,`area[href]${$}${D}`,`input:not([type="hidden"]):not([type="radio"])${$}${D}${L}`,`input[type="radio"]${$}${D}${L}`,`select${$}${D}${L}`,`textarea${$}${D}${L}`,`button${$}${D}${L}`,`details${$} > summary:first-of-type${D}`,`iframe${$}${D}`,`audio[controls]${$}${D}`,`video[controls]${$}${D}`,`[contenteditable]${$}${D}`,`[tabindex]${$}${D}`];function J(e){(e.querySelector("[autofocus]")||e).focus()}function K(e,t){if(t&&q(e))return e;if(!((n=e).shadowRoot&&"-1"===n.getAttribute("tabindex")||n.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let n=V(e.shadowRoot,t);for(;n;){const e=K(n,t);if(e)return e;n=W(n,t)}}else if("slot"===e.localName){const n=e.assignedElements({flatten:!0});t||n.reverse();for(const e of n){const n=K(e,t);if(n)return n}}else{let n=V(e,t);for(;n;){const e=K(n,t);if(e)return e;n=W(n,t)}}var n;return!t&&q(e)?e:null}function V(e,t){return t?e.firstElementChild:e.lastElementChild}function W(e,t){return t?e.nextElementSibling:e.previousElementSibling}const q=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(j.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function M(e=document){const t=e.activeElement;return t?t.shadowRoot?M(t.shadowRoot)||document.activeElement:t:null}function H(e,t){const[n,r]=function(e){const t=K(e,!0);return[t,t?K(e,!1)||t:null]}(e);if(!n)return t.preventDefault();const o=M();t.shiftKey&&o===n?(r.focus(),t.preventDefault()):t.shiftKey||o!==r||(n.focus(),t.preventDefault())}class F{$el;id;previouslyFocused;shown;constructor(e){this.$el=e,this.id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this.previouslyFocused=null,this.shown=!1,this.maintainFocus=this.maintainFocus.bind(this),this.bindKeypress=this.bindKeypress.bind(this),this.handleTriggerClicks=this.handleTriggerClicks.bind(this),this.show=this.show.bind(this),this.hide=this.hide.bind(this),this.$el.setAttribute("aria-hidden","true"),this.$el.setAttribute("aria-modal","true"),this.$el.setAttribute("tabindex","-1"),this.$el.hasAttribute("role")||this.$el.setAttribute("role","dialog"),document.addEventListener("click",this.handleTriggerClicks,!0)}destroy(){return this.hide(),document.removeEventListener("click",this.handleTriggerClicks,!0),this.$el.replaceWith(this.$el.cloneNode(!0)),this.fire("destroy"),this}show(e){return this.shown||(this.shown=!0,this.$el.removeAttribute("aria-hidden"),this.previouslyFocused=M(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):J(this.$el),document.body.addEventListener("focus",this.maintainFocus,!0),this.$el.addEventListener("keydown",this.bindKeypress,!0),this.fire("show",e)),this}hide(e){return this.shown?(this.shown=!1,this.$el.setAttribute("aria-hidden","true"),this.previouslyFocused?.focus?.(),document.body.removeEventListener("focus",this.maintainFocus,!0),this.$el.removeEventListener("keydown",this.bindKeypress,!0),this.fire("hide",e),this):this}on(e,t,n){return this.$el.addEventListener(e,t,n),this}off(e,t,n){return this.$el.removeEventListener(e,t,n),this}fire(e,t){this.$el.dispatchEvent(new CustomEvent(e,{detail:t,cancelable:!0}))}handleTriggerClicks(e){const t=e.target;t.closest(`[data-a11y-dialog-show="${this.id}"]`)&&this.show(e),(t.closest(`[data-a11y-dialog-hide="${this.id}"]`)||t.closest("[data-a11y-dialog-hide]")&&t.closest('[aria-modal="true"]')===this.$el)&&this.hide(e)}bindKeypress(e){if(document.activeElement?.closest('[aria-modal="true"]')!==this.$el)return;let t=!1;try{t=!!this.$el.querySelector('[popover]:not([popover="manual"]):popover-open')}catch{}"Escape"!==e.key||"alertdialog"===this.$el.getAttribute("role")||t||(e.preventDefault(),this.hide(e)),"Tab"===e.key&&H(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||J(this.$el)}}function G(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new F(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",G):G());var B="__authsignal-popup-container",z="__authsignal-popup-content",Y="__authsignal-popup-overlay",X="__authsignal-popup-style",Q="__authsignal-popup-iframe",Z="385px",ee=function(){function e(e){var t=e.width,n=e.isClosable;if(this.popup=null,document.querySelector("#".concat(B)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:t,isClosable:n})}return e.prototype.create=function(e){var t=this,n=e.width,r=void 0===n?Z:n,o=e.isClosable,i=void 0===o||o,s=r;CSS.supports("width",r)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),s=Z);var a=document.createElement("div");a.setAttribute("id",B),a.setAttribute("aria-hidden","true"),i||a.setAttribute("role","alertdialog");var c=document.createElement("div");c.setAttribute("id",Y),i&&c.setAttribute("data-a11y-dialog-hide","true");var u=document.createElement("div");u.setAttribute("id",z),document.body.appendChild(a);var l=document.createElement("style");l.setAttribute("id",X),l.textContent="\n #".concat(B,",\n #").concat(Y," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(B," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(B,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(Y," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(z," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(s,";\n }\n\n #").concat(z," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: 95vh;\n height: ").concat("384px",";\n }\n "),document.head.insertAdjacentElement("beforeend",l),a.appendChild(c),a.appendChild(u),this.popup=new F(a),a.focus(),this.popup.on("hide",(function(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(B)),t=document.querySelector("#".concat(X));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),window.removeEventListener("message",te)},e.prototype.show=function(e){var t,n=e.url;if(!this.popup)throw new Error("Popup is not initialized");var r=document.createElement("iframe");r.setAttribute("id",Q),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 o=document.querySelector("#".concat(z));o&&o.appendChild(r),window.addEventListener("message",te),null===(t=this.popup)||void 0===t||t.show()},e.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},e.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},e}();function te(e){var t=document.querySelector("#".concat(Q));t&&e.data.height&&(t.style.height=e.data.height+"px")}var ne=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/totp"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/totp"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),re=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=C.shared,this.api=new ne({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,A(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,A(t)]}}))}))},e}(),oe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.email;return u(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:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-otp"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/email-otp"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ie=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=C.shared,this.api=new oe({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.email;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,A(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,A(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,A(t)]}}))}))},e}(),se=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.phoneNumber;return u(this,(function(e){switch(e.label){case 0:return t={phoneNumber:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/sms"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/sms"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.code;return u(this,(function(e){switch(e.label){case 0:return t={verificationCode:o},[4,fetch("".concat(this.baseUrl,"/client/verify/sms"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e}(),ae=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=C.shared,this.api=new se({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.phoneNumber;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,phoneNumber:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,A(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,A(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.code;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.verify({token:this.cache.token,code:n})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(t=e.sent())&&t.accessToken&&(this.cache.token=t.accessToken),[2,A(t)]}}))}))},e}(),ce=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.email;return u(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:R({token:r,tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return x({response:n=e.sent(),onTokenExpired:this.onTokenExpired}),[2,n]}}))}))},e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge/email-magic-link"),{method:"POST",headers:R({token:n,tenantId:this.tenantId})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.checkVerificationStatus=function(e){return c(this,arguments,void 0,(function(e){var t,n=this,r=e.token;return u(this,(function(e){switch(e.label){case 0:return t=function(){return c(n,void 0,void 0,(function(){var e,n=this;return u(this,(function(o){switch(o.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/email-magic-link/finalize"),{method:"POST",headers:R({token:r,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,o.sent().json()];case 2:return x({response:e=o.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return c(n,void 0,void 0,(function(){var n;return u(this,(function(r){switch(r.label){case 0:return n=e,[4,t()];case 1:return n.apply(void 0,[r.sent()]),[2]}}))}))}),1e3)}))]}}))}))},[4,t()];case 1:return[2,e.sent()]}}))}))},e}(),ue=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=C.shared,this.api=new ce({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return c(this,arguments,void 0,(function(e){var t=e.email;return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.enroll({token:this.cache.token,email:t})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,A(e.sent())]}}))}))},e.prototype.challenge=function(){return c(this,void 0,void 0,(function(){return u(this,(function(e){switch(e.label){case 0:return this.cache.token?[4,this.api.challenge({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return[2,A(e.sent())]}}))}))},e.prototype.checkVerificationStatus=function(){return c(this,void 0,void 0,(function(){var e;return u(this,(function(t){switch(t.label){case 0:return this.cache.token?[4,this.api.checkVerificationStatus({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:return"accessToken"in(e=t.sent())&&e.accessToken&&(this.cache.token=e.accessToken),[2,A(e)]}}))}))},e}(),le=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/registration-options"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.authenticationOptions=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key/authentication-options"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.addAuthenticator=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token,r=e.registrationCredential;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/security-key"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify(r)})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.token,r=e.authenticationCredential;return u(this,(function(e){switch(e.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/verify/security-key"),{method:"POST",headers:R({token:n,tenantId:this.tenantId}),body:JSON.stringify(r)})];case 1:return[4,e.sent().json()];case 2:return x({response:t=e.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),he=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=C.shared,this.api=new le({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(){return c(this,void 0,void 0,(function(){var e,t,n,r,o;return u(this,(function(i){switch(i.label){case 0:return this.cache.token?(e={token:this.cache.token},[4,this.api.registrationOptions(e)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(t=i.sent()))return[2,S(t)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,w({optionsJSON:t})];case 3:return n=i.sent(),[4,this.api.addAuthenticator({registrationCredential:n,token:this.cache.token})];case 4:return"error"in(r=i.sent())?[2,S(r)]:(r.accessToken&&(this.cache.token=r.accessToken),[2,{data:{token:r.accessToken,registrationResponse:n}}]);case 5:throw O(o=i.sent()),o;case 6:return[2]}}))}))},e.prototype.verify=function(){return c(this,void 0,void 0,(function(){var e,t,n,r,o;return u(this,(function(i){switch(i.label){case 0:return this.cache.token?[4,this.api.authenticationOptions({token:this.cache.token})]:[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(e=i.sent()))return[2,S(e)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,I({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,S(n)]:(n.accessToken&&(this.cache.token=n.accessToken),r=n.accessToken,[2,{data:{isVerified:n.isVerified,token:r,authenticationResponse:t}}]);case 5:throw O(o=i.sent()),o;case 6:return[2]}}))}))},e}(),de=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.baseUrl=t}return e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.action;return u(this,(function(e){switch(e.label){case 0:return t={action:n},[4,fetch("".concat(this.baseUrl,"/client/challenge/qr-code"),{method:"POST",headers:R({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.challengeId,r=e.deviceCode;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:n,deviceCode:r},[4,fetch("".concat(this.baseUrl,"/client/verify/qr-code"),{method:"POST",headers:R({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e}(),pe=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.api=new de({baseUrl:t,tenantId:n})}return e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t=e.action;return u(this,(function(e){switch(e.label){case 0:return[4,this.api.challenge({action:t})];case 1:return[2,A(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t=e.challengeId,n=e.deviceCode;return u(this,(function(e){switch(e.label){case 0:return[4,this.api.verify({challengeId:t,deviceCode:n})];case 1:return[2,A(e.sent())]}}))}))},e}(),fe=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.baseUrl=t}return e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.action;return u(this,(function(e){switch(e.label){case 0:return t={action:n},[4,fetch("".concat(this.baseUrl,"/client/challenge/push"),{method:"POST",headers:R({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t,n=e.challengeId;return u(this,(function(e){switch(e.label){case 0:return t={challengeId:n},[4,fetch("".concat(this.baseUrl,"/client/verify/push"),{method:"POST",headers:R({tenantId:this.tenantId}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e}(),ye=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.api=new fe({baseUrl:t,tenantId:n})}return e.prototype.challenge=function(e){return c(this,arguments,void 0,(function(e){var t=e.action;return u(this,(function(e){switch(e.label){case 0:return[4,this.api.challenge({action:t})];case 1:return[2,A(e.sent())]}}))}))},e.prototype.verify=function(e){return c(this,arguments,void 0,(function(e){var t=e.challengeId;return u(this,(function(e){switch(e.label){case 0:return[4,this.api.verify({challengeId:t})];case 1:return[2,A(e.sent())]}}))}))},e}(),be="4a08uqve",ve=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,r=void 0===n?"__as_aid":n,o=e.baseUrl,i=void 0===o?"https://api.authsignal.com/v1":o,a=e.tenantId,c=e.onTokenExpired;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=r,!a)throw new Error("tenantId is required");var u,l=(u=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(u).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;l?this.anonymousId=l:(this.anonymousId=s(),T({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.passkey=new _({tenantId:a,baseUrl:i,anonymousId:this.anonymousId,onTokenExpired:c}),this.totp=new re({tenantId:a,baseUrl:i,onTokenExpired:c}),this.email=new ie({tenantId:a,baseUrl:i,onTokenExpired:c}),this.emailML=new ue({tenantId:a,baseUrl:i,onTokenExpired:c}),this.sms=new ae({tenantId:a,baseUrl:i,onTokenExpired:c}),this.securityKey=new he({tenantId:a,baseUrl:i,onTokenExpired:c}),this.qrCode=new pe({tenantId:a,baseUrl:i}),this.push=new ye({tenantId:a,baseUrl:i})}return t.prototype.setToken=function(e){C.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,T({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(be,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(be,"&session_id=").concat(t),r=document.createElement("script");r.src=n,r.async=!1,r.id="as_adv_profile",document.head.appendChild(r);var o=document.createElement("noscript");o.setAttribute("id","as_adv_profile_pixel"),o.setAttribute("aria-hidden","true");var i=document.createElement("iframe"),a=e?"".concat(e,"/fp/tags?org_id=").concat(be,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(be,"&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;"),o&&(o.appendChild(i),document.body.prepend(o))},t.prototype.launchWithRedirect=function(e){window.location.href=e},t.prototype.launchWithPopup=function(t,n){var r=n.popupOptions,o=new ee({width:null==r?void 0:r.width,isClosable:null==r?void 0:r.isClosable}),i="".concat(t,"&mode=popup");return o.show({url:i}),new Promise((function(t){var n=void 0;o.on("hide",(function(){t({token:n})})),window.addEventListener("message",(function(t){var r=null;try{r=JSON.parse(t.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n=r.token,o.close())}),!1)}))},t.prototype.launchWithWindow=function(t,n){var r=n.windowOptions,o=new P,i="".concat(t,"&mode=popup");return o.show({url:i,width:null==r?void 0:r.width,height:null==r?void 0:r.height}),new Promise((function(t){window.addEventListener("message",(function(n){var r=null;try{r=JSON.parse(n.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o.close(),t({token:r.token}))}),!1)}))},t}();return e.Authsignal=ve,e.WebAuthnError=b,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
1
+ var authsignal=function(e){"use strict";let t;const n=new Uint8Array(16);function r(){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 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||r)();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,r=arguments.length;n<r;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 u(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function h(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(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((r=r.apply(e,t||[])).next())}))}function d(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[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,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=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 f(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,"="),o=atob(r),i=new ArrayBuffer(o.length),s=new Uint8Array(i);for(let e=0;e<o.length;e++)s[e]=o.charCodeAt(e);return i}function v(){return g.stubThis(void 0!==globalThis?.PublicKeyCredential&&"function"==typeof globalThis.PublicKeyCredential)}const g={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 b extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??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}}},k=["cross-platform","platform"];function I(e){if(e&&!(k.indexOf(e)<0))return e}async function E(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 r={...t,challenge:f(t.challenge),user:{...t.user,id:f(t.user.id)},excludeCredentials:t.excludeCredentials?.map(y)},o={};let i;n&&(o.mediation="conditional"),o.publicKey=r,o.signal=w.createNewAbortSignal();try{i=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 b({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 b({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 b({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 b({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 b({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new b({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 b({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new b({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 b({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new b({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 b({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 b({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(!i)throw new Error("Registration was not completed");const{id:s,rawId:a,response:c,type:l}=i;let u,h,d,g;if("function"==typeof c.getTransports&&(u=c.getTransports()),"function"==typeof c.getPublicKeyAlgorithm)try{h=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{g=p(c.getAuthenticatorData())}catch(e){T("getAuthenticatorData()",e)}return{id:s,rawId:p(a),response:{attestationObject:p(c.attestationObject),clientDataJSON:p(c.clientDataJSON),transports:u,publicKeyAlgorithm:h,publicKey:d,authenticatorData:g},type:l,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:I(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:r=!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 i={...t,challenge:f(t.challenge),allowCredentials:o},s={};if(n){if(!await function(){if(!v())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&&r)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=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 b({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new b({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 b({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new b({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 b({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:u,type:h}=a;let d;return u.userHandle&&(d=p(u.userHandle)),{id:c,rawId:p(l),response:{authenticatorData:p(u.authenticatorData),clientDataJSON:p(u.clientDataJSON),signature:p(u.signature),userHandle:d},type:h,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:I(a.authenticatorAttachment)}}function A(e){var t=e.name,n=e.value,r=e.expire,o=e.domain,i=e.secure,s=r===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+r;document.cookie=encodeURIComponent(t)+"="+n+"; path=/;"+s+(o?"; domain="+o:"")+(i?"; secure":"")}function R(e){var t,n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}function O(e){var t;if(e&&"object"==typeof e&&"error"in e){var n=null!==(t=e.errorDescription)&&void 0!==t?t:e.error;return console.error(n),{error:n}}if(e&&"object"==typeof e&&"accessToken"in e&&"string"==typeof e.accessToken){var r=e.accessToken,o=u(e,["accessToken"]);return{data:l(l({},o),{token:r})}}return{data:e}}function x(e){var t,n;if(e instanceof b&&"ERROR_INVALID_RP_ID"===e.code){var r=(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(r,'" is invalid for this domain.\n To learn more, visit https://docs.authsignal.com/scenarios/passkeys-prebuilt-ui#defining-the-relying-party'))}}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,(e.AuthsignalWindowMessage||(e.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP";var _=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return h(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.username,i=e.authenticatorAttachment;return d(this,(function(e){switch(e.label){case 0:return t=Boolean(i)?{username:o,authenticatorAttachment:i}:{username:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/registration-options"),{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.authenticationOptions=function(e){return h(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.challengeId;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:o},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey/authentication-options"),{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.addAuthenticator=function(e){return h(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.challengeId,i=e.registrationCredential,s=e.conditionalCreate;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:o,registrationCredential:i,conditionalCreate:s},[4,fetch("".concat(this.baseUrl,"/client/user-authenticators/passkey"),{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 h(this,arguments,void 0,(function(e){var t,n,r=e.token,o=e.challengeId,i=e.authenticationCredential,s=e.deviceId;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:o,authenticationCredential:i,deviceId:s},[4,fetch("".concat(this.baseUrl,"/client/verify/passkey"),{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.getPasskeyAuthenticator=function(e){return h(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 h(this,void 0,void 0,(function(){var t;return d(this,(function(n){switch(n.label){case 0:return[4,fetch("".concat(this.baseUrl,"/client/challenge"),{method:"POST",headers:U({tenantId:this.tenantId}),body:JSON.stringify({action:e})})];case 1:return[4,n.sent().json()];case 2:return P({response:t=n.sent(),onTokenExpired:this.onTokenExpired}),[2,t]}}))}))},e}(),N=function(){function e(){this.token=null}return e.prototype.handleTokenNotSetError=function(){var e="A token has not been set. Call 'setToken' first.";return console.error("Error: ".concat(e)),{error:"TOKEN_NOT_SET",errorDescription:e}},e.shared=new e,e}(),$=!1,D=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.anonymousId,o=e.onTokenExpired;this.passkeyLocalStorageKey="as_user_passkey_map",this.cache=N.shared,this.api=new _({baseUrl:t,tenantId:n,onTokenExpired:o}),this.anonymousId=r}return e.prototype.signUp=function(e){return h(this,arguments,void 0,(function(e){var t,n,r,o,i,s,a=e.username,c=e.displayName,u=e.token,h=e.authenticatorAttachment,p=void 0===h?"platform":h,f=e.useAutoRegister,v=void 0!==f&&f;return d(this,(function(e){switch(e.label){case 0:return(t=null!=u?u:this.cache.token)?v?[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},[4,this.api.registrationOptions(n)];case 3:if("error"in(r=e.sent()))return[2,R(r)];e.label=4;case 4:return e.trys.push([4,7,,8]),[4,E({optionsJSON:r.options,useAutoRegister:v})];case 5:return o=e.sent(),[4,this.api.addAuthenticator({challengeId:r.challengeId,registrationCredential:o,token:t,conditionalCreate:v})];case 6:return"error"in(i=e.sent())?[2,R(i)]:(i.isVerified&&this.storeCredentialAgainstDevice(l(l({},o),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),[2,{data:{token:i.accessToken,userAuthenticator:i.userAuthenticator,registrationResponse:o}}]);case 7:throw s=e.sent(),$=!1,x(s),s;case 8:return[2]}}))}))},e.prototype.signIn=function(e){return h(this,void 0,void 0,(function(){var t,n,r,o,i,s,a,c,u,h,p,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(e.action)]:[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,R(t)]):[4,this.api.authenticationOptions({token:null==e?void 0:e.token,challengeId:null==t?void 0:t.challengeId})];case 4:if("error"in(r=d.sent()))return $=!1,[2,R(r)];d.label=5;case 5:return d.trys.push([5,8,,9]),[4,S({optionsJSON:r.options,useBrowserAutofill:null==e?void 0:e.autofill})];case 6:return o=d.sent(),(null==e?void 0:e.onVerificationStarted)&&e.onVerificationStarted(),[4,this.api.verify({challengeId:r.challengeId,authenticationCredential:o,token:null==e?void 0:e.token,deviceId:this.anonymousId})];case 7:return"error"in(i=d.sent())?($=!1,[2,R(i)]):(i.isVerified&&this.storeCredentialAgainstDevice(l(l({},o),{userId:i.userId})),i.accessToken&&(this.cache.token=i.accessToken),s=i.accessToken,a=i.userId,c=i.userAuthenticatorId,u=i.username,h=i.userDisplayName,p=i.isVerified,$=!1,[2,{data:{isVerified:p,token:s,userId:a,userAuthenticatorId:c,username:u,displayName:h,authenticationResponse:o}}]);case 8:throw f=d.sent(),$=!1,x(f),f;case 9:return[2]}}))}))},e.prototype.isAvailableOnDevice=function(e){return h(this,arguments,void 0,(function(e){var t,n,r,o,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===(r=null!==(o=n[i])&&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:r})];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,r=e.userId,o=void 0===r?"":r;if("cross-platform"!==n){var i=localStorage.getItem(this.passkeyLocalStorageKey),s=i?JSON.parse(i):{};s[o]?s[o].includes(t)||s[o].push(t):s[o]=[t],localStorage.setItem(this.passkeyLocalStorageKey,JSON.stringify(s))}},e.prototype.doesBrowserSupportConditionalCreate=function(){return h(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}(),L=function(){function e(){this.windowRef=null}return e.prototype.show=function(e){var t=e.url,n=e.width,r=void 0===n?400:n,o=e.height,i=function(e){var t=e.url,n=e.width,r=e.height,o=e.win;if(!o.top)return null;var i=o.top.outerHeight/2+o.top.screenY-r/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(r,", top=").concat(i,", left=").concat(s))}({url:t,width:r,height:void 0===o?500:o,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 j=":not([inert]):not([inert] *)",J=':not([tabindex^="-"])',K=":not(:disabled)";var H=[`a[href]${j}${J}`,`area[href]${j}${J}`,`input:not([type="hidden"]):not([type="radio"])${j}${J}${K}`,`input[type="radio"]${j}${J}${K}`,`select${j}${J}${K}`,`textarea${j}${J}${K}`,`button${j}${J}${K}`,`details${j} > summary:first-of-type${J}`,`iframe${j}${J}`,`audio[controls]${j}${J}`,`video[controls]${j}${J}`,`[contenteditable]${j}${J}`,`[tabindex]${j}${J}`];function W(e){(e.querySelector("[autofocus]")||e).focus()}function M(e,t){if(t&&G(e))return e;if(!((n=e).shadowRoot&&"-1"===n.getAttribute("tabindex")||n.matches(":disabled,[hidden],[inert]")))if(e.shadowRoot){let n=V(e.shadowRoot,t);for(;n;){const e=M(n,t);if(e)return e;n=q(n,t)}}else if("slot"===e.localName){const n=e.assignedElements({flatten:!0});t||n.reverse();for(const e of n){const n=M(e,t);if(n)return n}}else{let n=V(e,t);for(;n;){const e=M(n,t);if(e)return e;n=q(n,t)}}var n;return!t&&G(e)?e:null}function V(e,t){return t?e.firstElementChild:e.lastElementChild}function q(e,t){return t?e.nextElementSibling:e.previousElementSibling}const G=e=>!e.shadowRoot?.delegatesFocus&&(e.matches(H.join(","))&&!(e=>!(!e.matches("details:not([open]) *")||e.matches("details>summary:first-of-type"))||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length))(e));function F(e=document){const t=e.activeElement;return t?t.shadowRoot?F(t.shadowRoot)||document.activeElement:t:null}function B(e,t){const[n,r]=function(e){const t=M(e,!0);return[t,t?M(e,!1)||t:null]}(e);if(!n)return t.preventDefault();const o=F();t.shiftKey&&o===n?(r.focus(),t.preventDefault()):t.shiftKey||o!==r||(n.focus(),t.preventDefault())}class z{$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=F(),"BODY"===this.previouslyFocused?.tagName&&e?.target&&(this.previouslyFocused=e.target),"focus"===e?.type?this.maintainFocus(e):W(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&&B(this.$el,e)}maintainFocus(e){e.target.closest('[aria-modal="true"], [data-a11y-dialog-ignore-focus-trap]')||W(this.$el)}}function Y(){for(const e of document.querySelectorAll("[data-a11y-dialog]"))new z(e)}"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",Y):Y());var Q="__authsignal-popup-container",X="__authsignal-popup-content",Z="__authsignal-popup-overlay",ee="__authsignal-popup-style",te="__authsignal-popup-iframe",ne="385px",re=function(){function e(e){var t=e.width,n=e.isClosable;if(this.popup=null,document.querySelector("#".concat(Q)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:t,isClosable:n})}return e.prototype.create=function(e){var t=this,n=e.width,r=void 0===n?ne:n,o=e.isClosable,i=void 0===o||o,s=r;CSS.supports("width",r)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),s=ne);var a=document.createElement("div");a.setAttribute("id",Q),a.setAttribute("aria-hidden","true"),i||a.setAttribute("role","alertdialog");var c=document.createElement("div");c.setAttribute("id",Z),i&&c.setAttribute("data-a11y-dialog-hide","true");var l=document.createElement("div");l.setAttribute("id",X),document.body.appendChild(a);var u=document.createElement("style");u.setAttribute("id",ee),u.textContent="\n #".concat(Q,",\n #").concat(Z," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(Q," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(Q,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(Z," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(X," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(s,";\n }\n\n #").concat(X," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: 95vh;\n height: ").concat("384px",";\n }\n "),document.head.insertAdjacentElement("beforeend",u),a.appendChild(c),a.appendChild(l),this.popup=new z(a),a.focus(),this.popup.on("hide",(function(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(Q)),t=document.querySelector("#".concat(ee));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),window.removeEventListener("message",oe)},e.prototype.show=function(e){var t,n=e.url;if(!this.popup)throw new Error("Popup is not initialized");var r=document.createElement("iframe");r.setAttribute("id",te),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 o=document.querySelector("#".concat(X));o&&o.appendChild(r),window.addEventListener("message",oe),null===(t=this.popup)||void 0===t||t.show()},e.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},e.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},e}();function oe(e){var t=document.querySelector("#".concat(te));t&&e.data.height&&(t.style.height=e.data.height+"px")}var ie=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(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 h(this,arguments,void 0,(function(e){var t,n,r=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: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,r=e.onTokenExpired;this.cache=N.shared,this.api=new ie({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(){return h(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(e.sent())]}}))}))},e.prototype.verify=function(e){return h(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(t)]}}))}))},e}(),ae=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t,n,r=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: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.challenge=function(e){return h(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 h(this,arguments,void 0,(function(e){var t,n,r=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: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}(),ce=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=N.shared,this.api=new ae({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return h(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(e.sent())]}}))}))},e.prototype.challenge=function(){return h(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(e.sent())]}}))}))},e.prototype.verify=function(e){return h(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(t)]}}))}))},e}(),le=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t,n,r=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: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.challenge=function(e){return h(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 h(this,arguments,void 0,(function(e){var t,n,r=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: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}(),ue=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=N.shared,this.api=new le({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return h(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(e.sent())]}}))}))},e.prototype.challenge=function(){return h(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(e.sent())]}}))}))},e.prototype.verify=function(e){return h(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(t)]}}))}))},e}(),he=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.enroll=function(e){return h(this,arguments,void 0,(function(e){var t,n,r=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: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.challenge=function(e){return h(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 h(this,arguments,void 0,(function(e){var t,n=this,r=e.token;return d(this,(function(e){switch(e.label){case 0:return t=function(){return h(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:r,tenantId:this.tenantId}),body:JSON.stringify({})})];case 1:return[4,o.sent().json()];case 2:return P({response:e=o.sent(),onTokenExpired:this.onTokenExpired}),e.isVerified?[2,e]:[2,new Promise((function(e){setTimeout((function(){return h(n,void 0,void 0,(function(){var n;return d(this,(function(r){switch(r.label){case 0:return n=e,[4,t()];case 1:return n.apply(void 0,[r.sent()]),[2]}}))}))}),1e3)}))]}}))}))},[4,t()];case 1:return[2,e.sent()]}}))}))},e}(),de=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.cache=N.shared,this.api=new he({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(e){return h(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(e.sent())]}}))}))},e.prototype.challenge=function(){return h(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(e.sent())]}}))}))},e.prototype.checkVerificationStatus=function(){return h(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(e)]}}))}))},e}(),pe=function(){function e(e){var t=e.baseUrl,n=e.tenantId,r=e.onTokenExpired;this.tenantId=n,this.baseUrl=t,this.onTokenExpired=r}return e.prototype.registrationOptions=function(e){return h(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 h(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 h(this,arguments,void 0,(function(e){var t,n=e.token,r=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(r)})];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 h(this,arguments,void 0,(function(e){var t,n=e.token,r=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(r)})];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,r=e.onTokenExpired;this.cache=N.shared,this.api=new pe({baseUrl:t,tenantId:n,onTokenExpired:r})}return e.prototype.enroll=function(){return h(this,void 0,void 0,(function(){var e,t,n,r,o;return d(this,(function(i){switch(i.label){case 0:return this.cache.token?(e={token:this.cache.token},[4,this.api.registrationOptions(e)]):[2,this.cache.handleTokenNotSetError()];case 1:if("error"in(t=i.sent()))return[2,R(t)];i.label=2;case 2:return i.trys.push([2,5,,6]),[4,E({optionsJSON:t})];case 3:return n=i.sent(),[4,this.api.addAuthenticator({registrationCredential:n,token:this.cache.token})];case 4:return"error"in(r=i.sent())?[2,R(r)]:(r.accessToken&&(this.cache.token=r.accessToken),[2,{data:{token:r.accessToken,registrationResponse:n}}]);case 5:throw x(o=i.sent()),o;case 6:return[2]}}))}))},e.prototype.verify=function(){return h(this,void 0,void 0,(function(){var e,t,n,r,o;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,R(e)];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,R(n)]:(n.accessToken&&(this.cache.token=n.accessToken),r=n.accessToken,[2,{data:{isVerified:n.isVerified,token:r,authenticationResponse:t}}]);case 5:throw x(o=i.sent()),o;case 6:return[2]}}))}))},e}(),ve=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.baseUrl=t}return e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,n=e.action,r=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:r}),body:JSON.stringify(t)})];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,n=e.challengeId,r=e.deviceCode;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:n,deviceCode:r},[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}(),ge=function(){},ye=54e4,me=5e3,be=function(e){function t(t){var n=t.baseUrl,r=t.tenantId,o=e.call(this)||this;return o.cache=N.shared,o.api=new ve({baseUrl:n,tenantId:r}),o}return c(t,e),t.prototype.challenge=function(e){return h(this,void 0,void 0,(function(){var t,n,r,o,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=O(t)).data&&(this.currentChallengeParams=e,this.clearPolling(),r=e.pollInterval||me,o=e.refreshInterval||ye,n.data.deviceCode&&this.startPolling({challengeId:n.data.challengeId,deviceCode:n.data.deviceCode,onStateChange:e.onStateChange,pollInterval:r}),e.onRefresh&&(i=e.onRefresh,this.startRefreshTimer((function(){return s.performRefresh({action:e.action,custom:e.custom,onRefresh:i,onStateChange:e.onStateChange,pollInterval:r})}),o))),[2,n]}}))}))},t.prototype.refresh=function(){return h(this,arguments,void 0,(function(e){var t,n,r,o,i,s,a,c,l,u=this,h=(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:h||this.currentChallengeParams.custom})]:[2];case 1:return t=e.sent(),(n=O(t)).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&&(r=this.currentChallengeParams.refreshInterval||ye,o=this.currentChallengeParams,i=o.action,s=o.custom,a=o.onRefresh,c=o.onStateChange,l=o.pollInterval,this.startRefreshTimer((function(){return u.performRefresh({action:i,custom:s,onRefresh:a,onStateChange:c,pollInterval:l||me})}),r))),[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 h(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 h(this,arguments,void 0,(function(e){var t,n,r=e.action,o=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:r,custom:o})];case 1:return t=e.sent(),(n=O(t)).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,r=e.deviceCode,o=e.onStateChange,i=e.pollInterval;this.pollingInterval=setInterval((function(){return h(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:r})];case 1:return e=i.sent(),(t=O(e)).data&&(t.data.isVerified?(o("approved",t.data.token),this.clearPolling()):t.data.isClaimed&&o("claimed")),[2]}}))}))}),i)},t.prototype.clearPolling=function(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0)},t}(ge),we="CHALLENGE_CREATED_HANDLER",ke=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=N.shared;var r=t.replace("https://","wss://").replace("http://","ws://").replace("v1","ws-v1-challenge").replace("api","api-ws");this.baseUrl=r,this.tenantId=n}return e.prototype.connect=function(){return h(this,void 0,void 0,(function(){var e=this;return d(this,(function(t){return[2,new Promise((function(t,n){try{var r=["authsignal-ws"];e.tokenCache.token?r.push("x.authsignal.token.".concat(e.tokenCache.token)):r.push("x.authsignal.tenant.".concat(e.tenantId)),e.ws=new WebSocket(e.baseUrl,r),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 h(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,r){t.messageHandlers.set(we,(function(r){if("CHALLENGE_CREATED"===r.type){var o=r;t.messageHandlers.delete(we),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(r)}))]}}))}))},e.prototype.monitorChallengeState=function(e,t){var n=this;this.messageHandlers.set(e,(function(r){var o;if("STATE_CHANGE"===r.type){var i=r;null===(o=t.onStateChange)||void 0===o||o.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,r=t.refreshInterval||54e4,o=e;this.refreshInterval=setInterval((function(){return h(n,void 0,void 0,(function(){var e,n,r;return d(this,(function(i){switch(i.label){case 0:this.messageHandlers.delete(o),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.createQrCodeChallenge(t)];case 2:return e=i.sent(),o=e.challengeId,null===(r=t.onRefresh)||void 0===r||r.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]}}))}))}),r)},e.prototype.sendChallengeRequest=function(e){return h(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 h(this,arguments,void 0,(function(e){var t,n,r,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===(r=(n=this.options).onRefresh)||void 0===r||r.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,r=t.tenantId,o=e.call(this)||this;return o.cache=N.shared,o.wsClient=new ke({baseUrl:n,tenantId:r}),o}return c(t,e),t.prototype.challenge=function(e){return h(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 h(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}(ge),Ee=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.handler=null,this.baseUrl=t,this.tenantId=n}return e.prototype.challenge=function(e){return h(this,void 0,void 0,(function(){var t,n,r;return d(this,(function(o){return t=e.polling,n=void 0!==t&&t,r=u(e,["polling"]),this.handler&&this.handler.disconnect(),this.handler=n?new be({baseUrl:this.baseUrl,tenantId:this.tenantId}):new Ie({baseUrl:this.baseUrl,tenantId:this.tenantId}),[2,this.handler.challenge(r)]}))}))},e.prototype.refresh=function(){return h(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}(),Te=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.baseUrl=t}return e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t,n=e.action;return d(this,(function(e){switch(e.label){case 0:return t={action:n},[4,fetch("".concat(this.baseUrl,"/client/challenge/push"),{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.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t,n=e.challengeId;return d(this,(function(e){switch(e.label){case 0:return t={challengeId:n},[4,fetch("".concat(this.baseUrl,"/client/verify/push"),{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}(),Ce=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.api=new Te({baseUrl:t,tenantId:n})}return e.prototype.challenge=function(e){return h(this,arguments,void 0,(function(e){var t=e.action;return d(this,(function(e){switch(e.label){case 0:return[4,this.api.challenge({action:t})];case 1:return[2,O(e.sent())]}}))}))},e.prototype.verify=function(e){return h(this,arguments,void 0,(function(e){var t=e.challengeId;return d(this,(function(e){switch(e.label){case 0:return[4,this.api.verify({challengeId:t})];case 1:return[2,O(e.sent())]}}))}))},e}(),Se="4a08uqve",Ae=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,r=void 0===n?"__as_aid":n,o=e.baseUrl,i=void 0===o?"https://api.authsignal.com/v1":o,a=e.tenantId,c=e.onTokenExpired;if(this.anonymousId="",this.profilingId="",this.cookieDomain="",this.anonymousIdCookieName="",this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=r,!a)throw new Error("tenantId is required");var l,u=(l=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(l).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;u?this.anonymousId=u:(this.anonymousId=s(),A({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol})),this.passkey=new D({tenantId:a,baseUrl:i,anonymousId:this.anonymousId,onTokenExpired:c}),this.totp=new se({tenantId:a,baseUrl:i,onTokenExpired:c}),this.email=new ce({tenantId:a,baseUrl:i,onTokenExpired:c}),this.emailML=new de({tenantId:a,baseUrl:i,onTokenExpired:c}),this.sms=new ue({tenantId:a,baseUrl:i,onTokenExpired:c}),this.securityKey=new fe({tenantId:a,baseUrl:i,onTokenExpired:c}),this.qrCode=new Ee({tenantId:a,baseUrl:i}),this.push=new Ce({tenantId:a,baseUrl:i})}return t.prototype.setToken=function(e){N.shared.token=e},t.prototype.launch=function(e,t){switch(null==t?void 0:t.mode){case"window":return this.launchWithWindow(e,t);case"popup":return this.launchWithPopup(e,t);default:this.launchWithRedirect(e)}},t.prototype.initAdvancedProfiling=function(e){var t=s();this.profilingId=t,A({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(Se,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags.js?org_id=".concat(Se,"&session_id=").concat(t),r=document.createElement("script");r.src=n,r.async=!1,r.id="as_adv_profile",document.head.appendChild(r);var o=document.createElement("noscript");o.setAttribute("id","as_adv_profile_pixel"),o.setAttribute("aria-hidden","true");var i=document.createElement("iframe"),a=e?"".concat(e,"/fp/tags?org_id=").concat(Se,"&session_id=").concat(t):"https://h.online-metrix.net/fp/tags?org_id=".concat(Se,"&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;"),o&&(o.appendChild(i),document.body.prepend(o))},t.prototype.launchWithRedirect=function(e){window.location.href=e},t.prototype.launchWithPopup=function(t,n){var r=n.popupOptions,o=new re({width:null==r?void 0:r.width,isClosable:null==r?void 0:r.isClosable}),i="".concat(t,"&mode=popup");return o.show({url:i}),new Promise((function(t){var n=void 0;o.on("hide",(function(){t({token:n})})),window.addEventListener("message",(function(t){var r=null;try{r=JSON.parse(t.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(n=r.token,o.close())}),!1)}))},t.prototype.launchWithWindow=function(t,n){var r=n.windowOptions,o=new L,i="".concat(t,"&mode=popup");return o.show({url:i,width:null==r?void 0:r.width,height:null==r?void 0:r.height}),new Promise((function(t){window.addEventListener("message",(function(n){var r=null;try{r=JSON.parse(n.data)}catch(e){}(null==r?void 0:r.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o.close(),t({token:r.token}))}),!1)}))},t}();return e.Authsignal=Ae,e.WebAuthnError=b,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
@@ -0,0 +1,17 @@
1
+ import { ChallengeParams } from "../qr-code";
2
+ import { AuthsignalResponse } from "../types";
3
+ import { QrCodeChallengeResponse } from "../api/types/qr-code";
4
+ export interface QrHandler {
5
+ challenge(params: ChallengeParams): Promise<AuthsignalResponse<QrCodeChallengeResponse>>;
6
+ refresh(params: {
7
+ custom?: Record<string, unknown>;
8
+ }): Promise<void>;
9
+ disconnect(): void;
10
+ }
11
+ export declare abstract class BaseQrHandler implements QrHandler {
12
+ abstract challenge(params: ChallengeParams): Promise<AuthsignalResponse<QrCodeChallengeResponse>>;
13
+ abstract refresh(params: {
14
+ custom?: Record<string, unknown>;
15
+ }): Promise<void>;
16
+ abstract disconnect(): void;
17
+ }
@@ -0,0 +1,25 @@
1
+ import { QrCodeChallengeResponse } from "../api/types/qr-code";
2
+ import { AuthsignalResponse } from "../types";
3
+ import { ChallengeParams } from "../qr-code";
4
+ import { BaseQrHandler } from "./base-qr-handler";
5
+ export declare class RestQrHandler extends BaseQrHandler {
6
+ private api;
7
+ private pollingInterval?;
8
+ private refreshTimeout?;
9
+ private currentChallengeParams?;
10
+ private cache;
11
+ constructor({ baseUrl, tenantId }: {
12
+ baseUrl: string;
13
+ tenantId: string;
14
+ });
15
+ challenge(params: ChallengeParams): Promise<AuthsignalResponse<QrCodeChallengeResponse>>;
16
+ refresh({ custom }?: {
17
+ custom?: Record<string, unknown>;
18
+ }): Promise<void>;
19
+ disconnect(): void;
20
+ private startRefreshTimer;
21
+ private clearRefreshTimer;
22
+ private performRefresh;
23
+ private startPolling;
24
+ private clearPolling;
25
+ }
@@ -0,0 +1,17 @@
1
+ import { QrCodeChallengeResponse } from "../api/types/qr-code";
2
+ import { AuthsignalResponse } from "../types";
3
+ import { ChallengeParams } from "../qr-code";
4
+ import { BaseQrHandler } from "./base-qr-handler";
5
+ export declare class WebSocketQrHandler extends BaseQrHandler {
6
+ private wsClient;
7
+ private cache;
8
+ constructor({ baseUrl, tenantId }: {
9
+ baseUrl: string;
10
+ tenantId: string;
11
+ });
12
+ challenge(params: ChallengeParams): Promise<AuthsignalResponse<QrCodeChallengeResponse>>;
13
+ refresh({ custom }?: {
14
+ custom?: Record<string, unknown>;
15
+ }): Promise<void>;
16
+ disconnect(): void;
17
+ }
package/dist/qr-code.d.ts CHANGED
@@ -1,20 +1,35 @@
1
- import { QrCodeChallengeResponse, QrCodeVerifyResponse } from "./api/types/qr-code";
1
+ import { QrCodeChallengeResponse } from "./api/types/qr-code";
2
+ import { ChallengeState } from "./api/types/websocket";
2
3
  import { AuthsignalResponse } from "./types";
3
4
  type QrCodeOptions = {
4
5
  baseUrl: string;
5
6
  tenantId: string;
6
7
  };
7
- type ChallengeParams = {
8
+ export type ChallengeParams = {
9
+ /** The action to be performed when the QR code is scanned. If track action is called, this must match the action passed to track. */
8
10
  action: string;
9
- };
10
- type VerifyParams = {
11
- challengeId: string;
12
- deviceCode: string;
11
+ /** Custom data to be included in the challenge request. If track action is called, this must be omitted. */
12
+ custom?: Record<string, unknown>;
13
+ /** Use REST API polling instead of WebSocket connection. Default: false */
14
+ polling?: boolean;
15
+ /** The interval in milliseconds at which the QR code challenge will be polled. Default: 5 seconds (Only used when polling is true)*/
16
+ pollInterval?: number;
17
+ /** The interval in milliseconds at which the QR code challenge will be refreshed. Default: 9 minutes */
18
+ refreshInterval?: number;
19
+ /** A callback function that is called when the QR code challenge is refreshed. */
20
+ onRefresh?: (challengeId: string, expiresAt: string) => void;
21
+ /** A callback function that is called when the state of the QR code challenge changes. */
22
+ onStateChange: (state: ChallengeState, accessToken?: string) => void;
13
23
  };
14
24
  export declare class QrCode {
15
- private api;
25
+ private handler;
26
+ private baseUrl;
27
+ private tenantId;
16
28
  constructor({ baseUrl, tenantId }: QrCodeOptions);
17
- challenge({ action }: ChallengeParams): Promise<AuthsignalResponse<QrCodeChallengeResponse>>;
18
- verify({ challengeId, deviceCode }: VerifyParams): Promise<AuthsignalResponse<QrCodeVerifyResponse>>;
29
+ challenge(params: ChallengeParams): Promise<AuthsignalResponse<QrCodeChallengeResponse>>;
30
+ refresh({ custom }?: {
31
+ custom?: Record<string, unknown>;
32
+ }): Promise<void>;
33
+ disconnect(): void;
19
34
  }
20
35
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authsignal/browser",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",