@teamhanko/hanko-frontend-sdk 1.5.2 → 2.0.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.
- package/README.md +453 -97
- package/dist/Hanko.d.ts +57 -29
- package/dist/index.d.ts +16 -9
- package/dist/lib/Cookie.d.ts +2 -2
- package/dist/lib/Dto.d.ts +11 -184
- package/dist/lib/client/HttpClient.d.ts +7 -9
- package/dist/lib/client/SessionClient.d.ts +0 -11
- package/dist/lib/client/UserClient.d.ts +1 -35
- package/dist/lib/events/CustomEvents.d.ts +25 -0
- package/dist/lib/events/Dispatcher.d.ts +9 -1
- package/dist/lib/events/Listener.d.ts +3 -1
- package/dist/lib/events/Relay.d.ts +3 -3
- package/dist/lib/flow-api/State.d.ts +192 -62
- package/dist/lib/flow-api/WebauthnManager.d.ts +47 -0
- package/dist/lib/flow-api/auto-steps.d.ts +2 -0
- package/dist/lib/flow-api/passkey-autofill-activation.d.ts +2 -0
- package/dist/lib/flow-api/types/action.d.ts +2 -1
- package/dist/lib/flow-api/types/flow.d.ts +25 -0
- package/dist/lib/flow-api/types/{error.d.ts → flowError.d.ts} +1 -2
- package/dist/lib/flow-api/types/input.d.ts +3 -4
- package/dist/lib/flow-api/types/{state-handling.d.ts → state.d.ts} +0 -7
- package/dist/sdk.cjs +1 -1
- package/dist/sdk.cjs.map +1 -1
- package/dist/sdk.modern.js +1 -1
- package/dist/sdk.modern.js.map +1 -1
- package/dist/sdk.module.js +1 -1
- package/dist/sdk.module.js.map +1 -1
- package/dist/sdk.umd.js +1 -1
- package/dist/sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/lib/client/EmailClient.d.ts +0 -58
- package/dist/lib/client/EnterpriseClient.d.ts +0 -41
- package/dist/lib/client/ThirdPartyClient.d.ts +0 -28
- package/dist/lib/client/TokenClient.d.ts +0 -21
- package/dist/lib/flow-api/BrowserFlowStorage.d.ts +0 -6
- package/dist/lib/flow-api/Flow.d.ts +0 -41
- package/dist/lib/state/State.d.ts +0 -50
|
@@ -1,69 +1,199 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { Action } from "./types/action";
|
|
1
|
+
import { Hanko } from "../../Hanko";
|
|
2
|
+
import { Actions, Payloads, StateName } from "./types/state";
|
|
4
3
|
import { Input } from "./types/input";
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
import { FlowError } from "./types/flowError";
|
|
5
|
+
import { Action as ActionType } from "./types/action";
|
|
6
|
+
import { AnyState, FlowName, FlowResponse } from "./types/flow";
|
|
7
|
+
import { autoSteps } from "./auto-steps";
|
|
8
|
+
import { passkeyAutofillActivationHandlers } from "./passkey-autofill-activation";
|
|
9
|
+
export type AutoSteppedStates = keyof typeof autoSteps;
|
|
10
|
+
export type PasskeyAutofillStates = keyof typeof passkeyAutofillActivationHandlers;
|
|
11
|
+
export type AutoStepExclusion = AutoSteppedStates[] | "all";
|
|
12
|
+
export type ActionMap<TState extends StateName> = {
|
|
13
|
+
[K in keyof Actions[TState]]: Action<Actions[TState][K] extends ActionType<infer TInputs> ? TInputs : never>;
|
|
7
14
|
};
|
|
8
|
-
type
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
tryValidate: () => ValidationError | void;
|
|
15
|
+
export type ActionInfo = {
|
|
16
|
+
name: string;
|
|
17
|
+
relatedStateName: StateName;
|
|
12
18
|
};
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
name: StateName;
|
|
20
|
-
status: number;
|
|
21
|
-
payload?: Payloads[TStateName];
|
|
22
|
-
actions?: Actions[TStateName];
|
|
23
|
-
csrf_token: string;
|
|
24
|
-
error: Error;
|
|
19
|
+
export interface StateInitConfig {
|
|
20
|
+
dispatchAfterStateChangeEvent?: boolean;
|
|
21
|
+
excludeAutoSteps?: AutoStepExclusion;
|
|
22
|
+
previousAction?: ActionInfo;
|
|
23
|
+
isCached?: boolean;
|
|
24
|
+
cacheKey?: string;
|
|
25
25
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
26
|
+
export type StateCreateConfig = Pick<StateInitConfig, "dispatchAfterStateChangeEvent" | "excludeAutoSteps" | "cacheKey"> & {
|
|
27
|
+
loadFromCache?: boolean;
|
|
28
|
+
};
|
|
29
|
+
export type ActionRunConfig = Pick<StateInitConfig, "dispatchAfterStateChangeEvent">;
|
|
30
|
+
type SerializedState = FlowResponse<any> & {
|
|
31
|
+
flow_name: FlowName;
|
|
32
|
+
previous_action?: ActionInfo;
|
|
33
|
+
is_cached?: boolean;
|
|
34
|
+
};
|
|
35
|
+
type ExtractInputValues<TInputs> = {
|
|
36
|
+
[K in keyof TInputs]: TInputs[K] extends Input<infer TValue> ? TValue : never;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Represents a state in a flow with associated actions and properties.
|
|
40
|
+
* @template TState - The specific state name type.
|
|
41
|
+
* @constructor
|
|
42
|
+
* @param {Hanko} hanko - The Hanko instance for API interactions.
|
|
43
|
+
* @param {FlowName} flowName - The name of the flow this state belongs to.
|
|
44
|
+
* @param {FlowResponse<TState>} response - The flow response containing state data.
|
|
45
|
+
* @param {StateInitConfig} [options={}] - Configuration options for state initialization.
|
|
46
|
+
* @category SDK
|
|
47
|
+
* @subcategory FlowAPI
|
|
48
|
+
*/
|
|
49
|
+
export declare class State<TState extends StateName = StateName> {
|
|
50
|
+
readonly name: TState;
|
|
51
|
+
readonly flowName: FlowName;
|
|
52
|
+
error?: FlowError;
|
|
53
|
+
readonly payload?: Payloads[TState];
|
|
54
|
+
readonly actions: ActionMap<TState>;
|
|
55
|
+
readonly csrfToken: string;
|
|
31
56
|
readonly status: number;
|
|
32
|
-
readonly
|
|
33
|
-
readonly
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
57
|
+
readonly previousAction?: ActionInfo;
|
|
58
|
+
readonly isCached: boolean;
|
|
59
|
+
readonly cacheKey: string;
|
|
60
|
+
readonly hanko: Hanko;
|
|
61
|
+
invokedAction?: ActionInfo;
|
|
62
|
+
readonly excludeAutoSteps: AutoStepExclusion;
|
|
63
|
+
readonly autoStep?: TState extends AutoSteppedStates ? () => Promise<AnyState> : never;
|
|
64
|
+
readonly passkeyAutofillActivation: TState extends PasskeyAutofillStates ? () => Promise<void> : never;
|
|
65
|
+
/**
|
|
66
|
+
* Constructs a new State instance.
|
|
67
|
+
* @param {Hanko} hanko - The Hanko instance for API interactions.
|
|
68
|
+
* @param {FlowName} flowName - The name of the flow this state belongs to.
|
|
69
|
+
* @param {FlowResponse<TState>} response - The flow response containing state data.
|
|
70
|
+
* @param {StateInitConfig} [options={}] - Configuration options for state initialization.
|
|
71
|
+
*/
|
|
72
|
+
constructor(hanko: Hanko, flowName: FlowName, response: FlowResponse<TState>, options?: StateInitConfig);
|
|
73
|
+
/**
|
|
74
|
+
* Builds the action map for this state, wrapping it in a Proxy to handle undefined actions.
|
|
75
|
+
* @param {Actions} actions - The actions available in this state.
|
|
76
|
+
* @returns {ActionMap<TState>} The action map for the state.
|
|
77
|
+
* @private
|
|
78
|
+
*/
|
|
79
|
+
private buildActionMap;
|
|
80
|
+
/**
|
|
81
|
+
* Dispatches an event after the state has changed.
|
|
82
|
+
*/
|
|
83
|
+
dispatchAfterStateChangeEvent(): void;
|
|
84
|
+
/**
|
|
85
|
+
* Serializes the current state into a storable format.
|
|
86
|
+
* @returns {SerializedState} The serialized state object.
|
|
87
|
+
*/
|
|
88
|
+
serialize(): SerializedState;
|
|
89
|
+
/**
|
|
90
|
+
* Saves the current state to localStorage.
|
|
91
|
+
* @returns {void}
|
|
92
|
+
*/
|
|
93
|
+
saveToLocalStorage(): void;
|
|
94
|
+
/**
|
|
95
|
+
* Removes the current state from localStorage.
|
|
96
|
+
* @returns {void}
|
|
97
|
+
*/
|
|
98
|
+
removeFromLocalStorage(): void;
|
|
99
|
+
/**
|
|
100
|
+
* Initializes a flow state, processing auto-steps if applicable.
|
|
101
|
+
* @param {Hanko} hanko - The Hanko instance for API interactions.
|
|
102
|
+
* @param {FlowName} flowName - The name of the flow.
|
|
103
|
+
* @param {FlowResponse<any>} response - The initial flow response.
|
|
104
|
+
* @param {StateInitConfig} [options={}] - Configuration options.
|
|
105
|
+
* @param {boolean} [options.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.
|
|
106
|
+
* @param {AutoStepExclusion} [options.excludeAutoSteps=null] - States to exclude from auto-step processing, or "all".
|
|
107
|
+
* @param {ActionInfo} [options.previousAction=null] - Information about the previous action.
|
|
108
|
+
* @param {boolean} [options.isCached=false] - Whether the state is loaded from cache.
|
|
109
|
+
* @param {string} [options.cacheKey="hanko-flow-state"] - Key for localStorage caching.
|
|
110
|
+
* @returns {Promise<AnyState>} A promise resolving to the initialized state.
|
|
111
|
+
*/
|
|
112
|
+
static initializeFlowState(hanko: Hanko, flowName: FlowName, response: FlowResponse<any>, options?: StateInitConfig): Promise<AnyState>;
|
|
113
|
+
/**
|
|
114
|
+
* Retrieves and parses state data from localStorage.
|
|
115
|
+
* @param {string} cacheKey - The key used to store the state in localStorage.
|
|
116
|
+
* @returns {SerializedState | undefined} The parsed serialized state, or undefined if not found or invalid.
|
|
117
|
+
*/
|
|
118
|
+
static readFromLocalStorage(cacheKey: string): SerializedState | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* Creates a new state instance, using cached or fetched data.
|
|
121
|
+
* @param {Hanko} hanko - The Hanko instance for API interactions.
|
|
122
|
+
* @param {FlowName} flowName - The name of the flow.
|
|
123
|
+
* @param {StateCreateConfig} [config={}] - Configuration options.
|
|
124
|
+
* @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.
|
|
125
|
+
* @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or "all".
|
|
126
|
+
* @param {string} [config.cacheKey="hanko-flow-state"] - Key for localStorage caching.
|
|
127
|
+
* @param {boolean} [config.loadFromCache=true] - Whether to attempt loading from cache.
|
|
128
|
+
* @returns {Promise<AnyState>} A promise resolving to the created state.
|
|
129
|
+
*/
|
|
130
|
+
static create(hanko: Hanko, flowName: FlowName, config?: StateCreateConfig): Promise<AnyState>;
|
|
131
|
+
/**
|
|
132
|
+
* Deserializes a state from a serialized state object.
|
|
133
|
+
* @param {Hanko} hanko - The Hanko instance for API interactions.
|
|
134
|
+
* @param {SerializedState} serializedState - The serialized state data.
|
|
135
|
+
* @param {StateCreateConfig} [config={}] - Configuration options.
|
|
136
|
+
* @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.
|
|
137
|
+
* @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or "all".
|
|
138
|
+
* @param {string} [config.cacheKey="hanko-flow-state"] - Key for localStorage caching.
|
|
139
|
+
* @param {boolean} [config.loadFromCache=true] - Whether to attempt loading from cache.
|
|
140
|
+
* @returns {Promise<AnyState>} A promise resolving to the deserialized state.
|
|
141
|
+
*/
|
|
142
|
+
static deserialize(hanko: Hanko, serializedState: SerializedState, config?: StateCreateConfig): Promise<AnyState>;
|
|
143
|
+
/**
|
|
144
|
+
* Fetches state data from the server.
|
|
145
|
+
* @param {Hanko} hanko - The Hanko instance for API interactions.
|
|
146
|
+
* @param {string} href - The endpoint to fetch from.
|
|
147
|
+
* @param {any} [body] - Optional request body.
|
|
148
|
+
* @returns {Promise<FlowResponse<any>>} A promise resolving to the flow response.
|
|
149
|
+
*/
|
|
150
|
+
static fetchState(hanko: Hanko, href: string, body?: any): Promise<FlowResponse<any>>;
|
|
151
|
+
/**
|
|
152
|
+
* Creates an error flow response.
|
|
153
|
+
* @param {FlowError} error - The error to include in the response.
|
|
154
|
+
* @returns {FlowResponse<"error">} A flow response with error details.
|
|
155
|
+
* @private
|
|
156
|
+
*/
|
|
157
|
+
private static createErrorResponse;
|
|
54
158
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
159
|
+
/**
|
|
160
|
+
* Represents an actionable operation within a state.
|
|
161
|
+
* @template TInputs - The type of inputs required for the action.
|
|
162
|
+
* @param {ActionType<TInputs>} action - The action type definition.
|
|
163
|
+
* @param {State} parentState - The state this action belongs to.
|
|
164
|
+
* @param {boolean} [enabled=true] - Whether the action is enabled.
|
|
165
|
+
* @category SDK
|
|
166
|
+
* @subcategory FlowAPI
|
|
167
|
+
*/
|
|
168
|
+
export declare class Action<TInputs> {
|
|
169
|
+
readonly enabled: boolean;
|
|
170
|
+
readonly href: string;
|
|
171
|
+
readonly name: string;
|
|
172
|
+
readonly inputs: TInputs;
|
|
173
|
+
private readonly parentState;
|
|
174
|
+
/**
|
|
175
|
+
* Constructs a new Action instance.
|
|
176
|
+
* @param {ActionType<TInputs>} action - The action type definition.
|
|
177
|
+
* @param {State} parentState - The state this action belongs to.
|
|
178
|
+
* @param {boolean} [enabled=true] - Whether the action is enabled.
|
|
179
|
+
*/
|
|
180
|
+
constructor(action: ActionType<TInputs>, parentState: State, enabled?: boolean);
|
|
181
|
+
/**
|
|
182
|
+
* Creates a disabled action instance.
|
|
183
|
+
* @template TInputs - The type of inputs (inferred as empty).
|
|
184
|
+
* @param {string} name - The name of the action.
|
|
185
|
+
* @param {State} parentState - The state this action belongs to.
|
|
186
|
+
* @returns {Action<TInputs>} A disabled action instance.
|
|
187
|
+
*/
|
|
188
|
+
static createDisabled<TInputs>(name: string, parentState: State): Action<TInputs>;
|
|
189
|
+
/**
|
|
190
|
+
* Executes the action, transitioning to a new state.
|
|
191
|
+
* @param {ExtractInputValues<TInputs>} [inputValues=null] - Values for the action's inputs.
|
|
192
|
+
* @param {ActionRunConfig} [config={}] - Configuration options.
|
|
193
|
+
* @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.
|
|
194
|
+
* @returns {Promise<AnyState>} A promise resolving to the next state.
|
|
195
|
+
* @throws {FlowError} If the action is disabled or already invoked.
|
|
196
|
+
*/
|
|
197
|
+
run(inputValues?: ExtractInputValues<TInputs>, config?: ActionRunConfig): Promise<AnyState>;
|
|
67
198
|
}
|
|
68
|
-
export
|
|
69
|
-
export { State };
|
|
199
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { CredentialRequestOptionsJSON, CredentialCreationOptionsJSON, PublicKeyCredentialWithAssertionJSON, PublicKeyCredentialWithAttestationJSON } from "@github/webauthn-json";
|
|
2
|
+
/**
|
|
3
|
+
* Manages WebAuthn credential operations as a singleton, ensuring only one active request at a time.
|
|
4
|
+
* Uses an internal AbortController to cancel previous requests when a new one is initiated.
|
|
5
|
+
*/
|
|
6
|
+
declare class WebauthnManager {
|
|
7
|
+
private static instance;
|
|
8
|
+
private abortController;
|
|
9
|
+
private constructor();
|
|
10
|
+
/**
|
|
11
|
+
* Gets the singleton instance of WebauthnManager.
|
|
12
|
+
* Creates a new instance if one doesn't exist, otherwise returns the existing one.
|
|
13
|
+
* @returns {WebauthnManager} The singleton instance
|
|
14
|
+
*/
|
|
15
|
+
static getInstance(): WebauthnManager;
|
|
16
|
+
/**
|
|
17
|
+
* Creates a new abort signal, aborting any ongoing WebAuthn request.
|
|
18
|
+
* @private
|
|
19
|
+
* @returns {AbortSignal} The new abort signal
|
|
20
|
+
*/
|
|
21
|
+
private createAbortSignal;
|
|
22
|
+
/**
|
|
23
|
+
* Retrieves a WebAuthn credential using the provided options.
|
|
24
|
+
* Aborts any previous request before starting a new one.
|
|
25
|
+
* @param {CredentialRequestOptionsJSON} options - The options for credential retrieval
|
|
26
|
+
* @returns {Promise<PublicKeyCredentialWithAssertionJSON>} A promise resolving to the retrieved credential
|
|
27
|
+
* @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)
|
|
28
|
+
*/
|
|
29
|
+
getWebauthnCredential(options: CredentialRequestOptionsJSON): Promise<PublicKeyCredentialWithAssertionJSON>;
|
|
30
|
+
/**
|
|
31
|
+
* Retrieves a WebAuthn credential with conditional UI mediation.
|
|
32
|
+
* Aborts any previous request before starting a new one.
|
|
33
|
+
* @param {CredentialRequestOptionsJSON} publicKey - The public key options for conditional retrieval
|
|
34
|
+
* @returns {Promise<PublicKeyCredentialWithAssertionJSON>} A promise resolving to the retrieved credential
|
|
35
|
+
* @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)
|
|
36
|
+
*/
|
|
37
|
+
getConditionalWebauthnCredential(publicKey: CredentialRequestOptionsJSON["publicKey"]): Promise<PublicKeyCredentialWithAssertionJSON>;
|
|
38
|
+
/**
|
|
39
|
+
* Creates a new WebAuthn credential using the provided options.
|
|
40
|
+
* Aborts any previous request before starting a new one.
|
|
41
|
+
* @param {CredentialCreationOptionsJSON} options - The options for credential creation
|
|
42
|
+
* @returns {Promise<PublicKeyCredentialWithAttestationJSON>} A promise resolving to the created credential
|
|
43
|
+
* @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)
|
|
44
|
+
*/
|
|
45
|
+
createWebauthnCredential(options: CredentialCreationOptionsJSON): Promise<PublicKeyCredentialWithAttestationJSON>;
|
|
46
|
+
}
|
|
47
|
+
export default WebauthnManager;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ContinueWithLoginIdentifierInputs, EmailCreateInputs, EmailDeleteInputs, EmailSetPrimaryInputs, EmailVerifyInputs, ExchangeTokenInputs, PasskeyCredentialDeleteInputs, PasskeyCredentialRenameInputs, PasswordRecoveryInputs, PasswordInputs, RegisterClientCapabilitiesInputs, RegisterLoginIdentifierInputs, RegisterPasswordInputs, ThirdpartyOauthInputs, UsernameSetInputs, VerifyPasscodeInputs, WebauthnVerifyAssertionResponseInputs, WebauthnVerifyAttestationResponseInputs, SessionDeleteInputs, OTPCodeInputs, SecurityKeyDeleteInputs, RememberMeInputs } from "./input";
|
|
2
2
|
export interface Action<TInputs> {
|
|
3
|
-
|
|
3
|
+
action: string;
|
|
4
4
|
href: string;
|
|
5
5
|
inputs: TInputs;
|
|
6
6
|
description: string;
|
|
@@ -123,4 +123,5 @@ export interface DeviceTrustActions {
|
|
|
123
123
|
}
|
|
124
124
|
export interface ThirdPartyActions {
|
|
125
125
|
readonly exchange_token: Action<ExchangeTokenInputs>;
|
|
126
|
+
readonly back?: Action<null>;
|
|
126
127
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { StateName, Actions, Payloads } from "./state";
|
|
2
|
+
import { FlowError } from "./flowError";
|
|
3
|
+
import { State } from "../State";
|
|
4
|
+
type PickStates<TState extends StateName> = TState;
|
|
5
|
+
export type FlowName = "login" | "registration" | "profile" | "token_exchange";
|
|
6
|
+
export type AnyState = {
|
|
7
|
+
[TState in StateName]: State<TState>;
|
|
8
|
+
}[StateName];
|
|
9
|
+
export type AutoStep<TState extends StateName> = (state: State<TState>) => Promise<AnyState>;
|
|
10
|
+
export type AutoSteps = {
|
|
11
|
+
[TState in PickStates<"preflight" | "login_passkey" | "onboarding_verify_passkey_attestation" | "webauthn_credential_verification" | "thirdparty" | "success" | "account_deleted">]: AutoStep<TState>;
|
|
12
|
+
};
|
|
13
|
+
export type PasskeyAutofillActivationHandler<TState extends StateName> = (state: State<TState>) => Promise<void>;
|
|
14
|
+
export type PasskeyAutofillActivationHandlers = {
|
|
15
|
+
[TState in PickStates<"login_init">]: PasskeyAutofillActivationHandler<TState>;
|
|
16
|
+
};
|
|
17
|
+
export interface FlowResponse<TState extends StateName> {
|
|
18
|
+
name: TState;
|
|
19
|
+
status: number;
|
|
20
|
+
payload?: Payloads[TState];
|
|
21
|
+
actions?: Actions[TState];
|
|
22
|
+
csrf_token: string;
|
|
23
|
+
error?: FlowError;
|
|
24
|
+
}
|
|
25
|
+
export {};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { FlowError } from "./flowError";
|
|
2
2
|
import { PublicKeyCredentialWithAssertionJSON, PublicKeyCredentialWithAttestationJSON } from "@github/webauthn-json";
|
|
3
3
|
export interface Input<TValue> {
|
|
4
4
|
readonly name: string;
|
|
5
5
|
readonly type: string;
|
|
6
|
-
value?: TValue;
|
|
6
|
+
readonly value?: TValue;
|
|
7
7
|
readonly min_length?: number;
|
|
8
8
|
readonly max_length?: number;
|
|
9
9
|
readonly required?: boolean;
|
|
10
10
|
readonly hidden?: boolean;
|
|
11
|
-
readonly error?:
|
|
11
|
+
readonly error?: FlowError;
|
|
12
12
|
readonly allowed_values?: AllowedInputValues[];
|
|
13
13
|
}
|
|
14
14
|
export interface AllowedInputValues {
|
|
@@ -35,7 +35,6 @@ export interface RegisterClientCapabilitiesInputs {
|
|
|
35
35
|
readonly webauthn_available: Input<boolean>;
|
|
36
36
|
readonly webauthn_conditional_mediation_available: Input<boolean>;
|
|
37
37
|
readonly webauthn_platform_authenticator_available: Input<boolean>;
|
|
38
|
-
readonly trusted_device: Input<boolean>;
|
|
39
38
|
}
|
|
40
39
|
export interface ContinueWithLoginIdentifierInputs {
|
|
41
40
|
readonly identifier?: Input<string>;
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { State } from "../State";
|
|
2
1
|
import { CredentialOnboardingChooserActions, DeviceTrustActions, LoginInitActions, LoginMethodChooserActions, LoginOTPActions, LoginPasskeyActions, LoginPasswordActions, LoginPasswordRecoveryActions, LoginSecurityKeyActions, MFAAOTPSecretCreationActions, MFAMethodChooserActions, MFASecurityKeyCreationActions, OnboardingCreatePasskeyActions, OnboardingEmailActions, OnboardingUsernameActions, OnboardingVerifyPasskeyAttestationActions, PasscodeConfirmationActions, PasswordCreationActions, PreflightActions, ProfileInitActions, RegistrationInitActions, ThirdPartyActions } from "./action";
|
|
3
2
|
import { LoginInitPayload, LoginPasskeyPayload, MFAOTPSecretCreationPayload, OnboardingVerifyPasskeyAttestationPayload, PasscodeConfirmationPayload, ProfilePayload, SuccessPayload, ThirdPartyPayload } from "./payload";
|
|
4
3
|
export type StateName = "account_deleted" | "credential_onboarding_chooser" | "device_trust" | "error" | "login_init" | "login_method_chooser" | "login_otp" | "login_passkey" | "login_password" | "login_password_recovery" | "login_security_key" | "mfa_method_chooser" | "mfa_otp_secret_creation" | "mfa_security_key_creation" | "onboarding_create_passkey" | "onboarding_email" | "onboarding_username" | "onboarding_verify_passkey_attestation" | "passcode_confirmation" | "password_creation" | "preflight" | "profile_init" | "registration_init" | "success" | "thirdparty" | "webauthn_credential_verification";
|
|
@@ -58,9 +57,3 @@ export interface Payloads {
|
|
|
58
57
|
readonly thirdparty: ThirdPartyPayload;
|
|
59
58
|
readonly webauthn_credential_verification: OnboardingVerifyPasskeyAttestationPayload;
|
|
60
59
|
}
|
|
61
|
-
export type FlowPath = "/login" | "/registration" | "/profile" | "/token_exchange";
|
|
62
|
-
export type FetchNextState = (href: string, body?: any) => Promise<State<any>>;
|
|
63
|
-
export type HandlerFunction<TStateName extends StateName> = (state: State<TStateName>) => any;
|
|
64
|
-
export type Handlers = {
|
|
65
|
-
[TStateName in StateName]: HandlerFunction<TStateName>;
|
|
66
|
-
};
|
package/dist/sdk.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},e.apply(this,arguments)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,i(e,t)}function n(e){return n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},n(e)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function r(e,t,n){return r=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&i(o,n.prototype),o},r.apply(null,arguments)}function o(e){var t="function"==typeof Map?new Map:void 0;return o=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,o)}function o(){return r(e,arguments,n(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),i(o,e)},o(e)}function s(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var a=0;function c(e){return"__private_"+a+++"_"+e}function u(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var h=/*#__PURE__*/function(e){function n(t,i,r){var o;return(o=e.call(this,t)||this).code=void 0,o.cause=void 0,o.code=i,o.cause=r,Object.setPrototypeOf(s(o),n.prototype),o}return t(n,e),n}(/*#__PURE__*/o(Error)),l=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),d=/*#__PURE__*/function(e){function n(t,i){var r;return r=e.call(this,"Conflict error","conflict",i)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(h),p=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),f=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),v=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),m=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),y=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),w=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),g=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),k=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),E=/*#__PURE__*/function(e){function n(t,i){var r;return(r=e.call(this,"Too many requests error","tooManyRequests",i)||this).retryAfter=void 0,r.retryAfter=t,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(h),S=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),x=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Forbidden error","forbidden",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),b=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),C=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),P=/*#__PURE__*/function(e){function n(t){var i;return i=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",t)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),O=/*#__PURE__*/function(e){function n(t,i){var r;return r=e.call(this,"An error occurred during third party sign up/sign in",t,i)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(h),j="hanko-session-created",_="hanko-session-expired",I="hanko-user-logged-out",L="hanko-user-deleted",T=/*#__PURE__*/function(e){function n(t,n){return e.call(this,t,{detail:n})||this}return t(n,e),n}(/*#__PURE__*/o(CustomEvent)),A=/*#__PURE__*/function(){function e(){this._dispatchEvent=document.dispatchEvent.bind(document)}var t=e.prototype;return t.dispatch=function(e,t){this._dispatchEvent(new T(e,t))},t.dispatchSessionCreatedEvent=function(e){this.dispatch(j,e)},t.dispatchSessionExpiredEvent=function(){this.dispatch(_,null)},t.dispatchUserLoggedOutEvent=function(){this.dispatch(I,null)},t.dispatchUserDeletedEvent=function(){this.dispatch(L,null)},e}();function N(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)e[i]=n[i]}return e}var R,D=function e(t,n){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=N({},n,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in r)r[s]&&(o+="; "+s,!0!==r[s]&&(o+="="+r[s].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],i={},r=0;r<n.length;r++){var o=n[r].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(i[a]=t.read(s,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",N({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,N({},this.attributes,t))},withConverter:function(t){return e(N({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),q=/*#__PURE__*/function(){function t(e){var t;this.authCookieName=void 0,this.authCookieDomain=void 0,this.authCookieSameSite=void 0,this.authCookieName=e.cookieName,this.authCookieDomain=e.cookieDomain,this.authCookieSameSite=null!=(t=e.cookieSameSite)?t:"lax"}var n=t.prototype;return n.getAuthCookie=function(){return D.get(this.authCookieName)},n.setAuthCookie=function(t,n){var i={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(i.domain=this.authCookieDomain);var r=e({},i,n);if(("none"===r.sameSite||"None"===r.sameSite)&&!1===r.secure)throw new l(new Error("Secure attribute must be set when SameSite=None"));D.set(this.authCookieName,t,r)},n.removeAuthCookie=function(){D.remove(this.authCookieName)},t}(),M=/*#__PURE__*/function(){function e(e){this.keyName=void 0,this.keyName=e.keyName}var t=e.prototype;return t.getSessionToken=function(){return sessionStorage.getItem(this.keyName)},t.setSessionToken=function(e){sessionStorage.setItem(this.keyName,e)},t.removeSessionToken=function(){sessionStorage.removeItem(this.keyName)},e}(),U=/*#__PURE__*/function(){function e(e){this._xhr=void 0,this._xhr=e}return e.prototype.getResponseHeader=function(e){return this._xhr.getResponseHeader(e)},e}(),W=/*#__PURE__*/function(){function e(e){this.headers=void 0,this.ok=void 0,this.status=void 0,this.statusText=void 0,this.url=void 0,this._decodedJSON=void 0,this.xhr=void 0,this.headers=new U(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}var t=e.prototype;return t.json=function(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON},t.parseNumericHeader=function(e){var t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t},e}(),H=/*#__PURE__*/function(){function t(t,n){this.timeout=void 0,this.api=void 0,this.dispatcher=void 0,this.cookie=void 0,this.sessionTokenStorage=void 0,this.lang=void 0,this.sessionTokenLocation=void 0,this.api=t,this.timeout=n.timeout,this.dispatcher=new A,this.cookie=new q(e({},n)),this.sessionTokenStorage=new M({keyName:n.cookieName}),this.lang=n.lang,this.sessionTokenLocation=n.sessionTokenLocation}var n=t.prototype;return n._fetch=function(e,t,n){void 0===n&&(n=new XMLHttpRequest);var i=this,r=this.api+e,o=this.timeout,s=this.getAuthToken(),a=this.lang;return new Promise(function(e,c){n.open(t.method,r,!0),n.setRequestHeader("Accept","application/json"),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("X-Language",a),s&&n.setRequestHeader("Authorization","Bearer "+s),n.timeout=o,n.withCredentials=!0,n.onload=function(){i.processHeaders(n),e(new W(n))},n.onerror=function(){c(new l)},n.ontimeout=function(){c(new p)},n.send(t.body?t.body.toString():null)})},n._fetch_blocking=function(e,t,n){void 0===n&&(n=new XMLHttpRequest);var i=this.api+e,r=this.getAuthToken();return n.open(t.method,i,!1),n.setRequestHeader("Accept","application/json"),n.setRequestHeader("Content-Type","application/json"),r&&n.setRequestHeader("Authorization","Bearer "+r),n.withCredentials=!0,n.send(t.body?t.body.toString():null),n.responseText},n.processHeaders=function(e){var t="",n=0,i="";if(e.getAllResponseHeaders().split("\r\n").forEach(function(r){var o=r.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?n=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(i=e.getResponseHeader("X-Session-Retention"))}),t){var r=new RegExp("^https://"),o=!!this.api.match(r)&&!!window.location.href.match(r),s="session"===i?void 0:new Date((new Date).getTime()+1e3*n);this.setAuthToken(t,{secure:o,expires:s})}},n.get=function(e){return this._fetch(e,{method:"GET"})},n.post=function(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})},n.put=function(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})},n.patch=function(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})},n.delete=function(e){return this._fetch(e,{method:"DELETE"})},n.getAuthToken=function(){var e="";switch(this.sessionTokenLocation){case"cookie":e=this.cookie.getAuthCookie();break;case"sessionStorage":e=this.sessionTokenStorage.getSessionToken()}return e},n.setAuthToken=function(e,t){switch(this.sessionTokenLocation){case"cookie":return this.cookie.setAuthCookie(e,t);case"sessionStorage":return this.sessionTokenStorage.setSessionToken(e)}},t}(),K=function(e,t){this.client=void 0,this.client=new H(e,t)},F=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var i=n.prototype;return i.getDomain=function(e){if(!e)throw new O("somethingWentWrong",new Error("email missing from request"));var t=e.split("@");if(2!==t.length)throw new O("somethingWentWrong",new Error("email is not in a valid email format."));var n=t[1].trim();if(""===n)throw new O("somethingWentWrong",new Error("email is not in a valid email format."));return n},i.hasProvider=function(e){try{var t=this.getDomain(e);return Promise.resolve(this.client.get("/saml/provider?domain="+t).then(function(e){if(404==e.status)throw new k(new Error("provider not found"));if(!e.ok)throw new l(new Error("unable to fetch provider"));return e.ok}))}catch(e){return Promise.reject(e)}},i.auth=function(e,t){var n=new URL("/saml/auth",this.client.api),i=this.getDomain(e);if(!t)throw new O("somethingWentWrong",new Error("redirectTo missing from request"));n.searchParams.append("domain",i),n.searchParams.append("redirect_to",t),window.location.assign(n.href)},i.getError=function(){var e=new URLSearchParams(window.location.search),t=e.get("error"),n=e.get("error_description");if(t){var i;switch(t){case"access_denied":i="enterpriseAccessDenied";break;case"user_conflict":i="emailAddressAlreadyExistsError";break;case"multiple_accounts":i="enterpriseMultipleAccounts";break;case"unverified_email":i="enterpriseUnverifiedEmail";break;case"email_maxnum":i="maxNumOfEmailAddressesReached";break;default:i="somethingWentWrong"}return new O(i,new Error(n))}},n}(K),J=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var i=n.prototype;return i.getInfo=function(e){try{return Promise.resolve(this.client.post("/user",{email:e})).then(function(e){if(404===e.status)throw new k;if(!e.ok)throw new l;return e.json()})}catch(e){return Promise.reject(e)}},i.create=function(e){try{return Promise.resolve(this.client.post("/users",{email:e})).then(function(e){if(409===e.status)throw new d;if(403===e.status)throw new x;if(!e.ok)throw new l;return e.json()})}catch(e){return Promise.reject(e)}},i.getCurrent=function(){try{var e=this;return Promise.resolve(e.client.get("/me")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new S;if(!t.ok)throw new l;var n=t.json();return Promise.resolve(e.client.get("/users/"+n.id)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new S;if(!t.ok)throw new l;return t.json()})})}catch(e){return Promise.reject(e)}},i.delete=function(){try{var e=this;return Promise.resolve(e.client.delete("/user")).then(function(t){if(t.ok)return e.client.sessionTokenStorage.removeSessionToken(),e.client.cookie.removeAuthCookie(),void e.client.dispatcher.dispatchUserDeletedEvent();if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new S;throw new l})}catch(e){return Promise.reject(e)}},i.logout=function(){try{var e=this;return Promise.resolve(e.client.post("/logout")).then(function(t){if(e.client.sessionTokenStorage.removeSessionToken(),e.client.cookie.removeAuthCookie(),e.client.dispatcher.dispatchUserLoggedOutEvent(),401===t.status);else if(!t.ok)throw new l})}catch(e){return Promise.reject(e)}},n}(K),B=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var i=n.prototype;return i.list=function(){try{var e=this;return Promise.resolve(e.client.get("/emails")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new S;if(!t.ok)throw new l;return t.json()})}catch(e){return Promise.reject(e)}},i.create=function(e){try{var t=this;return Promise.resolve(t.client.post("/emails",{address:e})).then(function(e){if(e.ok)return e.json();if(400===e.status)throw new P;if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new S;if(409===e.status)throw new C;throw new l})}catch(e){return Promise.reject(e)}},i.setPrimaryEmail=function(e){try{var t=this;return Promise.resolve(t.client.post("/emails/"+e+"/set_primary")).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new S;if(!e.ok)throw new l})}catch(e){return Promise.reject(e)}},i.delete=function(e){try{var t=this;return Promise.resolve(t.client.delete("/emails/"+e)).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new S;if(!e.ok)throw new l})}catch(e){return Promise.reject(e)}},n}(K),z=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var i=n.prototype;return i.auth=function(e,t){try{var n=new URL("/thirdparty/auth",this.client.api);if(!e)throw new O("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new O("somethingWentWrong",new Error("redirectTo missing from request"));return n.searchParams.append("provider",e),n.searchParams.append("redirect_to",t),window.location.assign(n.href),Promise.resolve()}catch(e){return Promise.reject(e)}},i.getError=function(){var e=new URLSearchParams(window.location.search),t=e.get("error"),n=e.get("error_description");if(t){var i="";switch(t){case"access_denied":i="thirdPartyAccessDenied";break;case"user_conflict":i="emailAddressAlreadyExistsError";break;case"multiple_accounts":i="thirdPartyMultipleAccounts";break;case"unverified_email":i="thirdPartyUnverifiedEmail";break;case"email_maxnum":i="maxNumOfEmailAddressesReached";break;case"signup_disabled":i="signupDisabled";break;default:i="somethingWentWrong"}return new O(i,new Error(n))}},n}(K),V=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.validate=function(){try{var e=new URLSearchParams(window.location.search).get("hanko_token");return e?(window.history.replaceState(null,null,window.location.pathname),Promise.resolve(this.client.post("/token",{value:e})).then(function(e){if(!e.ok)throw new l;return e.json()})):Promise.resolve()}catch(e){return Promise.reject(e)}},n}(K),X=/*#__PURE__*/function(){function e(){}return e.throttle=function(e,t,n){void 0===n&&(n={});var i,r,o,s=n.leading,a=void 0===s||s,c=n.trailing,u=void 0===c||c,h=0,l=function(){h=!1===a?0:Date.now(),o=null,e.apply(i,r)};return function(){var n=Date.now();h||!1!==a||(h=n);var s=t-(n-h);i=this,r=[].slice.call(arguments),s<=0||s>t?(o&&(window.clearTimeout(o),o=null),h=n,e.apply(i,r)):o||!1===u||(o=window.setTimeout(l,s))}},e}(),G=/*#__PURE__*/function(){function e(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=X.throttle}var t=e.prototype;return t.wrapCallback=function(e,t){var n=function(t){e(t.detail)};return t?this._throttle(n,this.throttleLimit,{leading:!0,trailing:!1}):n},t.addEventListenerWithType=function(e){var t=this,n=e.type,i=e.once,r=void 0!==i&&i,o=e.throttle,s=this.wrapCallback(e.callback,void 0!==o&&o);return this._addEventListener(n,s,{once:r}),function(){return t._removeEventListener(n,s)}},e.mapAddEventListenerParams=function(e,t,n){return{type:e,callback:t.callback,once:t.once,throttle:n}},t.addEventListener=function(t,n,i){return this.addEventListenerWithType(e.mapAddEventListenerParams(t,n,i))},t.onSessionCreated=function(e,t){return this.addEventListener(j,{callback:e,once:t},!0)},t.onSessionExpired=function(e,t){return this.addEventListener(_,{callback:e,once:t},!0)},t.onUserLoggedOut=function(e,t){return this.addEventListener(I,{callback:e,once:t})},t.onUserDeleted=function(e,t){return this.addEventListener(L,{callback:e,once:t})},e}(),Q=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.validate=function(){try{return Promise.resolve(this.client.get("/sessions/validate")).then(function(e){if(!e.ok)throw new l;return Promise.resolve(e.json())})}catch(e){return Promise.reject(e)}},n}(K),Y=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.isValid=function(){var e;try{var t=this.client._fetch_blocking("/sessions/validate",{method:"GET"});e=JSON.parse(t)}catch(e){throw new l(e)}return!!e&&e.is_valid},n}(K),Z=/*#__PURE__*/function(){function e(e){this.storageKey=void 0,this.defaultState={expiration:0,lastCheck:0},this.storageKey=e}var t=e.prototype;return t.load=function(){var e=window.localStorage.getItem(this.storageKey);return null==e?this.defaultState:JSON.parse(e)},t.save=function(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e||this.defaultState))},e}(),$=function(e,t){var n=this;this.onActivityCallback=void 0,this.onInactivityCallback=void 0,this.handleFocus=function(){n.onActivityCallback()},this.handleBlur=function(){n.onInactivityCallback()},this.handleVisibilityChange=function(){"visible"===document.visibilityState?n.onActivityCallback():n.onInactivityCallback()},this.hasFocus=function(){return document.hasFocus()},this.onActivityCallback=e,this.onInactivityCallback=t,window.addEventListener("focus",this.handleFocus),window.addEventListener("blur",this.handleBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange)},ee=/*#__PURE__*/function(){function e(e,t,n){this.intervalID=null,this.timeoutID=null,this.checkInterval=void 0,this.checkSession=void 0,this.onSessionExpired=void 0,this.checkInterval=e,this.checkSession=t,this.onSessionExpired=n}var t=e.prototype;return t.scheduleSessionExpiry=function(e){var t=this;this.stop(),this.timeoutID=setTimeout(function(){try{return t.stop(),t.onSessionExpired(),Promise.resolve()}catch(e){return Promise.reject(e)}},e)},t.start=function(e,t){var n=this;void 0===e&&(e=0),void 0===t&&(t=0);var i=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(i):this.timeoutID=setTimeout(function(){try{return Promise.resolve(n.checkSession()).then(function(e){if(e.is_valid){if(n.sessionExpiresSoon(e.expiration))return void n.scheduleSessionExpiry(e.expiration-Date.now());n.intervalID=setInterval(function(){try{return Promise.resolve(n.checkSession()).then(function(t){(e=t).is_valid?n.sessionExpiresSoon(e.expiration)&&n.scheduleSessionExpiry(e.expiration-Date.now()):n.stop()})}catch(e){return Promise.reject(e)}},n.checkInterval)}else n.stop()})}catch(e){return Promise.reject(e)}},i)},t.stop=function(){this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null),this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)},t.isRunning=function(){return null!==this.timeoutID||null!==this.intervalID},t.sessionExpiresSoon=function(e){return e>0&&e-Date.now()<=this.checkInterval},t.calcTimeToNextCheck=function(e){var t=Date.now()-e;return this.checkInterval>=t?this.checkInterval-t%this.checkInterval:0},e}(),te=/*#__PURE__*/function(){function e(e,t,n,i){var r=this;void 0===e&&(e="hanko_session"),this.channel=void 0,this.onSessionExpired=void 0,this.onSessionCreated=void 0,this.onLeadershipRequested=void 0,this.handleMessage=function(e){var t=e.data;switch(t.action){case"sessionExpired":r.onSessionExpired(t);break;case"sessionCreated":r.onSessionCreated(t);break;case"requestLeadership":r.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=n,this.onLeadershipRequested=i,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}return e.prototype.post=function(e){this.channel.postMessage(e)},e}(),ne=/*#__PURE__*/function(e){function n(t,n){var i;(i=e.call(this)||this).listener=new G,i.checkInterval=3e4,i.client=void 0,i.sessionState=void 0,i.windowActivityManager=void 0,i.scheduler=void 0,i.sessionChannel=void 0,i.isLoggedIn=void 0,i.client=new Q(t,n),i.checkInterval=n.sessionCheckInterval,i.sessionState=new Z(n.cookieName+"_session_state"),i.sessionChannel=new te(i.getSessionCheckChannelName(n.sessionTokenLocation,n.sessionCheckChannelName),function(){return i.onChannelSessionExpired()},function(e){return i.onChannelSessionCreated(e)},function(){return i.onChannelLeadershipRequested()}),i.scheduler=new ee(i.checkInterval,function(){return i.checkSession()},function(){return i.onSessionExpired()}),i.windowActivityManager=new $(function(){return i.startSessionCheck()},function(){return i.scheduler.stop()});var r=Date.now(),o=i.sessionState.load();return i.isLoggedIn=r<o.expiration,i.initializeEventListeners(),i.startSessionCheck(),i}t(n,e);var i=n.prototype;return i.initializeEventListeners=function(){var e=this;this.listener.onSessionCreated(function(t){var n=t.claims,i=Date.parse(n.expiration),r=Date.now();e.isLoggedIn=!0,e.sessionState.save({expiration:i,lastCheck:r}),e.sessionChannel.post({action:"sessionCreated",claims:n}),e.startSessionCheck()}),this.listener.onUserLoggedOut(function(){e.isLoggedIn=!1,e.sessionChannel.post({action:"sessionExpired"}),e.sessionState.save(null),e.scheduler.stop()}),window.addEventListener("beforeunload",function(){return e.scheduler.stop()})},i.startSessionCheck=function(){if(this.windowActivityManager.hasFocus()&&(this.sessionChannel.post({action:"requestLeadership"}),!this.scheduler.isRunning())){var e=this.sessionState.load();this.isLoggedIn&&this.scheduler.start(e.lastCheck,e.expiration)}},i.checkSession=function(){try{var e=this,t=Date.now();return Promise.resolve(e.client.validate()).then(function(n){var i=n.is_valid,r=n.claims,o=n.expiration_time,s=o?Date.parse(o):0;return!i&&e.isLoggedIn&&e.dispatchSessionExpiredEvent(),i?(e.isLoggedIn=!0,e.sessionState.save({lastCheck:t,expiration:s})):(e.isLoggedIn=!1,e.sessionState.save(null),e.sessionChannel.post({action:"sessionExpired"})),{is_valid:i,claims:r,expiration:s}})}catch(e){return Promise.reject(e)}},i.onSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())},i.onChannelSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())},i.onChannelSessionCreated=function(e){var t=e.claims,n=Date.now(),i=Date.parse(t.expiration)-n;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:i})},i.onChannelLeadershipRequested=function(){this.windowActivityManager.hasFocus()||this.scheduler.stop()},i.getSessionCheckChannelName=function(e,t){if("cookie"==e)return t;var n=sessionStorage.getItem("sessionCheckChannelName");return null!=n&&""!==n||(n=t+"-"+(Math.floor(100*Math.random())+1),sessionStorage.setItem("sessionCheckChannelName",n)),n},n}(A),ie=/*#__PURE__*/c("actionDefinitions"),re=/*#__PURE__*/c("createActionsProxy"),oe=/*#__PURE__*/function(){var e=t.prototype;function t(e,t){var n=e.name,i=e.payload,r=e.error,o=e.status,s=e.actions,a=e.csrf_token;Object.defineProperty(this,re,{value:se}),this.name=void 0,this.payload=void 0,this.error=void 0,this.status=void 0,this.csrf_token=void 0,Object.defineProperty(this,ie,{writable:!0,value:void 0}),this.actions=void 0,this.fetchNextState=void 0,this.name=n,this.payload=i,this.error=r,this.status=o,this.csrf_token=a,u(this,ie)[ie]=s,this.actions=u(this,re)[re](s,a),this.fetchNextState=t}return e.toJSON=function(){return{name:this.name,payload:this.payload,error:this.error,status:this.status,csrf_token:this.csrf_token,actions:u(this,ie)[ie]}},e.runAction=function(e,t){var n={};if("inputs"in e&&"object"==typeof e.inputs&&null!==e.inputs){var i=e.inputs;for(var r in e.inputs){var o=i[r];o&&"value"in o&&(n[r]=o.value)}}return this.fetchNextState(e.href,{input_data:n,csrf_token:t})},e.validateAction=function(e){if("inputs"in e){var t=function(t){var n=e.inputs[t];function i(e,n,i,r){throw new ae({reason:e,inputName:t,wanted:i,actual:r,message:n})}var r=n.value;n.required&&!r&&i(R.Required,"is required"),(null!=n.min_length||null!=n.max_length)&&("length"in r||i(R.InvalidInputDefinition,'has min/max length requirement, but is missing "length" property',"string",typeof r),null!=n.min_length&&r<n.min_length&&i(R.MinLength,"too short (min "+n.min_length+")",n.min_length,r.length),null!=n.max_length&&r>n.max_length&&i(R.MaxLength,"too long (max "+n.max_length+")",n.max_length,r.length))};for(var n in e.inputs)t(n)}},t}();function se(e,t){var n=this,i=function(e){return n.validateAction(e)};return new Proxy(e,{get:function(e,r){if("symbol"==typeof r)return e[r];var o=e[r];return null==o?null:function(e){var r=Object.assign(JSON.parse(JSON.stringify(o)),{validate:function(){return i(r),r},tryValidate:function(){try{i(r)}catch(e){if(e instanceof ae)return e;throw e}},run:function(){return function(e){return n.runAction(e,t)}(r)}});if(null!==r&&"object"==typeof r&&"inputs"in r)for(var s in e){var a=r.inputs;a[s]||(a[s]={name:s,type:""}),a[s].value=e[s]}return r}}})}!function(e){e[e.InvalidInputDefinition=0]="InvalidInputDefinition",e[e.MinLength=1]="MinLength",e[e.MaxLength=2]="MaxLength",e[e.Required=3]="Required"}(R||(R={}));var ae=/*#__PURE__*/function(e){function n(t){var n;return(n=e.call(this,'"'+t.inputName+'" '+t.message)||this).reason=void 0,n.inputName=void 0,n.wanted=void 0,n.actual=void 0,n.name="ValidationError",n.reason=t.reason,n.inputName=t.inputName,n.wanted=t.wanted,n.actual=t.actual,n}return t(n,e),n}(/*#__PURE__*/o(Error));function ce(e){return"object"==typeof e&&null!==e&&"status"in e&&"error"in e&&"name"in e&&Boolean(e.name)&&Boolean(e.status)}function ue(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var he=/*#__PURE__*/function(e){function n(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];return(t=e.call.apply(e,[this].concat(i))||this).run=function(e,n){try{return Promise.resolve(ue(function(){if(!ce(e))throw new de(e);var i=n[e.name];if(!i)throw new le(e);return Promise.resolve(i(e)).then(function(e){function i(){if(ce(e))return t.run(e,n)}var r=function(){if("object"==typeof(t=e)&&null!==t&&"href"in t&&"inputs"in t)return Promise.resolve(e.run()).then(function(t){e=t});var t}();return r&&r.then?r.then(i):i()})},function(e){if("function"==typeof n.onError)return n.onError(e)}))}catch(e){return Promise.reject(e)}},t}t(n,e);var i=n.prototype;return i.init=function(e,t){var n=this;return Promise.resolve(function e(i,r){try{return Promise.resolve(ue(function(){return Promise.resolve(n.client.post(i,r)).then(function(t){return new oe(t.json(),e)})},function(e){null==t.onError||t.onError(e)}))}catch(e){return Promise.reject(e)}}(e)).then(function(e){return Promise.resolve(n.run(e,t)).then(function(){})})},i.fromString=function(e,t){try{var n=this,i=new oe(JSON.parse(e),function e(i,r){try{return Promise.resolve(ue(function(){return Promise.resolve(n.client.post(i,r)).then(function(t){return new oe(t.json(),e)})},function(e){null==t.onError||t.onError(e)}))}catch(e){return Promise.reject(e)}});return Promise.resolve(n.run(i,t)).then(function(){})}catch(e){return Promise.reject(e)}},n}(K),le=/*#__PURE__*/function(e){function n(t){var i;return(i=e.call(this,"No handler found for state: "+("string"==typeof t.name?'"'+t.name+'"':"("+typeof t.name+")"),"handlerNotFoundError")||this).state=void 0,i.state=t,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(h),de=/*#__PURE__*/function(e){function n(t){var n;return(n=e.call(this,"Invalid state: "+("string"==typeof t.name?'"'+t.name+'"':"("+typeof t.name+")"))||this).state=void 0,n.state=t,n}return t(n,e),n}(/*#__PURE__*/o(Error)),pe=/*#__PURE__*/function(e){function n(t,n){var i;(i=e.call(this)||this).api=void 0,i.user=void 0,i.email=void 0,i.thirdParty=void 0,i.enterprise=void 0,i.token=void 0,i.sessionClient=void 0,i.session=void 0,i.relay=void 0,i.flow=void 0;var r={timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check",sessionTokenLocation:"cookie"};return void 0!==(null==n?void 0:n.cookieName)&&(r.cookieName=n.cookieName),void 0!==(null==n?void 0:n.timeout)&&(r.timeout=n.timeout),void 0!==(null==n?void 0:n.localStorageKey)&&(r.localStorageKey=n.localStorageKey),void 0!==(null==n?void 0:n.cookieDomain)&&(r.cookieDomain=n.cookieDomain),void 0!==(null==n?void 0:n.cookieSameSite)&&(r.cookieSameSite=n.cookieSameSite),void 0!==(null==n?void 0:n.lang)&&(r.lang=n.lang),void 0!==(null==n?void 0:n.sessionCheckInterval)&&(r.sessionCheckInterval=n.sessionCheckInterval<3e3?3e3:n.sessionCheckInterval),void 0!==(null==n?void 0:n.sessionCheckChannelName)&&(r.sessionCheckChannelName=n.sessionCheckChannelName),void 0!==(null==n?void 0:n.sessionTokenLocation)&&(r.sessionTokenLocation=n.sessionTokenLocation),i.api=t,i.user=new J(t,r),i.email=new B(t,r),i.thirdParty=new z(t,r),i.enterprise=new F(t,r),i.token=new V(t,r),i.sessionClient=new Q(t,r),i.session=new Y(t,r),i.relay=new ne(t,r),i.flow=new he(t,r),i}return t(n,e),n.prototype.setLang=function(e){this.flow.client.lang=e},n}(G),fe=/*#__PURE__*/function(){function e(){}return e.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},e.isPlatformAuthenticatorAvailable=function(){try{return this.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e.isSecurityKeySupported=function(){try{return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()):Promise.resolve(this.supported())}catch(e){return Promise.reject(e)}},e.isConditionalMediationAvailable=function(){try{return window.PublicKeyCredential&&window.PublicKeyCredential.isConditionalMediationAvailable?Promise.resolve(window.PublicKeyCredential.isConditionalMediationAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e}();exports.ConflictError=d,exports.CustomEventWithDetail=T,exports.EmailAddressAlreadyExistsError=P,exports.EmailClient=B,exports.EnterpriseClient=F,exports.ForbiddenError=x,exports.Hanko=pe,exports.HankoError=h,exports.InvalidPasscodeError=m,exports.InvalidPasswordError=v,exports.InvalidWebauthnCredentialError=y,exports.MaxNumOfEmailAddressesReachedError=C,exports.MaxNumOfPasscodeAttemptsReachedError=g,exports.NotFoundError=k,exports.PasscodeExpiredError=w,exports.RequestTimeoutError=p,exports.SessionClient=Q,exports.TechnicalError=l,exports.ThirdPartyClient=z,exports.ThirdPartyError=O,exports.TokenClient=V,exports.TooManyRequestsError=E,exports.UnauthorizedError=S,exports.UserClient=J,exports.UserVerificationError=b,exports.WebauthnRequestCancelledError=f,exports.WebauthnSupport=fe,exports.sessionCreatedType=j,exports.sessionExpiredType=_,exports.userDeletedType=L,exports.userLoggedOutType=I;
|
|
1
|
+
function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},e.apply(this,arguments)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,r(e,t)}function n(e){return n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},n(e)}function r(e,t){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},r(e,t)}function i(e,t,n){return i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}()?Reflect.construct.bind():function(e,t,n){var i=[null];i.push.apply(i,t);var o=new(Function.bind.apply(e,i));return n&&r(o,n.prototype),o},i.apply(null,arguments)}function o(e){var t="function"==typeof Map?new Map:void 0;return o=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,o)}function o(){return i(e,arguments,n(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),r(o,e)},o(e)}function s(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var a=/*#__PURE__*/function(){function e(){}return e.throttle=function(e,t,n){void 0===n&&(n={});var r,i,o,s=n.leading,a=void 0===s||s,c=n.trailing,u=void 0===c||c,h=0,l=function(){h=!1===a?0:Date.now(),o=null,e.apply(r,i)};return function(){var n=Date.now();h||!1!==a||(h=n);var s=t-(n-h);r=this,i=[].slice.call(arguments),s<=0||s>t?(o&&(window.clearTimeout(o),o=null),h=n,e.apply(r,i)):o||!1===u||(o=window.setTimeout(l,s))}},e}(),c="hanko-session-created",u="hanko-session-expired",h="hanko-user-logged-out",l="hanko-user-deleted",d="hanko-after-state-change",f="hanko-before-state-change",p=/*#__PURE__*/function(e){function n(t,n){return e.call(this,t,{detail:n})||this}return t(n,e),n}(/*#__PURE__*/o(CustomEvent)),v=/*#__PURE__*/function(){function e(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=a.throttle}var t=e.prototype;return t.wrapCallback=function(e,t){var n=function(t){e(t.detail)};return t?this._throttle(n,this.throttleLimit,{leading:!0,trailing:!1}):n},t.addEventListenerWithType=function(e){var t=this,n=e.type,r=e.once,i=void 0!==r&&r,o=e.throttle,s=this.wrapCallback(e.callback,void 0!==o&&o);return this._addEventListener(n,s,{once:i}),function(){return t._removeEventListener(n,s)}},e.mapAddEventListenerParams=function(e,t,n){return{type:e,callback:t.callback,once:t.once,throttle:n}},t.addEventListener=function(t,n,r){return this.addEventListenerWithType(e.mapAddEventListenerParams(t,n,r))},t.onSessionCreated=function(e,t){return this.addEventListener(c,{callback:e,once:t},!0)},t.onSessionExpired=function(e,t){return this.addEventListener(u,{callback:e,once:t},!0)},t.onUserLoggedOut=function(e,t){return this.addEventListener(h,{callback:e,once:t})},t.onUserDeleted=function(e,t){return this.addEventListener(l,{callback:e,once:t})},t.onAfterStateChange=function(e,t){return this.addEventListener(d,{callback:e,once:t},!1)},t.onBeforeStateChange=function(e,t){return this.addEventListener(f,{callback:e,once:t},!1)},e}(),m=/*#__PURE__*/function(){function e(){this._dispatchEvent=document.dispatchEvent.bind(document)}var t=e.prototype;return t.dispatch=function(e,t){this._dispatchEvent(new p(e,t))},t.dispatchSessionCreatedEvent=function(e){this.dispatch(c,e)},t.dispatchSessionExpiredEvent=function(){this.dispatch(u,null)},t.dispatchUserLoggedOutEvent=function(){this.dispatch(h,null)},t.dispatchUserDeletedEvent=function(){this.dispatch(l,null)},t.dispatchAfterStateChangeEvent=function(e){this.dispatch(d,e)},t.dispatchBeforeStateChangeEvent=function(e){this.dispatch(f,e)},e}(),y=/*#__PURE__*/function(e){function n(t,r,i){var o;return(o=e.call(this,t)||this).code=void 0,o.cause=void 0,o.code=r,o.cause=i,Object.setPrototypeOf(s(o),n.prototype),o}return t(n,e),n}(/*#__PURE__*/o(Error)),g=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),S=/*#__PURE__*/function(e){function n(t,r){var i;return i=e.call(this,"Conflict error","conflict",r)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(y),k=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),b=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),w=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),C=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),P=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),x=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),E=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),A=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),_=/*#__PURE__*/function(e){function n(t,r){var i;return(i=e.call(this,"Too many requests error","tooManyRequests",r)||this).retryAfter=void 0,i.retryAfter=t,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(y),O=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),I=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Forbidden error","forbidden",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),j=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),L=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),T=/*#__PURE__*/function(e){function n(t){var r;return r=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",t)||this,Object.setPrototypeOf(s(r),n.prototype),r}return t(n,e),n}(y),N=/*#__PURE__*/function(e){function n(t,r){var i;return i=e.call(this,"An error occurred during third party sign up/sign in",t,r)||this,Object.setPrototypeOf(s(i),n.prototype),i}return t(n,e),n}(y);function R(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}var D=function e(t,n){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=R({},n,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in i)i[s]&&(o+="; "+s,!0!==i[s]&&(o+="="+i[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+o}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},i=0;i<n.length;i++){var o=n[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(r[a]=t.read(s,a),e===a)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",R({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,R({},this.attributes,t))},withConverter:function(t){return e(R({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),K=/*#__PURE__*/function(){function t(e){var t,n;this.authCookieName=void 0,this.authCookieDomain=void 0,this.authCookieSameSite=void 0,this.authCookieName=null!=(t=e.cookieName)?t:"hanko",this.authCookieDomain=e.cookieDomain,this.authCookieSameSite=null!=(n=e.cookieSameSite)?n:"lax"}var n=t.prototype;return n.getAuthCookie=function(){return D.get(this.authCookieName)},n.setAuthCookie=function(t,n){var r={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(r.domain=this.authCookieDomain);var i=e({},r,n);if(("none"===i.sameSite||"None"===i.sameSite)&&!1===i.secure)throw new g(new Error("Secure attribute must be set when SameSite=None"));D.set(this.authCookieName,t,i)},n.removeAuthCookie=function(){D.remove(this.authCookieName)},t}(),q=/*#__PURE__*/function(){function e(e){this.keyName=void 0,this.keyName=e.keyName}var t=e.prototype;return t.getSessionToken=function(){return sessionStorage.getItem(this.keyName)},t.setSessionToken=function(e){sessionStorage.setItem(this.keyName,e)},t.removeSessionToken=function(){sessionStorage.removeItem(this.keyName)},e}(),U=/*#__PURE__*/function(){function e(e){this._xhr=void 0,this._xhr=e}return e.prototype.getResponseHeader=function(e){return this._xhr.getResponseHeader(e)},e}(),F=/*#__PURE__*/function(){function e(e){this.headers=void 0,this.ok=void 0,this.status=void 0,this.statusText=void 0,this.url=void 0,this._decodedJSON=void 0,this.xhr=void 0,this.headers=new U(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}var t=e.prototype;return t.json=function(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON},t.parseNumericHeader=function(e){var t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t},e}(),M=/*#__PURE__*/function(){function t(t,n){var r;this.timeout=void 0,this.api=void 0,this.dispatcher=void 0,this.cookie=void 0,this.sessionTokenStorage=void 0,this.lang=void 0,this.sessionTokenLocation=void 0,this.api=t,this.timeout=null!=(r=n.timeout)?r:13e3,this.dispatcher=new m,this.cookie=new K(e({},n)),this.sessionTokenStorage=new q({keyName:n.cookieName}),this.lang=n.lang,this.sessionTokenLocation=n.sessionTokenLocation}var n=t.prototype;return n._fetch=function(e,t,n){void 0===n&&(n=new XMLHttpRequest);var r=this,i=this.api+e,o=this.timeout,s=this.getAuthToken(),a=this.lang;return new Promise(function(e,c){n.open(t.method,i,!0),n.setRequestHeader("Accept","application/json"),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("X-Language",a),s&&n.setRequestHeader("Authorization","Bearer "+s),n.timeout=o,n.withCredentials=!0,n.onload=function(){r.processHeaders(n),e(new F(n))},n.onerror=function(){c(new g)},n.ontimeout=function(){c(new k)},n.send(t.body?t.body.toString():null)})},n.processHeaders=function(e){var t="",n=0,r="";if(e.getAllResponseHeaders().split("\r\n").forEach(function(i){var o=i.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?n=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(r=e.getResponseHeader("X-Session-Retention"))}),t){var i=new RegExp("^https://"),o=!!this.api.match(i)&&!!window.location.href.match(i),s="session"===r?void 0:new Date((new Date).getTime()+1e3*n);this.setAuthToken(t,{secure:o,expires:s})}},n.get=function(e){return this._fetch(e,{method:"GET"})},n.post=function(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})},n.put=function(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})},n.patch=function(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})},n.delete=function(e){return this._fetch(e,{method:"DELETE"})},n.getAuthToken=function(){var e="";switch(this.sessionTokenLocation){case"cookie":default:e=this.cookie.getAuthCookie();break;case"sessionStorage":e=this.sessionTokenStorage.getSessionToken()}return e},n.setAuthToken=function(e,t){switch(this.sessionTokenLocation){case"cookie":default:return this.cookie.setAuthCookie(e,t);case"sessionStorage":return this.sessionTokenStorage.setSessionToken(e)}},t}(),H=function(e,t){this.client=void 0,this.client=new M(e,t)},W=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}return t(n,e),n.prototype.validate=function(){try{return Promise.resolve(this.client.get("/sessions/validate")).then(function(e){if(!e.ok)throw new g;return Promise.resolve(e.json())})}catch(e){return Promise.reject(e)}},n}(H),z=/*#__PURE__*/function(){function e(e){this.storageKey=void 0,this.defaultState={expiration:0,lastCheck:0},this.storageKey=e}var t=e.prototype;return t.load=function(){var e=window.localStorage.getItem(this.storageKey);return null==e?this.defaultState:JSON.parse(e)},t.save=function(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e||this.defaultState))},e}(),B=function(e,t){var n=this;this.onActivityCallback=void 0,this.onInactivityCallback=void 0,this.handleFocus=function(){n.onActivityCallback()},this.handleBlur=function(){n.onInactivityCallback()},this.handleVisibilityChange=function(){"visible"===document.visibilityState?n.onActivityCallback():n.onInactivityCallback()},this.hasFocus=function(){return document.hasFocus()},this.onActivityCallback=e,this.onInactivityCallback=t,window.addEventListener("focus",this.handleFocus),window.addEventListener("blur",this.handleBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange)},J=/*#__PURE__*/function(){function e(e,t,n){this.intervalID=null,this.timeoutID=null,this.checkInterval=void 0,this.checkSession=void 0,this.onSessionExpired=void 0,this.checkInterval=e,this.checkSession=t,this.onSessionExpired=n}var t=e.prototype;return t.scheduleSessionExpiry=function(e){var t=this;this.stop(),this.timeoutID=setTimeout(function(){try{return t.stop(),t.onSessionExpired(),Promise.resolve()}catch(e){return Promise.reject(e)}},e)},t.start=function(e,t){var n=this;void 0===e&&(e=0),void 0===t&&(t=0);var r=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(r):this.timeoutID=setTimeout(function(){try{return Promise.resolve(n.checkSession()).then(function(e){if(e.is_valid){if(n.sessionExpiresSoon(e.expiration))return void n.scheduleSessionExpiry(e.expiration-Date.now());n.intervalID=setInterval(function(){try{return Promise.resolve(n.checkSession()).then(function(t){(e=t).is_valid?n.sessionExpiresSoon(e.expiration)&&n.scheduleSessionExpiry(e.expiration-Date.now()):n.stop()})}catch(e){return Promise.reject(e)}},n.checkInterval)}else n.stop()})}catch(e){return Promise.reject(e)}},r)},t.stop=function(){this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null),this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)},t.isRunning=function(){return null!==this.timeoutID||null!==this.intervalID},t.sessionExpiresSoon=function(e){return e>0&&e-Date.now()<=this.checkInterval},t.calcTimeToNextCheck=function(e){var t=Date.now()-e;return this.checkInterval>=t?this.checkInterval-t%this.checkInterval:0},e}(),V=/*#__PURE__*/function(){function e(e,t,n,r){var i=this;void 0===e&&(e="hanko_session"),this.channel=void 0,this.onSessionExpired=void 0,this.onSessionCreated=void 0,this.onLeadershipRequested=void 0,this.handleMessage=function(e){var t=e.data;switch(t.action){case"sessionExpired":i.onSessionExpired(t);break;case"sessionCreated":i.onSessionCreated(t);break;case"requestLeadership":i.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=n,this.onLeadershipRequested=r,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}return e.prototype.post=function(e){this.channel.postMessage(e)},e}(),X=/*#__PURE__*/function(e){function n(t,n){var r;(r=e.call(this)||this).listener=new v,r.checkInterval=3e4,r.client=void 0,r.sessionState=void 0,r.windowActivityManager=void 0,r.scheduler=void 0,r.sessionChannel=void 0,r.isLoggedIn=void 0,r.client=new W(t,n),n.sessionCheckInterval&&(r.checkInterval=n.sessionCheckInterval<3e3?3e3:n.sessionCheckInterval),r.sessionState=new z(n.cookieName+"_session_state"),r.sessionChannel=new V(r.getSessionCheckChannelName(n.sessionTokenLocation,n.sessionCheckChannelName),function(){return r.onChannelSessionExpired()},function(e){return r.onChannelSessionCreated(e)},function(){return r.onChannelLeadershipRequested()}),r.scheduler=new J(r.checkInterval,function(){return r.checkSession()},function(){return r.onSessionExpired()}),r.windowActivityManager=new B(function(){return r.startSessionCheck()},function(){return r.scheduler.stop()});var i=Date.now(),o=r.sessionState.load();return r.isLoggedIn=i<o.expiration,r.initializeEventListeners(),r.startSessionCheck(),r}t(n,e);var r=n.prototype;return r.initializeEventListeners=function(){var e=this;this.listener.onSessionCreated(function(t){var n=t.claims,r=Date.parse(n.expiration),i=Date.now();e.isLoggedIn=!0,e.sessionState.save({expiration:r,lastCheck:i}),e.sessionChannel.post({action:"sessionCreated",claims:n}),e.startSessionCheck()}),this.listener.onUserLoggedOut(function(){e.isLoggedIn=!1,e.sessionChannel.post({action:"sessionExpired"}),e.sessionState.save(null),e.scheduler.stop()}),window.addEventListener("beforeunload",function(){return e.scheduler.stop()})},r.startSessionCheck=function(){if(this.windowActivityManager.hasFocus()&&(this.sessionChannel.post({action:"requestLeadership"}),!this.scheduler.isRunning())){var e=this.sessionState.load();this.isLoggedIn&&this.scheduler.start(e.lastCheck,e.expiration)}},r.checkSession=function(){try{var e=this,t=Date.now();return Promise.resolve(e.client.validate()).then(function(n){var r=n.is_valid,i=n.claims,o=n.expiration_time,s=o?Date.parse(o):0;return!r&&e.isLoggedIn&&e.dispatchSessionExpiredEvent(),r?(e.isLoggedIn=!0,e.sessionState.save({lastCheck:t,expiration:s})):(e.isLoggedIn=!1,e.sessionState.save(null),e.sessionChannel.post({action:"sessionExpired"})),{is_valid:r,claims:i,expiration:s}})}catch(e){return Promise.reject(e)}},r.onSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())},r.onChannelSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())},r.onChannelSessionCreated=function(e){var t=e.claims,n=Date.now(),r=Date.parse(t.expiration)-n;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:r})},r.onChannelLeadershipRequested=function(){this.windowActivityManager.hasFocus()||this.scheduler.stop()},r.getSessionCheckChannelName=function(e,t){if("cookie"==e)return t;var n=sessionStorage.getItem("sessionCheckChannelName");return null!=n&&""!==n||(n=t+"-"+(Math.floor(100*Math.random())+1),sessionStorage.setItem("sessionCheckChannelName",n)),n},n}(m),G=/*#__PURE__*/function(){function e(){}return e.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},e.isPlatformAuthenticatorAvailable=function(){try{return this.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e.isSecurityKeySupported=function(){try{return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()):Promise.resolve(this.supported())}catch(e){return Promise.reject(e)}},e.isConditionalMediationAvailable=function(){try{return window.PublicKeyCredential&&window.PublicKeyCredential.isConditionalMediationAvailable?Promise.resolve(window.PublicKeyCredential.isConditionalMediationAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e}();function $(e){const t="==".slice(0,(4-e.length%4)%4),n=e.replace(/-/g,"+").replace(/_/g,"/")+t,r=atob(n),i=new ArrayBuffer(r.length),o=new Uint8Array(i);for(let e=0;e<r.length;e++)o[e]=r.charCodeAt(e);return i}function Q(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,"")}var Y="copy",Z="convert";function ee(e,t,n){if(t===Y)return n;if(t===Z)return e(n);if(t instanceof Array)return n.map(n=>ee(e,t[0],n));if(t instanceof Object){const r={};for(const[i,o]of Object.entries(t)){if(o.derive){const e=o.derive(n);void 0!==e&&(n[i]=e)}if(i in n)r[i]=null!=n[i]?ee(e,o.schema,n[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return r}}function te(e,t){return{required:!0,schema:e,derive:t}}function ne(e){return{required:!0,schema:e}}function re(e){return{required:!1,schema:e}}var ie={type:ne(Y),id:ne(Z),transports:re(Y)},oe={appid:re(Y),appidExclude:re(Y),credProps:re(Y)},se={appid:re(Y),appidExclude:re(Y),credProps:re(Y)},ae={publicKey:ne({rp:ne(Y),user:ne({id:ne(Z),name:ne(Y),displayName:ne(Y)}),challenge:ne(Z),pubKeyCredParams:ne(Y),timeout:re(Y),excludeCredentials:re([ie]),authenticatorSelection:re(Y),attestation:re(Y),extensions:re(oe)}),signal:re(Y)},ce={type:ne(Y),id:ne(Y),rawId:ne(Z),authenticatorAttachment:re(Y),response:ne({clientDataJSON:ne(Z),attestationObject:ne(Z),transports:te(Y,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:te(se,e=>e.getClientExtensionResults())},ue={mediation:re(Y),publicKey:ne({challenge:ne(Z),timeout:re(Y),rpId:re(Y),allowCredentials:re([ie]),userVerification:re(Y),extensions:re(oe)}),signal:re(Y)},he={type:ne(Y),id:ne(Y),rawId:ne(Z),authenticatorAttachment:re(Y),response:ne({clientDataJSON:ne(Z),authenticatorData:ne(Z),signature:ne(Z),userHandle:ne(Z)}),clientExtensionResults:te(se,e=>e.getClientExtensionResults())};async function le(e){const t=await navigator.credentials.get(function(e){return ee($,ue,e)}(e));return function(e){return ee(Q,he,e)}(t)}var de=/*#__PURE__*/function(){function t(){this.abortController=new AbortController}t.getInstance=function(){return t.instance||(t.instance=new t),t.instance};var n=t.prototype;return n.createAbortSignal=function(){return this.abortController.abort(),this.abortController=new AbortController,this.abortController.signal},n.getWebauthnCredential=function(t){try{return Promise.resolve(le(e({},t,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},n.getConditionalWebauthnCredential=function(e){try{return Promise.resolve(le({publicKey:e,mediation:"conditional",signal:this.createAbortSignal()}))}catch(e){return Promise.reject(e)}},n.createWebauthnCredential=function(t){try{return Promise.resolve(async function(e){return t=await navigator.credentials.create(function(e){return ee($,ae,e)}(e)),ee(Q,ce,t);var t}(e({},t,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},t}();function fe(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}de.instance=null;var pe=function(e,t,n,r,i){void 0===r&&(r="webauthn_credential_already_exists"),void 0===i&&(i="Webauthn credential already exists");try{return Promise.resolve(fe(function(){return Promise.resolve(t.createWebauthnCredential(n)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_attestation_response.run({public_key:t}))})},function(){return Promise.resolve(e.actions.back.run()).then(function(e){return e.error={code:r,message:i},e})}))}catch(e){return Promise.reject(e)}},ve={preflight:function(e){try{var t=e.actions.register_client_capabilities,n=t.run,r=G.supported();return Promise.resolve(G.isConditionalMediationAvailable()).then(function(e){return Promise.resolve(G.isPlatformAuthenticatorAvailable()).then(function(i){return Promise.resolve(n.call(t,{webauthn_available:r,webauthn_conditional_mediation_available:e,webauthn_platform_authenticator_available:i}))})})}catch(e){return Promise.reject(e)}},login_passkey:function(e){try{var t=de.getInstance();return Promise.resolve(fe(function(){return Promise.resolve(t.getWebauthnCredential(e.payload.request_options)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_assertion_response.run({assertion_response:t}))})},function(){return Promise.resolve(e.actions.back.run()).then(function(t){return e.error&&(t.error=e.error),t})}))}catch(e){return Promise.reject(e)}},onboarding_verify_passkey_attestation:function(e){try{var t=de.getInstance();return Promise.resolve(pe(e,t,e.payload.creation_options))}catch(e){return Promise.reject(e)}},webauthn_credential_verification:function(e){try{var t=de.getInstance();return Promise.resolve(pe(e,t,e.payload.creation_options))}catch(e){return Promise.reject(e)}},thirdparty:function(e){try{var t,n=function(n){var i;if(t)return n;function a(t){var n;if(i)return t;var r=function(){if(e.isCached)return Promise.resolve(e.actions.back.run()).then(function(e){return n=1,e});e.saveToLocalStorage(),window.location.assign(e.payload.redirect_url)}();return r&&r.then?r.then(function(t){return n?t:e}):n?r:e}var c=function(){if((null==o?void 0:o.length)>0){var t="access_denied"===o?"third_party_access_denied":"technical_error",n=r.get("error_description");return s(["error","error_description"]),Promise.resolve(e.actions.back.run(null,{dispatchAfterStateChangeEvent:!1})).then(function(e){return e.error={code:t,message:n},e.dispatchAfterStateChangeEvent(),i=1,e})}}();return c&&c.then?c.then(a):a(c)},r=new URLSearchParams(window.location.search),i=r.get("hanko_token"),o=r.get("error"),s=function(e){e.forEach(function(e){return r.delete(e)});var t=r.toString()?"?"+r.toString():"";history.replaceState(null,null,""+window.location.pathname+t)},a=function(){if((null==i?void 0:i.length)>0)return s(["hanko_token"]),Promise.resolve(e.actions.exchange_token.run({token:i})).then(function(e){return t=1,e})}();return Promise.resolve(a&&a.then?a.then(n):n(a))}catch(e){return Promise.reject(e)}},success:function(e){try{var t=e.payload.claims,n=Date.parse(t.expiration)-Date.now();return e.removeFromLocalStorage(),e.hanko.relay.dispatchSessionCreatedEvent({claims:t,expirationSeconds:n}),Promise.resolve(e)}catch(e){return Promise.reject(e)}},account_deleted:function(e){try{return e.removeFromLocalStorage(),e.hanko.relay.dispatchUserDeletedEvent(),Promise.resolve(e)}catch(e){return Promise.reject(e)}}},me={login_init:function(e){try{return Promise.resolve(void function(){try{var t=de.getInstance();Promise.resolve(function(){if(e.payload.request_options)return function(n,r){try{var i=Promise.resolve(t.getConditionalWebauthnCredential(e.payload.request_options.publicKey)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_assertion_response.run({assertion_response:t}))})}catch(e){return}return i&&i.then?i.then(void 0,function(){}):i}()}())}catch(e){return Promise.reject(e)}}())}catch(e){return Promise.reject(e)}}};function ye(e,t,n){if(!e.s){if(n instanceof ge){if(!n.s)return void(n.o=ye.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(ye.bind(null,e,t),ye.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}var ge=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var r=new e,i=this.s;if(i){var o=1&i?t:n;if(o){try{ye(r,1,o(this.v))}catch(e){ye(r,2,e)}return r}return this}return this.o=function(e){try{var i=e.v;1&e.s?ye(r,1,t?t(i):i):n?ye(r,1,n(i)):ye(r,2,i)}catch(e){ye(r,2,e)}},r},e}();function Se(e){return e instanceof ge&&1&e.s}var ke=/*#__PURE__*/function(){function t(e,t,n,r){var i=this;if(void 0===r&&(r={}),this.name=void 0,this.flowName=void 0,this.error=void 0,this.payload=void 0,this.actions=void 0,this.csrfToken=void 0,this.status=void 0,this.previousAction=void 0,this.isCached=void 0,this.cacheKey=void 0,this.hanko=void 0,this.invokedAction=void 0,this.excludeAutoSteps=void 0,this.autoStep=void 0,this.passkeyAutofillActivation=void 0,this.flowName=t,this.name=n.name,this.error=n.error,this.payload=n.payload,this.csrfToken=n.csrf_token,this.status=n.status,this.hanko=e,this.actions=this.buildActionMap(n.actions),this.name in ve){var o=ve[this.name];this.autoStep=function(){return o(i)}}if(this.name in me){var s=me[this.name];this.passkeyAutofillActivation=function(){return s(i)}}var a=r.dispatchAfterStateChangeEvent,c=void 0===a||a,u=r.excludeAutoSteps,h=r.previousAction,l=void 0===h?null:h,d=r.isCached,f=void 0!==d&&d,p=r.cacheKey,v=void 0===p?"hanko-flow-state":p;this.excludeAutoSteps=void 0===u?null:u,this.previousAction=l,this.isCached=f,this.cacheKey=v,c&&this.dispatchAfterStateChangeEvent()}var n=t.prototype;return n.buildActionMap=function(e){var t=this,n={};return Object.keys(e).forEach(function(r){n[r]=new be(e[r],t)}),new Proxy(n,{get:function(e,n){if(n in e)return e[n];var r="string"==typeof n?n:n.toString();return be.createDisabled(r,t)}})},n.dispatchAfterStateChangeEvent=function(){this.hanko.relay.dispatchAfterStateChangeEvent({state:this})},n.serialize=function(){return{flow_name:this.flowName,name:this.name,error:this.error,payload:this.payload,csrf_token:this.csrfToken,status:this.status,previous_action:this.previousAction,actions:Object.fromEntries(Object.entries(this.actions).map(function(e){var t=e[1];return[e[0],{action:t.name,href:t.href,inputs:t.inputs,description:null}]}))}},n.saveToLocalStorage=function(){localStorage.setItem(this.cacheKey,JSON.stringify(e({},this.serialize(),{is_cached:!0})))},n.removeFromLocalStorage=function(){localStorage.removeItem(this.cacheKey)},t.initializeFlowState=function(e,n,r,i){void 0===i&&(i={});try{var o,s=new t(e,n,r,i),a=function(){if("all"!=s.excludeAutoSteps)return function(e,t,n){for(var r;;){var i=e();if(Se(i)&&(i=i.v),!i)return o;if(i.then){r=0;break}var o=n();if(o&&o.then){if(!Se(o)){r=1;break}o=o.s}if(t){var s=t();if(s&&s.then&&!Se(s)){r=2;break}}}var a=new ge,c=ye.bind(null,a,2);return(0===r?i.then(h):1===r?o.then(u):s.then(l)).then(void 0,c),a;function u(r){o=r;do{if(t&&(s=t())&&s.then&&!Se(s))return void s.then(l).then(void 0,c);if(!(i=e())||Se(i)&&!i.v)return void ye(a,1,o);if(i.then)return void i.then(h).then(void 0,c);Se(o=n())&&(o=o.v)}while(!o||!o.then);o.then(u).then(void 0,c)}function h(e){e?(o=n())&&o.then?o.then(u).then(void 0,c):u(o):ye(a,1,o)}function l(){(i=e())?i.then?i.then(h).then(void 0,c):h(i):ye(a,1,o)}}(function(){var e;return!(o||!s||!s.autoStep||null!=(e=s.excludeAutoSteps)&&e.includes(s.name))},void 0,function(){return Promise.resolve(s.autoStep()).then(function(e){if(e.name==s.name)return o=1,e;s=e})})}();return Promise.resolve(a&&a.then?a.then(function(e){return o?e:s}):o?a:s)}catch(e){return Promise.reject(e)}},t.readFromLocalStorage=function(e){var t=localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}},t.create=function(n,r,i){void 0===i&&(i={});try{var o=i.cacheKey,s=void 0===o?"hanko-flow-state":o,a=i.loadFromCache;if(void 0===a||a){var c=t.readFromLocalStorage(s);if(c)return Promise.resolve(t.deserialize(n,c,e({},i,{cacheKey:s})))}return Promise.resolve(t.fetchState(n,"/"+r)).then(function(o){return t.initializeFlowState(n,r,o,e({},i,{cacheKey:s}))})}catch(e){return Promise.reject(e)}},t.deserialize=function(n,r,i){void 0===i&&(i={});try{return Promise.resolve(t.initializeFlowState(n,r.flow_name,r,e({},i,{previousAction:r.previous_action,isCached:r.is_cached})))}catch(e){return Promise.reject(e)}},t.fetchState=function(e,n,r){try{return Promise.resolve(function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(function(){return Promise.resolve(e.client.post(n,r)).then(function(e){return e.json()})},function(e){return t.createErrorResponse(e)}))}catch(e){return Promise.reject(e)}},t.createErrorResponse=function(e){return{actions:null,csrf_token:"",name:"error",payload:null,status:0,error:e}},t}(),be=/*#__PURE__*/function(){function t(e,t,n){void 0===n&&(n=!0),this.enabled=void 0,this.href=void 0,this.name=void 0,this.inputs=void 0,this.parentState=void 0,this.enabled=n,this.href=e.href,this.name=e.action,this.inputs=e.inputs,this.parentState=t}return t.createDisabled=function(e,n){return new t({action:e,href:"",inputs:{},description:"Disabled action"},n,!1)},t.prototype.run=function(t,n){void 0===t&&(t=null),void 0===n&&(n={});try{var r=this,i=r.parentState,o=i.name,s=i.hanko,a=i.flowName,c=i.csrfToken,u=i.invokedAction,h=i.excludeAutoSteps,l=i.cacheKey,d=n.dispatchAfterStateChangeEvent,f=void 0===d||d;if(!r.enabled)throw new Error("Action '"+r.name+"' is not enabled in state '"+o+"'");if(u)throw new Error("An action '"+u.name+"' has already been invoked on state '"+u.relatedStateName+"'. No further actions can be run.");r.parentState.invokedAction={name:r.name,relatedStateName:o},s.relay.dispatchBeforeStateChangeEvent({state:r.parentState});var p=e({},Object.keys(r.inputs).reduce(function(e,t){var n=r.inputs[t];return void 0!==n.value&&(e[t]=n.value),e},{}),t);return Promise.resolve(ke.fetchState(s,r.href,{input_data:p,csrf_token:c})).then(function(e){return r.parentState.removeFromLocalStorage(),ke.initializeFlowState(s,a,e,{dispatchAfterStateChangeEvent:f,excludeAutoSteps:h,previousAction:u,cacheKey:l})})}catch(e){return Promise.reject(e)}},t}(),we=/*#__PURE__*/function(e){function n(){return e.apply(this,arguments)||this}t(n,e);var r=n.prototype;return r.getCurrent=function(){try{var e=this;return Promise.resolve(e.client.get("/me")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new O;if(!t.ok)throw new g;var n=t.json();return Promise.resolve(e.client.get("/users/"+n.id)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new O;if(!t.ok)throw new g;return t.json()})})}catch(e){return Promise.reject(e)}},r.logout=function(){try{var e=this;return Promise.resolve(e.client.post("/logout")).then(function(t){if(e.client.sessionTokenStorage.removeSessionToken(),e.client.cookie.removeAuthCookie(),e.client.dispatcher.dispatchUserLoggedOutEvent(),401===t.status);else if(!t.ok)throw new g})}catch(e){return Promise.reject(e)}},n}(H),Ce=/*#__PURE__*/function(n){function r(t,r){var i;(i=n.call(this)||this).session=void 0,i.user=void 0,i.cookie=void 0,i.client=void 0,i.relay=void 0;var o=e({timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check"},r);return i.client=new M(t,o),i.session=new W(t,o),i.user=new we(t,o),i.relay=new X(t,o),i.cookie=new K(o),i}t(r,n);var i=r.prototype;return i.setLang=function(e){this.client.lang=e},i.createState=function(e,t){return void 0===t&&(t={}),ke.create(this,e,t)},i.getUser=function(){try{return Promise.resolve(this.user.getCurrent())}catch(e){return Promise.reject(e)}},i.validateSession=function(){try{return Promise.resolve(this.session.validate())}catch(e){return Promise.reject(e)}},i.getSessionToken=function(){return this.cookie.getAuthCookie()},i.logout=function(){try{return Promise.resolve(this.user.logout())}catch(e){return Promise.reject(e)}},r}(v);exports.Action=be,exports.Client=H,exports.ConflictError=S,exports.CustomEventWithDetail=p,exports.EmailAddressAlreadyExistsError=T,exports.ForbiddenError=I,exports.Hanko=Ce,exports.HankoError=y,exports.HttpClient=M,exports.InvalidPasscodeError=C,exports.InvalidPasswordError=w,exports.InvalidWebauthnCredentialError=P,exports.MaxNumOfEmailAddressesReachedError=L,exports.MaxNumOfPasscodeAttemptsReachedError=E,exports.NotFoundError=A,exports.PasscodeExpiredError=x,exports.Relay=X,exports.RequestTimeoutError=k,exports.SessionClient=W,exports.State=ke,exports.TechnicalError=g,exports.ThirdPartyError=N,exports.TooManyRequestsError=_,exports.UnauthorizedError=O,exports.UserClient=we,exports.UserVerificationError=j,exports.WebauthnRequestCancelledError=b,exports.WebauthnSupport=G,exports.sessionCreatedType=c,exports.sessionExpiredType=u,exports.userDeletedType=l,exports.userLoggedOutType=h;
|
|
2
2
|
//# sourceMappingURL=sdk.cjs.map
|