@teamhanko/hanko-frontend-sdk 0.4.0-alpha → 0.8.0-beta
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 +108 -9
- package/dist/Hanko.d.ts +7 -1
- package/dist/index.d.ts +5 -2
- package/dist/lib/Cookie.d.ts +26 -0
- package/dist/lib/Dto.d.ts +38 -19
- package/dist/lib/Session.d.ts +47 -0
- package/dist/lib/Throttle.d.ts +32 -0
- package/dist/lib/client/EmailClient.d.ts +3 -3
- package/dist/lib/client/HttpClient.d.ts +19 -21
- package/dist/lib/client/PasscodeClient.d.ts +2 -3
- package/dist/lib/client/PasswordClient.d.ts +4 -3
- package/dist/lib/client/UserClient.d.ts +6 -3
- package/dist/lib/client/WebauthnClient.d.ts +5 -6
- package/dist/lib/events/CustomEvents.d.ts +69 -0
- package/dist/lib/events/Dispatcher.d.ts +44 -0
- package/dist/lib/events/Listener.d.ts +114 -0
- package/dist/lib/events/Relay.d.ts +47 -0
- package/dist/lib/events/Scheduler.d.ts +43 -0
- package/dist/lib/state/State.d.ts +5 -3
- package/dist/lib/state/session/SessionState.d.ts +78 -0
- package/dist/lib/state/{PasscodeState.d.ts → users/PasscodeState.d.ts} +1 -1
- package/dist/lib/state/{UserState.d.ts → users/UserState.d.ts} +2 -1
- package/dist/lib/state/{WebauthnState.d.ts → users/WebauthnState.d.ts} +1 -1
- 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 +3 -3
- /package/dist/lib/state/{PasswordState.d.ts → users/PasswordState.d.ts} +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { create as createWebauthnCredential, get as getWebauthnCredential } from "@github/webauthn-json";
|
|
2
2
|
import { Client } from "./Client";
|
|
3
|
-
import { PasscodeState } from "../state/PasscodeState";
|
|
4
|
-
import { WebauthnState } from "../state/WebauthnState";
|
|
5
|
-
import { User, WebauthnCredentials } from "../Dto";
|
|
3
|
+
import { PasscodeState } from "../state/users/PasscodeState";
|
|
4
|
+
import { WebauthnState } from "../state/users/WebauthnState";
|
|
5
|
+
import { User, WebauthnCredentials, WebauthnFinalized } from "../Dto";
|
|
6
6
|
/**
|
|
7
7
|
* A class that handles WebAuthn authentication and registration.
|
|
8
8
|
*
|
|
@@ -32,8 +32,9 @@ declare class WebauthnClient extends Client {
|
|
|
32
32
|
* @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnLoginInit
|
|
33
33
|
* @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/webauthnLoginFinal
|
|
34
34
|
* @see https://www.w3.org/TR/webauthn-2/#authentication-ceremony
|
|
35
|
+
* @return {WebauthnFinalized}
|
|
35
36
|
*/
|
|
36
|
-
login(userID?: string, useConditionalMediation?: boolean): Promise<
|
|
37
|
+
login(userID?: string, useConditionalMediation?: boolean): Promise<WebauthnFinalized>;
|
|
37
38
|
/**
|
|
38
39
|
* Performs a WebAuthn registration ceremony.
|
|
39
40
|
*
|
|
@@ -64,7 +65,6 @@ declare class WebauthnClient extends Client {
|
|
|
64
65
|
* @param {string=} credentialID - The credential's UUID.
|
|
65
66
|
* @param {string} name - The new credential name.
|
|
66
67
|
* @return {Promise<void>}
|
|
67
|
-
* @throws {NotFoundError}
|
|
68
68
|
* @throws {UnauthorizedError}
|
|
69
69
|
* @throws {RequestTimeoutError}
|
|
70
70
|
* @throws {TechnicalError}
|
|
@@ -76,7 +76,6 @@ declare class WebauthnClient extends Client {
|
|
|
76
76
|
*
|
|
77
77
|
* @param {string=} credentialID - The credential's UUID.
|
|
78
78
|
* @return {Promise<void>}
|
|
79
|
-
* @throws {NotFoundError}
|
|
80
79
|
* @throws {UnauthorizedError}
|
|
81
80
|
* @throws {RequestTimeoutError}
|
|
82
81
|
* @throws {TechnicalError}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The type of the `hanko-session-created` event.
|
|
3
|
+
* @typedef {string} sessionCreatedType
|
|
4
|
+
* @memberOf Listener
|
|
5
|
+
*/
|
|
6
|
+
export declare const sessionCreatedType: "hanko-session-created";
|
|
7
|
+
/**
|
|
8
|
+
* The type of the `hanko-session-expired` event.
|
|
9
|
+
* @typedef {string} sessionExpiredType
|
|
10
|
+
* @memberOf Listener
|
|
11
|
+
*/
|
|
12
|
+
export declare const sessionExpiredType: "hanko-session-expired";
|
|
13
|
+
/**
|
|
14
|
+
* The type of the `hanko-user-logged-out` event.
|
|
15
|
+
* @typedef {string} userLoggedOutType
|
|
16
|
+
* @memberOf Listener
|
|
17
|
+
*/
|
|
18
|
+
export declare const userLoggedOutType: "hanko-user-logged-out";
|
|
19
|
+
/**
|
|
20
|
+
* The type of the `hanko-user-deleted` event.
|
|
21
|
+
* @typedef {string} userDeletedType
|
|
22
|
+
* @memberOf Listener
|
|
23
|
+
*/
|
|
24
|
+
export declare const userDeletedType: "hanko-user-deleted";
|
|
25
|
+
/**
|
|
26
|
+
* The type of the `hanko-auth-flow-completed` event.
|
|
27
|
+
* @typedef {string} authFlowCompletedType
|
|
28
|
+
* @memberOf Listener
|
|
29
|
+
*/
|
|
30
|
+
export declare const authFlowCompletedType: "hanko-auth-flow-completed";
|
|
31
|
+
/**
|
|
32
|
+
* The data passed in the `hanko-session-created` or `hanko-session-resumed` event.
|
|
33
|
+
*
|
|
34
|
+
* @interface
|
|
35
|
+
* @category SDK
|
|
36
|
+
* @subcategory Events
|
|
37
|
+
* @property {string=} jwt - The JSON web token associated with the session. Only present when the Hanko-API allows the JWT to be accessible client-side.
|
|
38
|
+
* @property {number} expirationSeconds - The number of seconds until the JWT expires.
|
|
39
|
+
* @property {string} userID - The user associated with the session.
|
|
40
|
+
*/
|
|
41
|
+
export interface SessionDetail {
|
|
42
|
+
jwt?: string;
|
|
43
|
+
expirationSeconds: number;
|
|
44
|
+
userID: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The data passed in the `hanko-auth-flow-completed` event.
|
|
48
|
+
*
|
|
49
|
+
* @interface
|
|
50
|
+
* @category SDK
|
|
51
|
+
* @subcategory Events
|
|
52
|
+
* @property {string} userID - The user associated with the removed session.
|
|
53
|
+
*/
|
|
54
|
+
export interface AuthFlowCompletedDetail {
|
|
55
|
+
userID: string;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* A custom event that includes a detail object.
|
|
59
|
+
*
|
|
60
|
+
* @category SDK
|
|
61
|
+
* @subcategory Events
|
|
62
|
+
* @extends CustomEvent
|
|
63
|
+
* @ignore
|
|
64
|
+
* @param {string} type - The type of the event.
|
|
65
|
+
* @param {T} detail - The detail object to include in the event.
|
|
66
|
+
*/
|
|
67
|
+
export declare class CustomEventWithDetail<T> extends CustomEvent<T> {
|
|
68
|
+
constructor(type: string, detail: T);
|
|
69
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { SessionDetail, AuthFlowCompletedDetail } from "./CustomEvents";
|
|
2
|
+
import { SessionState } from "../state/session/SessionState";
|
|
3
|
+
/**
|
|
4
|
+
* A class that dispatches custom events.
|
|
5
|
+
*
|
|
6
|
+
* @category SDK
|
|
7
|
+
* @subcategory Internal
|
|
8
|
+
*/
|
|
9
|
+
export declare class Dispatcher {
|
|
10
|
+
_dispatchEvent: any;
|
|
11
|
+
_sessionState: SessionState;
|
|
12
|
+
/**
|
|
13
|
+
* Dispatches a custom event.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} type
|
|
16
|
+
* @param {T} detail
|
|
17
|
+
* @private
|
|
18
|
+
*/
|
|
19
|
+
private dispatch;
|
|
20
|
+
/**
|
|
21
|
+
* Dispatches a "hanko-session-created" event to the document with the specified detail.
|
|
22
|
+
*
|
|
23
|
+
* @param {SessionDetail} detail - The event detail.
|
|
24
|
+
*/
|
|
25
|
+
dispatchSessionCreatedEvent(detail: SessionDetail): void;
|
|
26
|
+
/**
|
|
27
|
+
* Dispatches a "hanko-session-expired" event to the document.
|
|
28
|
+
*/
|
|
29
|
+
dispatchSessionExpiredEvent(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Dispatches a "hanko-user-logged-out" event to the document.
|
|
32
|
+
*/
|
|
33
|
+
dispatchUserLoggedOutEvent(): void;
|
|
34
|
+
/**
|
|
35
|
+
* Dispatches a "hanko-user-deleted" event to the document.
|
|
36
|
+
*/
|
|
37
|
+
dispatchUserDeletedEvent(): void;
|
|
38
|
+
/**
|
|
39
|
+
* Dispatches a "hanko-auth-flow-completed" event to the document with the specified detail.
|
|
40
|
+
*
|
|
41
|
+
* @param {AuthFlowCompletedDetail} detail - The event detail.
|
|
42
|
+
*/
|
|
43
|
+
dispatchAuthFlowCompletedEvent(detail: AuthFlowCompletedDetail): void;
|
|
44
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { Throttle } from "../Throttle";
|
|
2
|
+
import { SessionDetail, AuthFlowCompletedDetail } from "./CustomEvents";
|
|
3
|
+
/**
|
|
4
|
+
* A callback function to be executed when an event is triggered.
|
|
5
|
+
*
|
|
6
|
+
* @alias CallbackFunc
|
|
7
|
+
* @typedef {function} CallbackFunc
|
|
8
|
+
* @memberOf Listener
|
|
9
|
+
*/
|
|
10
|
+
type CallbackFunc<T> = (detail: T) => any;
|
|
11
|
+
/**
|
|
12
|
+
* A function returned when adding an event listener. The function can be called to remove the corresponding event
|
|
13
|
+
* listener.
|
|
14
|
+
*
|
|
15
|
+
* @alias CleanupFunc
|
|
16
|
+
* @typedef {function} CleanupFunc
|
|
17
|
+
* @memberOf Listener
|
|
18
|
+
*/
|
|
19
|
+
type CleanupFunc = () => void;
|
|
20
|
+
/**
|
|
21
|
+
* A class to bind event listener for custom events.
|
|
22
|
+
*
|
|
23
|
+
* @category SDK
|
|
24
|
+
* @subcategory Events
|
|
25
|
+
*/
|
|
26
|
+
export declare class Listener {
|
|
27
|
+
throttleLimit: number;
|
|
28
|
+
_addEventListener: any;
|
|
29
|
+
_removeEventListener: any;
|
|
30
|
+
_throttle: typeof Throttle.throttle;
|
|
31
|
+
/**
|
|
32
|
+
* Wraps the given callback.
|
|
33
|
+
*
|
|
34
|
+
* @param callback
|
|
35
|
+
* @param throttle
|
|
36
|
+
* @private
|
|
37
|
+
* @return {WrappedCallback}
|
|
38
|
+
*/
|
|
39
|
+
private wrapCallback;
|
|
40
|
+
/**
|
|
41
|
+
* Adds an event listener with the specified type, callback function, and options.
|
|
42
|
+
*
|
|
43
|
+
* @private
|
|
44
|
+
* @param {EventListenerWithTypeParams<T>} params - The parameters for the event listener.
|
|
45
|
+
* @returns {CleanupFunc} This function can be called to remove the event listener.
|
|
46
|
+
*/
|
|
47
|
+
private addEventListenerWithType;
|
|
48
|
+
/**
|
|
49
|
+
* Maps the parameters for an event listener to the `EventListenerWithTypeParams` interface.
|
|
50
|
+
*
|
|
51
|
+
* @static
|
|
52
|
+
* @private
|
|
53
|
+
* @param {string} type - The type of the event.
|
|
54
|
+
* @param {EventListenerParams<T>} params - The parameters for the event listener.
|
|
55
|
+
* @param {boolean} [throttle=false] - Whether the event listener should be throttled.
|
|
56
|
+
* @returns {EventListenerWithTypeParams<T>}
|
|
57
|
+
**/
|
|
58
|
+
private static mapAddEventListenerParams;
|
|
59
|
+
/**
|
|
60
|
+
* Adds an event listener with the specified type, callback function, and options.
|
|
61
|
+
*
|
|
62
|
+
* @private
|
|
63
|
+
* @param {string} type - The type of the event.
|
|
64
|
+
* @param {EventListenerParams<T>} params - The parameters for the event listener.
|
|
65
|
+
* @param {boolean=} throttle - Whether the event listener should be throttled.
|
|
66
|
+
* @returns {CleanupFunc} This function can be called to remove the event listener.
|
|
67
|
+
*/
|
|
68
|
+
private addEventListener;
|
|
69
|
+
/**
|
|
70
|
+
* Adds an event listener for "hanko-session-created" events. Will be triggered across all browser windows, when the user
|
|
71
|
+
* logs in, or when the page has been loaded or refreshed and there is a valid session.
|
|
72
|
+
*
|
|
73
|
+
* @param {CallbackFunc<SessionDetail>} callback - The function to be called when the event is triggered.
|
|
74
|
+
* @param {boolean=} once - Whether the event listener should be removed after being called once.
|
|
75
|
+
* @returns {CleanupFunc} This function can be called to remove the event listener.
|
|
76
|
+
*/
|
|
77
|
+
onSessionCreated(callback: CallbackFunc<SessionDetail>, once?: boolean): CleanupFunc;
|
|
78
|
+
/**
|
|
79
|
+
* Adds an event listener for "hanko-session-expired" events. The event will be triggered across all browser windows
|
|
80
|
+
* as soon as the current JWT expires or the user logs out. It also triggers, when the user deletes the account in
|
|
81
|
+
* another window.
|
|
82
|
+
*
|
|
83
|
+
* @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.
|
|
84
|
+
* @param {boolean=} once - Whether the event listener should be removed after being called once.
|
|
85
|
+
* @returns {CleanupFunc} This function can be called to remove the event listener.
|
|
86
|
+
*/
|
|
87
|
+
onSessionExpired(callback: CallbackFunc<null>, once?: boolean): CleanupFunc;
|
|
88
|
+
/**
|
|
89
|
+
* Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account in
|
|
90
|
+
* the browser window where the deletion happened.
|
|
91
|
+
*
|
|
92
|
+
* @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.
|
|
93
|
+
* @param {boolean=} once - Whether the event listener should be removed after being called once.
|
|
94
|
+
* @returns {CleanupFunc} This function can be called to remove the event listener.
|
|
95
|
+
*/
|
|
96
|
+
onUserLoggedOut(callback: CallbackFunc<null>, once?: boolean): CleanupFunc;
|
|
97
|
+
/**
|
|
98
|
+
* Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account.
|
|
99
|
+
*
|
|
100
|
+
* @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.
|
|
101
|
+
* @param {boolean=} once - Whether the event listener should be removed after being called once.
|
|
102
|
+
* @returns {CleanupFunc} This function can be called to remove the event listener.
|
|
103
|
+
*/
|
|
104
|
+
onUserDeleted(callback: CallbackFunc<null>, once?: boolean): CleanupFunc;
|
|
105
|
+
/**
|
|
106
|
+
* Adds an event listener for hanko-auth-flow-completed events. Will be triggered after the login or registration flow has been completed.
|
|
107
|
+
*
|
|
108
|
+
* @param {CallbackFunc<AuthFlowCompletedDetail>} callback - The function to be called when the event is triggered.
|
|
109
|
+
* @param {boolean=} once - Whether the event listener should be removed after being called once.
|
|
110
|
+
* @returns {CleanupFunc} This function can be called to remove the event listener.
|
|
111
|
+
*/
|
|
112
|
+
onAuthFlowCompleted(callback: CallbackFunc<AuthFlowCompletedDetail>, once?: boolean): CleanupFunc;
|
|
113
|
+
}
|
|
114
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Listener } from "./Listener";
|
|
2
|
+
import { Scheduler } from "./Scheduler";
|
|
3
|
+
import { Dispatcher } from "./Dispatcher";
|
|
4
|
+
import { Session } from "../Session";
|
|
5
|
+
/**
|
|
6
|
+
* A class that dispatches events and scheduled events, based on other events.
|
|
7
|
+
*
|
|
8
|
+
* @category SDK
|
|
9
|
+
* @subcategory Internal
|
|
10
|
+
* @extends Dispatcher
|
|
11
|
+
*/
|
|
12
|
+
export declare class Relay extends Dispatcher {
|
|
13
|
+
_listener: Listener;
|
|
14
|
+
_scheduler: Scheduler;
|
|
15
|
+
_session: Session;
|
|
16
|
+
constructor();
|
|
17
|
+
/**
|
|
18
|
+
* Removes the scheduled "hanko-session-expired" event and re-schedules a new event with updated expirationSeconds, to
|
|
19
|
+
* ensure the "hanko-session-expired" event won't be triggered too early.
|
|
20
|
+
*
|
|
21
|
+
* @private
|
|
22
|
+
* @param {SessionDetail} detail - The event detail.
|
|
23
|
+
*/
|
|
24
|
+
private scheduleSessionExpiredEvent;
|
|
25
|
+
/**
|
|
26
|
+
* Cancels scheduled "hanko-session-expired" events, to prevent it from being triggered again (e.g. when there are
|
|
27
|
+
* multiple SDK instances).
|
|
28
|
+
*
|
|
29
|
+
* @private
|
|
30
|
+
*/
|
|
31
|
+
private cancelSessionExpiredEvent;
|
|
32
|
+
/**
|
|
33
|
+
* Handles the "storage" event in case the local storage entry, that contains the session detail has been changed by
|
|
34
|
+
* another window. Depending on the new value of `expirationSeconds`, it either dispatches a "hanko-session-created"
|
|
35
|
+
* or a "hanko-session-expired" event.
|
|
36
|
+
*
|
|
37
|
+
* @private
|
|
38
|
+
* @param {StorageEvent} event - The storage event object.
|
|
39
|
+
*/
|
|
40
|
+
private handleStorageEvent;
|
|
41
|
+
/**
|
|
42
|
+
* Listens for events sent in the current browser.
|
|
43
|
+
*
|
|
44
|
+
* @private
|
|
45
|
+
*/
|
|
46
|
+
private listenEventDependencies;
|
|
47
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents a task to be scheduled in the scheduler.
|
|
3
|
+
*
|
|
4
|
+
* @ignore
|
|
5
|
+
* @param {number} timeoutID - the ID returned by `setTimeout()`
|
|
6
|
+
* @param {string} type - The type, helps to organize the tasks.
|
|
7
|
+
* @param {Function} func - The function to be called within the task.
|
|
8
|
+
*/
|
|
9
|
+
export type Task = {
|
|
10
|
+
timeoutID: number;
|
|
11
|
+
type: string;
|
|
12
|
+
func: () => any;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* A class that manages scheduled tasks.
|
|
16
|
+
*
|
|
17
|
+
* @category SDK
|
|
18
|
+
* @subcategory Internal
|
|
19
|
+
*/
|
|
20
|
+
export declare class Scheduler {
|
|
21
|
+
_tasks: Task[];
|
|
22
|
+
/**
|
|
23
|
+
* Removes a task from the scheduler.
|
|
24
|
+
*
|
|
25
|
+
* @private
|
|
26
|
+
* @param {Task} task - The task to be removed.
|
|
27
|
+
*/
|
|
28
|
+
private removeTask;
|
|
29
|
+
/**
|
|
30
|
+
* Removes all tasks with a given type from the scheduler.
|
|
31
|
+
*
|
|
32
|
+
* @param {string} type - The type of tasks to be removed.
|
|
33
|
+
*/
|
|
34
|
+
removeTasksWithType(type: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Schedules a task to be executed after a given timeout.
|
|
37
|
+
*
|
|
38
|
+
* @param {string} type - The type of the task.
|
|
39
|
+
* @param {Function} func - The function to be executed when the task is triggered.
|
|
40
|
+
* @param {number} timeoutSeconds - The timeout after which the task should be executed, in seconds.
|
|
41
|
+
*/
|
|
42
|
+
scheduleTask(type: string, func: () => any, timeoutSeconds: number): void;
|
|
43
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { LocalStorageUsers } from "./UserState";
|
|
1
|
+
import { LocalStorageUsers } from "./users/UserState";
|
|
2
|
+
import { LocalStorageSession } from "./session/SessionState";
|
|
2
3
|
/**
|
|
3
4
|
* @interface
|
|
4
5
|
* @category SDK
|
|
@@ -7,6 +8,7 @@ import { LocalStorageUsers } from "./UserState";
|
|
|
7
8
|
*/
|
|
8
9
|
interface LocalStorage {
|
|
9
10
|
users?: LocalStorageUsers;
|
|
11
|
+
session?: LocalStorageSession;
|
|
10
12
|
}
|
|
11
13
|
/**
|
|
12
14
|
* A class to read and write local storage contents.
|
|
@@ -17,9 +19,9 @@ interface LocalStorage {
|
|
|
17
19
|
* @subcategory Internal
|
|
18
20
|
*/
|
|
19
21
|
declare abstract class State {
|
|
20
|
-
|
|
22
|
+
key: string;
|
|
21
23
|
ls: LocalStorage;
|
|
22
|
-
constructor(key
|
|
24
|
+
constructor(key: string);
|
|
23
25
|
/**
|
|
24
26
|
* Reads and decodes the locally stored data.
|
|
25
27
|
*
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { State } from "../State";
|
|
2
|
+
/**
|
|
3
|
+
* @interface
|
|
4
|
+
* @category SDK
|
|
5
|
+
* @subcategory Internal
|
|
6
|
+
* @property {Object.<string, LocalStorageSession>} - A dictionary for mapping users to their states.
|
|
7
|
+
*/
|
|
8
|
+
export interface LocalStorageSession {
|
|
9
|
+
expiry: number;
|
|
10
|
+
userID: string;
|
|
11
|
+
authFlowCompleted: boolean;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A class to read and write local storage contents regarding sessions.
|
|
15
|
+
*
|
|
16
|
+
* @extends State
|
|
17
|
+
* @param {string} key - The local storage key.
|
|
18
|
+
* @category SDK
|
|
19
|
+
* @subcategory Internal
|
|
20
|
+
*/
|
|
21
|
+
declare class SessionState extends State {
|
|
22
|
+
constructor();
|
|
23
|
+
/**
|
|
24
|
+
* Reads the current state.
|
|
25
|
+
*
|
|
26
|
+
* @public
|
|
27
|
+
* @return {SessionState}
|
|
28
|
+
*/
|
|
29
|
+
read(): SessionState;
|
|
30
|
+
/**
|
|
31
|
+
* Gets the session state.
|
|
32
|
+
*
|
|
33
|
+
* @return {LocalStorageSession}
|
|
34
|
+
*/
|
|
35
|
+
getState(): LocalStorageSession;
|
|
36
|
+
/**
|
|
37
|
+
* Gets the number of seconds until the active session is valid.
|
|
38
|
+
*
|
|
39
|
+
* @return {number}
|
|
40
|
+
*/
|
|
41
|
+
getExpirationSeconds(): number;
|
|
42
|
+
/**
|
|
43
|
+
* Sets the number of seconds until the active session is valid.
|
|
44
|
+
*
|
|
45
|
+
* @param {number} seconds - The number of seconds
|
|
46
|
+
* @return {SessionState}
|
|
47
|
+
*/
|
|
48
|
+
setExpirationSeconds(seconds: number): SessionState;
|
|
49
|
+
/**
|
|
50
|
+
* Gets the user id.
|
|
51
|
+
*/
|
|
52
|
+
getUserID(): string;
|
|
53
|
+
/**
|
|
54
|
+
* Sets the user id.
|
|
55
|
+
*
|
|
56
|
+
* @param {string} userID - The user id
|
|
57
|
+
* @return {SessionState}
|
|
58
|
+
*/
|
|
59
|
+
setUserID(userID: string): SessionState;
|
|
60
|
+
/**
|
|
61
|
+
* Gets the authFlowCompleted indicator.
|
|
62
|
+
*/
|
|
63
|
+
getAuthFlowCompleted(): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Sets the authFlowCompleted indicator.
|
|
66
|
+
*
|
|
67
|
+
* @param {string} completed - The authFlowCompleted indicator.
|
|
68
|
+
* @return {SessionState}
|
|
69
|
+
*/
|
|
70
|
+
setAuthFlowCompleted(completed: boolean): SessionState;
|
|
71
|
+
/**
|
|
72
|
+
* Removes the session details.
|
|
73
|
+
*
|
|
74
|
+
* @return {SessionState}
|
|
75
|
+
*/
|
|
76
|
+
reset(): SessionState;
|
|
77
|
+
}
|
|
78
|
+
export { SessionState };
|
|
@@ -100,7 +100,7 @@ declare class PasscodeState extends UserState {
|
|
|
100
100
|
* Sets the number of seconds until a new passcode can be sent.
|
|
101
101
|
*
|
|
102
102
|
* @param {string} userID - The UUID of the user.
|
|
103
|
-
* @param {
|
|
103
|
+
* @param {number} seconds - Number of seconds the passcode is valid for.
|
|
104
104
|
* @return {PasscodeState}
|
|
105
105
|
*/
|
|
106
106
|
setResendAfter(userID: string, seconds: number): PasscodeState;
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @subcategory Internal
|
|
5
5
|
* @property {Object.<string, LocalStorageUser>} - A dictionary for mapping users to their states.
|
|
6
6
|
*/
|
|
7
|
-
import { State } from "
|
|
7
|
+
import { State } from "../State";
|
|
8
8
|
import { LocalStorageWebauthn } from "./WebauthnState";
|
|
9
9
|
import { LocalStoragePasscode } from "./PasscodeState";
|
|
10
10
|
import { LocalStoragePassword } from "./PasswordState";
|
|
@@ -40,6 +40,7 @@ export interface LocalStorageUsers {
|
|
|
40
40
|
* @subcategory Internal
|
|
41
41
|
*/
|
|
42
42
|
declare abstract class UserState extends State {
|
|
43
|
+
constructor();
|
|
43
44
|
/**
|
|
44
45
|
* Gets the state of the specified user.
|
|
45
46
|
*
|
package/dist/sdk.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function t(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,r(t,e)}function e(t){return e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},e(t)}function r(t,e){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},r(t,e)}function n(t,e,i){return n=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(t){return!1}}()?Reflect.construct.bind():function(t,e,n){var i=[null];i.push.apply(i,e);var o=new(Function.bind.apply(t,i));return n&&r(o,n.prototype),o},n.apply(null,arguments)}function i(t){var o="function"==typeof Map?new Map:void 0;return i=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==o){if(o.has(t))return o.get(t);o.set(t,i)}function i(){return n(t,arguments,e(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),r(i,t)},i(t)}function o(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var s=/*#__PURE__*/function(e){function r(t,n,i){var s;return(s=e.call(this,t)||this).code=void 0,s.cause=void 0,s.code=n,s.cause=i,Object.setPrototypeOf(o(s),r.prototype),s}return t(r,e),r}(/*#__PURE__*/i(Error)),a=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),u=/*#__PURE__*/function(e){function r(t,n){var i;return i=e.call(this,"Conflict error","conflict",n)||this,Object.setPrototypeOf(o(i),r.prototype),i}return t(r,e),r}(s),c=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),h=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),l=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),d=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),f=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),p=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),w=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),v=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),m=/*#__PURE__*/function(e){function r(t,n){var i;return(i=e.call(this,"Too many requests error","tooManyRequests",n)||this).retryAfter=void 0,i.retryAfter=t,Object.setPrototypeOf(o(i),r.prototype),i}return t(r,e),r}(s),y=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),g=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),P=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),b=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",t)||this,Object.setPrototypeOf(o(n),r.prototype),n}return t(r,e),r}(s),C=/*#__PURE__*/function(e){function r(t,n){var i;return i=e.call(this,"An error occurred during third party sign up/sign in",t,n)||this,Object.setPrototypeOf(o(i),r.prototype),i}return t(r,e),r}(s);function A(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)t[n]=r[n]}return t}var S=function t(e,r){function n(t,n,i){if("undefined"!=typeof document){"number"==typeof(i=A({},r,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).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=t+"="+e.write(n,t)+o}}return Object.create({set:n,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var r=document.cookie?document.cookie.split("; "):[],n={},i=0;i<r.length;i++){var o=r[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(n[a]=e.read(s,a),t===a)break}catch(t){}}return t?n[t]:n}},remove:function(t,e){n(t,"",A({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,A({},this.attributes,e))},withConverter:function(e){return t(A({},this.converter,e),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(e)}})}({read:function(t){return'"'===t[0]&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"}),j=/*#__PURE__*/function(){function t(t){this._xhr=void 0,this._xhr=t}return t.prototype.get=function(t){return this._xhr.getResponseHeader(t)},t}(),O=/*#__PURE__*/function(){function t(t){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 j(t),this.ok=t.status>=200&&t.status<=299,this.status=t.status,this.statusText=t.statusText,this.url=t.responseURL,this.xhr=t}var e=t.prototype;return e.json=function(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON},e.parseRetryAfterHeader=function(){var t=parseInt(this.headers.get("Retry-After"),10);return isNaN(t)?0:t},t}(),x=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e=13e3),this.timeout=void 0,this.api=void 0,this.authCookieName="hanko",this.api=t,this.timeout=e}var e=t.prototype;return e._fetch=function(t,e,r){void 0===r&&(r=new XMLHttpRequest);var n=this,i=this.api+t,o=this.timeout,s=this._getAuthCookie();return new Promise(function(t,u){r.open(e.method,i,!0),r.setRequestHeader("Accept","application/json"),r.setRequestHeader("Content-Type","application/json"),s&&r.setRequestHeader("Authorization","Bearer "+s),r.timeout=o,r.withCredentials=!0,r.onload=function(){if(r.getAllResponseHeaders().split("\r\n").filter(function(t){return t.toLowerCase().startsWith("x-auth-token")}).length){var e=r.getResponseHeader("X-Auth-Token");e&&n._setAuthCookie(e)}t(new O(r))},r.onerror=function(){u(new a)},r.ontimeout=function(){u(new c)},r.send(e.body?e.body.toString():null)})},e._getAuthCookie=function(){return S.get(this.authCookieName)},e._setAuthCookie=function(t){var e=!!this.api.match("^https://");S.set(this.authCookieName,t,{secure:e})},e.removeAuthCookie=function(){S.remove(this.authCookieName)},e.get=function(t){return this._fetch(t,{method:"GET"})},e.post=function(t,e){return this._fetch(t,{method:"POST",body:JSON.stringify(e)})},e.put=function(t,e){return this._fetch(t,{method:"PUT",body:JSON.stringify(e)})},e.patch=function(t,e){return this._fetch(t,{method:"PATCH",body:JSON.stringify(e)})},e.delete=function(t){return this._fetch(t,{method:"DELETE"})},t}(),k=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new x(t,e)},R=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}return t(r,e),r.prototype.get=function(){try{return Promise.resolve(this.client.get("/.well-known/config")).then(function(t){if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},r}(k),E=/*#__PURE__*/function(){function t(t){void 0===t&&(t="hanko"),this.key=void 0,this.ls=void 0,this.key=t,this.ls={}}var e=t.prototype;return e.read=function(){var t;try{var e=localStorage.getItem(this.key),r=decodeURIComponent(decodeURI(window.atob(e)));t=JSON.parse(r)}catch(t){return this.ls={},this}return this.ls=t,this},e.write=function(){var t=JSON.stringify(this.ls),e=window.btoa(encodeURI(encodeURIComponent(t)));return localStorage.setItem(this.key,e),this},t.timeToRemainingSeconds=function(t){return void 0===t&&(t=0),t-Math.floor(Date.now()/1e3)},t.remainingSecondsToTime=function(t){return void 0===t&&(t=0),Math.floor(Date.now()/1e3)+t},t}(),_=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}return t(r,e),r.prototype.getUserState=function(t){var e;return(e=this.ls).users||(e.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,t)||(this.ls.users[t]={}),this.ls.users[t]},r}(E),T=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.getState=function(t){var r;return(r=e.prototype.getUserState.call(this,t)).passcode||(r.passcode={})},n.read=function(){return e.prototype.read.call(this),this},n.getActiveID=function(t){return this.getState(t).id},n.setActiveID=function(t,e){return this.getState(t).id=e,this},n.getEmailID=function(t){return this.getState(t).emailID},n.setEmailID=function(t,e){return this.getState(t).emailID=e,this},n.reset=function(t){var e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,delete e.emailID,this},n.getTTL=function(t){return E.timeToRemainingSeconds(this.getState(t).ttl)},n.setTTL=function(t,e){return this.getState(t).ttl=E.remainingSecondsToTime(e),this},n.getResendAfter=function(t){return E.timeToRemainingSeconds(this.getState(t).resendAfter)},n.setResendAfter=function(t,e){return this.getState(t).resendAfter=E.remainingSecondsToTime(e),this},r}(_),I=/*#__PURE__*/function(e){function r(t,r){var n;return void 0===r&&(r=13e3),(n=e.call(this,t,r)||this).state=void 0,n.state=new T,n}t(r,e);var n=r.prototype;return n.initialize=function(t,e,r){try{var n=this;n.state.read();var i=n.state.getTTL(t),o=n.state.getActiveID(t),s=n.state.getEmailID(t),u=n.state.getResendAfter(t);if(u>0)throw new m(u);if(!r&&i>0&&e===s)return Promise.resolve({id:o,ttl:i});var c={user_id:t};return e&&(c.email_id=e),Promise.resolve(n.client.post("/passcode/login/initialize",c)).then(function(r){if(429===r.status)throw u=r.parseRetryAfterHeader(),n.state.setResendAfter(t,u).write(),new m(u);if(401===r.status)throw new y;if(!r.ok)throw new a;var i=r.json();return n.state.setActiveID(t,i.id).setTTL(t,i.ttl),e&&n.state.setEmailID(t,e),n.state.write(),i})}catch(t){return Promise.reject(t)}},n.finalize=function(t,e){try{var r=this,n=r.state.read().getActiveID(t);if(r.state.getTTL(t)<=0)throw new p;return Promise.resolve(r.client.post("/passcode/login/finalize",{id:n,code:e})).then(function(e){if(401===e.status)throw new d;if(410===e.status)throw r.state.reset(t).write(),new w;if(!e.ok)throw new a;r.state.reset(t).write()})}catch(t){return Promise.reject(t)}},n.getTTL=function(t){return this.state.read().getTTL(t)},n.getResendAfter=function(t){return this.state.read().getResendAfter(t)},r}(k),U=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.getState=function(t){var r;return(r=e.prototype.getUserState.call(this,t)).password||(r.password={})},n.read=function(){return e.prototype.read.call(this),this},n.getRetryAfter=function(t){return E.timeToRemainingSeconds(this.getState(t).retryAfter)},n.setRetryAfter=function(t,e){return this.getState(t).retryAfter=E.remainingSecondsToTime(e),this},r}(_),N=/*#__PURE__*/function(e){function r(t,r){var n;return void 0===r&&(r=13e3),(n=e.call(this,t,r)||this).passwordState=void 0,n.passcodeState=void 0,n.passwordState=new U,n.passcodeState=new T,n}t(r,e);var n=r.prototype;return n.login=function(t,e){try{var r=this;return Promise.resolve(r.client.post("/password/login",{user_id:t,password:e})).then(function(e){if(401===e.status)throw new l;if(429===e.status){var n=e.parseRetryAfterHeader();throw r.passwordState.read().setRetryAfter(t,n).write(),new m(n)}if(!e.ok)throw new a;r.passcodeState.read().reset(t).write()})}catch(t){return Promise.reject(t)}},n.update=function(t,e){try{return Promise.resolve(this.client.put("/password",{user_id:t,password:e})).then(function(t){if(401===t.status)throw new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},n.getRetryAfter=function(t){return this.passwordState.read().getRetryAfter(t)},r}(k),D=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.getInfo=function(t){try{return Promise.resolve(this.client.post("/user",{email:t})).then(function(t){if(404===t.status)throw new v;if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},n.create=function(t){try{return Promise.resolve(this.client.post("/users",{email:t})).then(function(t){if(409===t.status)throw new u;if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},n.getCurrent=function(){try{var t=this;return Promise.resolve(t.client.get("/me")).then(function(e){if(400===e.status||401===e.status||404===e.status)throw new y;if(!e.ok)throw new a;var r=e.json();return Promise.resolve(t.client.get("/users/"+r.id)).then(function(t){if(400===t.status||401===t.status||404===t.status)throw new y;if(!t.ok)throw new a;return t.json()})})}catch(t){return Promise.reject(t)}},n.delete=function(){try{var t=this;return Promise.resolve(t.client.delete("/user")).then(function(e){if(!e.ok){if(401===e.status)throw new y;throw new a}t.client.removeAuthCookie()})}catch(t){return Promise.reject(t)}},n.logout=function(){try{var t=this;return Promise.resolve(t.client.post("/logout")).then(function(e){if(t.client.removeAuthCookie(),401===e.status);else if(!e.ok)throw new a})}catch(t){return Promise.reject(t)}},r}(k);function q(t){const e="==".slice(0,(4-t.length%4)%4),r=t.replace(/-/g,"+").replace(/_/g,"/")+e,n=atob(r),i=new ArrayBuffer(n.length),o=new Uint8Array(i);for(let t=0;t<n.length;t++)o[t]=n.charCodeAt(t);return i}function M(t){const e=new Uint8Array(t);let r="";for(const t of e)r+=String.fromCharCode(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var K="copy",W="convert";function z(t,e,r){if(e===K)return r;if(e===W)return t(r);if(e instanceof Array)return r.map(r=>z(t,e[0],r));if(e instanceof Object){const n={};for(const[i,o]of Object.entries(e)){if(o.derive){const t=o.derive(r);void 0!==t&&(r[i]=t)}if(i in r)n[i]=null!=r[i]?z(t,o.schema,r[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return n}}function H(t,e){return{required:!0,schema:t,derive:e}}function L(t){return{required:!0,schema:t}}function J(t){return{required:!1,schema:t}}var B={type:L(K),id:L(W),transports:J(K)},F={appid:J(K),appidExclude:J(K),credProps:J(K)},V={appid:J(K),appidExclude:J(K),credProps:J(K)},X={publicKey:L({rp:L(K),user:L({id:L(W),name:L(K),displayName:L(K)}),challenge:L(W),pubKeyCredParams:L(K),timeout:J(K),excludeCredentials:J([B]),authenticatorSelection:J(K),attestation:J(K),extensions:J(F)}),signal:J(K)},G={type:L(K),id:L(K),rawId:L(W),authenticatorAttachment:J(K),response:L({clientDataJSON:L(W),attestationObject:L(W),transports:H(K,t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:H(V,t=>t.getClientExtensionResults())},$={mediation:J(K),publicKey:L({challenge:L(W),timeout:J(K),rpId:J(K),allowCredentials:J([B]),userVerification:J(K),extensions:J(F)}),signal:J(K)},Q={type:L(K),id:L(K),rawId:L(W),authenticatorAttachment:J(K),response:L({clientDataJSON:L(W),authenticatorData:L(W),signature:L(W),userHandle:L(W)}),clientExtensionResults:H(V,t=>t.getClientExtensionResults())};async function Y(t){const e=await navigator.credentials.create(function(t){return z(q,X,t)}(t));return function(t){return z(M,G,t)}(e)}async function Z(t){const e=await navigator.credentials.get(function(t){return z(q,$,t)}(t));return function(t){return z(M,Q,t)}(e)}var tt=/*#__PURE__*/function(){function t(){}return t.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},t.isPlatformAuthenticatorAvailable=function(){try{return this.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},t.isSecurityKeySupported=function(){try{return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()):Promise.resolve(this.supported())}catch(t){return Promise.reject(t)}},t.isConditionalMediationAvailable=function(){try{return window.PublicKeyCredential&&window.PublicKeyCredential.isConditionalMediationAvailable?Promise.resolve(window.PublicKeyCredential.isConditionalMediationAvailable()):Promise.resolve(!1)}catch(t){return Promise.reject(t)}},t}(),et=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.getState=function(t){var r;return(r=e.prototype.getUserState.call(this,t)).webauthn||(r.webauthn={})},n.read=function(){return e.prototype.read.call(this),this},n.getCredentials=function(t){var e;return(e=this.getState(t)).credentials||(e.credentials=[])},n.addCredential=function(t,e){return this.getCredentials(t).push(e),this},n.matchCredentials=function(t,e){return this.getCredentials(t).filter(function(t){return e.find(function(e){return e.id===t})}).map(function(t){return{id:t}})},r}(_);function rt(t,e){try{var r=t()}catch(t){return e(t)}return r&&r.then?r.then(void 0,e):r}var nt=/*#__PURE__*/function(e){function r(t,r){var n;return void 0===r&&(r=13e3),(n=e.call(this,t,r)||this).webauthnState=void 0,n.passcodeState=void 0,n.controller=void 0,n._getCredential=Z,n._createCredential=Y,n.webauthnState=new et,n.passcodeState=new T,n}t(r,e);var n=r.prototype;return n.login=function(t,e){try{var r=this;return Promise.resolve(r.client.post("/webauthn/login/initialize",{user_id:t})).then(function(n){var i;function o(e){return i?e:Promise.resolve(r.client.post("/webauthn/login/finalize",s)).then(function(e){if(400===e.status||401===e.status)throw new f;if(!e.ok)throw new a;var n=e.json();r.webauthnState.read().addCredential(n.user_id,n.credential_id).write(),r.passcodeState.read().reset(t).write()})}if(!n.ok)throw new a;var s,u=n.json();u.signal=r._createAbortSignal(),e&&(u.mediation="conditional");var c=rt(function(){return Promise.resolve(r._getCredential(u)).then(function(t){s=t})},function(t){throw new h(t)});return c&&c.then?c.then(o):o(c)})}catch(t){return Promise.reject(t)}},n.register=function(){try{var t=this;return Promise.resolve(t.client.post("/webauthn/registration/initialize")).then(function(e){function r(e){return n.transports=n.response.transports,Promise.resolve(t.client.post("/webauthn/registration/finalize",n)).then(function(e){if(e.status>=400&&e.status<=499){if(422===e.status)throw new g;throw new y}if(!e.ok)throw new a;var r=e.json();t.webauthnState.read().addCredential(r.user_id,r.credential_id).write()})}if(e.status>=400&&e.status<=499)throw new y;if(!e.ok)throw new a;var n,i=e.json();i.signal=t._createAbortSignal();var o=rt(function(){return Promise.resolve(t._createCredential(i)).then(function(t){n=t})},function(t){throw new h(t)});return o&&o.then?o.then(r):r()})}catch(t){return Promise.reject(t)}},n.listCredentials=function(){try{return Promise.resolve(this.client.get("/webauthn/credentials")).then(function(t){if(401===t.status)throw new y;if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},n.updateCredential=function(t,e){try{return Promise.resolve(this.client.patch("/webauthn/credentials/"+t,{name:e})).then(function(t){if(401===t.status)throw new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},n.deleteCredential=function(t){try{return Promise.resolve(this.client.delete("/webauthn/credentials/"+t)).then(function(t){if(401===t.status)throw new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},n.shouldRegister=function(t){try{var e=tt.supported();if(!t.webauthn_credentials||!t.webauthn_credentials.length)return Promise.resolve(e);var r=this.webauthnState.read().matchCredentials(t.id,t.webauthn_credentials);return Promise.resolve(e&&!r.length)}catch(t){return Promise.reject(t)}},n._createAbortSignal=function(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal},r}(k),it=/*#__PURE__*/function(e){function r(){return e.apply(this,arguments)||this}t(r,e);var n=r.prototype;return n.list=function(){try{return Promise.resolve(this.client.get("/emails")).then(function(t){if(401===t.status)throw new y;if(!t.ok)throw new a;return t.json()})}catch(t){return Promise.reject(t)}},n.create=function(t){try{return Promise.resolve(this.client.post("/emails",{address:t})).then(function(t){if(t.ok)return t.json();if(400===t.status)throw new b;if(401===t.status)throw new y;if(409===t.status)throw new P;throw new a})}catch(t){return Promise.reject(t)}},n.setPrimaryEmail=function(t){try{return Promise.resolve(this.client.post("/emails/"+t+"/set_primary")).then(function(t){if(401===t.status)throw new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},n.delete=function(t){try{return Promise.resolve(this.client.delete("/emails/"+t)).then(function(t){if(401===t.status)throw new y;if(!t.ok)throw new a})}catch(t){return Promise.reject(t)}},r}(k),ot=/*#__PURE__*/function(e){function r(t,r){return void 0===r&&(r=13e3),e.call(this,t,r)||this}t(r,e);var n=r.prototype;return n.auth=function(t,e){try{var r=new URL("/thirdparty/auth",this.client.api);if(!t)throw new C("somethingWentWrong",new Error("provider missing from request"));if(!e)throw new C("somethingWentWrong",new Error("redirectTo missing from request"));return r.searchParams.append("provider",t),r.searchParams.append("redirect_to",e),window.location.assign(r.href),Promise.resolve()}catch(t){return Promise.reject(t)}},n.getError=function(){var t=new URLSearchParams(window.location.search),e=t.get("error"),r=t.get("error_description");if(e){var n="";switch(e){case"access_denied":n="thirdPartyAccessDenied";break;case"user_conflict":n="emailAddressAlreadyExistsError";break;case"multiple_accounts":n="thirdPartyMultipleAccounts";break;case"unverified_email":n="thirdPartyUnverifiedEmail";break;case"email_maxnum":n="maxNumOfEmailAddressesReached";break;default:n="somethingWentWrong"}return new C(n,new Error(r))}},r}(k),st=/*#__PURE__*/function(e){function r(t,r){return void 0===r&&(r=13e3),e.call(this,t,r)||this}return t(r,e),r.prototype.validate=function(){try{var t=new URLSearchParams(window.location.search).get("hanko_token");return t?(window.history.replaceState(null,null,window.location.pathname),Promise.resolve(this.client.post("/token",{value:t})).then(function(t){if(!t.ok)throw new a})):Promise.resolve()}catch(t){return Promise.reject(t)}},r}(k);exports.ConfigClient=R,exports.ConflictError=u,exports.EmailAddressAlreadyExistsError=b,exports.EmailClient=it,exports.Hanko=function(t,e){void 0===e&&(e=13e3),this.api=void 0,this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.email=void 0,this.thirdParty=void 0,this.token=void 0,this.api=t,this.config=new R(t,e),this.user=new D(t,e),this.webauthn=new nt(t,e),this.password=new N(t,e),this.passcode=new I(t,e),this.email=new it(t,e),this.thirdParty=new ot(t,e),this.token=new st(t,e)},exports.HankoError=s,exports.InvalidPasscodeError=d,exports.InvalidPasswordError=l,exports.InvalidWebauthnCredentialError=f,exports.MaxNumOfEmailAddressesReachedError=P,exports.MaxNumOfPasscodeAttemptsReachedError=w,exports.NotFoundError=v,exports.PasscodeClient=I,exports.PasscodeExpiredError=p,exports.PasswordClient=N,exports.RequestTimeoutError=c,exports.TechnicalError=a,exports.ThirdPartyClient=ot,exports.ThirdPartyError=C,exports.TokenClient=st,exports.TooManyRequestsError=m,exports.UnauthorizedError=y,exports.UserClient=D,exports.UserVerificationError=g,exports.WebauthnClient=nt,exports.WebauthnRequestCancelledError=h,exports.WebauthnSupport=tt;
|
|
1
|
+
function e(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,r(e,t)}function t(e){return t=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},t(e)}function r(e,t){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},r(e,t)}function n(e,t,i){return n=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},n.apply(null,arguments)}function i(e){var o="function"==typeof Map?new Map:void 0;return i=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!==o){if(o.has(e))return o.get(e);o.set(e,i)}function i(){return n(e,arguments,t(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),r(i,e)},i(e)}function o(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var s=/*#__PURE__*/function(t){function r(e,n,i){var s;return(s=t.call(this,e)||this).code=void 0,s.cause=void 0,s.code=n,s.cause=i,Object.setPrototypeOf(o(s),r.prototype),s}return e(r,t),r}(/*#__PURE__*/i(Error)),a=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Technical error","somethingWentWrong",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),c=/*#__PURE__*/function(t){function r(e,n){var i;return i=t.call(this,"Conflict error","conflict",n)||this,Object.setPrototypeOf(o(i),r.prototype),i}return e(r,t),r}(s),u=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Request timed out error","requestTimeout",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),h=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Request cancelled error","requestCancelled",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),d=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Invalid password error","invalidPassword",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),l=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Invalid Passcode error","invalidPasscode",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),p=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),f=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Passcode expired error","passcodeExpired",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),v=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),w=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Not found error","notFound",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),m=/*#__PURE__*/function(t){function r(e,n){var i;return(i=t.call(this,"Too many requests error","tooManyRequests",n)||this).retryAfter=void 0,i.retryAfter=e,Object.setPrototypeOf(o(i),r.prototype),i}return e(r,t),r}(s),y=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Unauthorized error","unauthorized",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),g=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"User verification error","userVerification",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),E=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),S=/*#__PURE__*/function(t){function r(e){var n;return n=t.call(this,"The email address already exists","emailAddressAlreadyExistsError",e)||this,Object.setPrototypeOf(o(n),r.prototype),n}return e(r,t),r}(s),P=/*#__PURE__*/function(t){function r(e,n){var i;return i=t.call(this,"An error occurred during third party sign up/sign in",e,n)||this,Object.setPrototypeOf(o(i),r.prototype),i}return e(r,t),r}(s),b=/*#__PURE__*/function(){function e(e){this.key=void 0,this.ls=void 0,this.key=e,this.ls={}}var t=e.prototype;return t.read=function(){var e;try{var t=localStorage.getItem(this.key),r=decodeURIComponent(decodeURI(window.atob(t)));e=JSON.parse(r)}catch(e){return this.ls={},this}return this.ls=e,this},t.write=function(){var e=JSON.stringify(this.ls),t=window.btoa(encodeURI(encodeURIComponent(e)));return localStorage.setItem(this.key,t),this},e.timeToRemainingSeconds=function(e){return void 0===e&&(e=0),e-Math.floor(Date.now()/1e3)},e.remainingSecondsToTime=function(e){return void 0===e&&(e=0),Math.floor(Date.now()/1e3)+e},e}(),x=/*#__PURE__*/function(t){function r(){return t.call(this,"hanko_session")||this}e(r,t);var n=r.prototype;return n.read=function(){return t.prototype.read.call(this),this},n.getState=function(){var e;return(e=this.ls).session||(e.session={expiry:0,userID:"",authFlowCompleted:!1}),this.ls.session},n.getExpirationSeconds=function(){return b.timeToRemainingSeconds(this.getState().expiry)},n.setExpirationSeconds=function(e){return this.getState().expiry=b.remainingSecondsToTime(e),this},n.getUserID=function(){return this.getState().userID},n.setUserID=function(e){return this.getState().userID=e,this},n.getAuthFlowCompleted=function(){return this.getState().authFlowCompleted},n.setAuthFlowCompleted=function(e){return this.getState().authFlowCompleted=e,this},n.reset=function(){var e=this.getState();return delete e.expiry,delete e.userID,this},r}(b),C=/*#__PURE__*/function(t){function r(){return t.call(this,"hanko")||this}return e(r,t),r.prototype.getUserState=function(e){var t;return(t=this.ls).users||(t.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,e)||(this.ls.users[e]={}),this.ls.users[e]},r}(b),k=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getState=function(e){var r;return(r=t.prototype.getUserState.call(this,e)).passcode||(r.passcode={})},n.read=function(){return t.prototype.read.call(this),this},n.getActiveID=function(e){return this.getState(e).id},n.setActiveID=function(e,t){return this.getState(e).id=t,this},n.getEmailID=function(e){return this.getState(e).emailID},n.setEmailID=function(e,t){return this.getState(e).emailID=t,this},n.reset=function(e){var t=this.getState(e);return delete t.id,delete t.ttl,delete t.resendAfter,delete t.emailID,this},n.getTTL=function(e){return b.timeToRemainingSeconds(this.getState(e).ttl)},n.setTTL=function(e,t){return this.getState(e).ttl=b.remainingSecondsToTime(t),this},n.getResendAfter=function(e){return b.timeToRemainingSeconds(this.getState(e).resendAfter)},n.setResendAfter=function(e,t){return this.getState(e).resendAfter=b.remainingSecondsToTime(t),this},r}(C),_="hanko-session-created",A="hanko-session-expired",O="hanko-user-logged-out",T="hanko-user-deleted",j="hanko-auth-flow-completed",R=/*#__PURE__*/function(t){function r(e,r){return t.call(this,e,{detail:r})||this}return e(r,t),r}(/*#__PURE__*/i(CustomEvent)),I=/*#__PURE__*/function(){function e(){this._dispatchEvent=document.dispatchEvent.bind(document),this._sessionState=new x}var t=e.prototype;return t.dispatch=function(e,t){this._dispatchEvent(new R(e,t))},t.dispatchSessionCreatedEvent=function(e){this.dispatch(_,e)},t.dispatchSessionExpiredEvent=function(){this.dispatch(A,null)},t.dispatchUserLoggedOutEvent=function(){this.dispatch(O,null)},t.dispatchUserDeletedEvent=function(){this.dispatch(T,null)},t.dispatchAuthFlowCompletedEvent=function(e){this._sessionState.read().setAuthFlowCompleted(!0).write(),this.dispatch(j,e)},e}();function D(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)e[n]=r[n]}return e}var L=function e(t,r){function n(e,n,i){if("undefined"!=typeof document){"number"==typeof(i=D({},r,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(n,e)+o}}return Object.create({set:n,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],n={},i=0;i<r.length;i++){var o=r[i].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(n[a]=t.read(s,a),e===a)break}catch(e){}}return e?n[e]:n}},remove:function(e,t){n(e,"",D({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,D({},this.attributes,t))},withConverter:function(t){return e(D({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(r)},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:"/"}),U=/*#__PURE__*/function(){function e(){this.authCookieName="hanko"}var t=e.prototype;return t.getAuthCookie=function(){return L.get(this.authCookieName)},t.setAuthCookie=function(e,t){void 0===t&&(t=!0),L.set(this.authCookieName,e,{secure:t})},t.removeAuthCookie=function(){L.remove(this.authCookieName)},e}(),N=/*#__PURE__*/function(){function e(e){this._xhr=void 0,this._xhr=e}return e.prototype.getResponseHeader=function(e){return this._xhr.getResponseHeader(e)},e}(),H=/*#__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 N(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}(),W=/*#__PURE__*/function(){function e(e,t){void 0===t&&(t=13e3),this.timeout=void 0,this.api=void 0,this.sessionState=void 0,this.passcodeState=void 0,this.dispatcher=void 0,this.cookie=void 0,this.api=e,this.timeout=t,this.sessionState=new x,this.passcodeState=new k,this.dispatcher=new I,this.cookie=new U}var t=e.prototype;return t._fetch=function(e,t,r){void 0===r&&(r=new XMLHttpRequest);var n=this.api+e,i=this.timeout,o=this.cookie.getAuthCookie();return new Promise(function(e,s){r.open(t.method,n,!0),r.setRequestHeader("Accept","application/json"),r.setRequestHeader("Content-Type","application/json"),o&&r.setRequestHeader("Authorization","Bearer "+o),r.timeout=i,r.withCredentials=!0,r.onload=function(){var t=new H(r);e(t)},r.onerror=function(){s(new a)},r.ontimeout=function(){s(new u)},r.send(t.body?t.body.toString():null)})},t.processResponseHeadersOnLogin=function(e,t){var r="",n=0;if(t.xhr.getAllResponseHeaders().split("\r\n").forEach(function(e){var i=e.toLowerCase();i.startsWith("x-auth-token")?r=t.headers.getResponseHeader("X-Auth-Token"):i.startsWith("x-session-lifetime")&&(n=parseInt(t.headers.getResponseHeader("X-Session-Lifetime"),10))}),r){var i=!!this.api.match("^https://");this.cookie.setAuthCookie(r,i)}this.passcodeState.read().reset(e).write(),n>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(n),this.sessionState.setUserID(e),this.sessionState.setAuthFlowCompleted(!1),this.sessionState.write(),this.dispatcher.dispatchSessionCreatedEvent({jwt:r,userID:e,expirationSeconds:n}))},t.get=function(e){return this._fetch(e,{method:"GET"})},t.post=function(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})},t.put=function(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})},t.patch=function(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})},t.delete=function(e){return this._fetch(e,{method:"DELETE"})},e}(),F=function(e,t){void 0===t&&(t=13e3),this.client=void 0,this.client=new W(e,t)},q=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}return e(r,t),r.prototype.get=function(){try{return Promise.resolve(this.client.get("/.well-known/config")).then(function(e){if(!e.ok)throw new a;return e.json()})}catch(e){return Promise.reject(e)}},r}(F),M=/*#__PURE__*/function(t){function r(e,r){var n;return void 0===r&&(r=13e3),(n=t.call(this,e,r)||this).state=void 0,n.state=new k,n}e(r,t);var n=r.prototype;return n.initialize=function(e,t,r){try{var n=this;n.state.read();var i=n.state.getTTL(e),o=n.state.getActiveID(e),s=n.state.getEmailID(e),c=n.state.getResendAfter(e);if(c>0)throw new m(c);if(!r&&i>0&&t===s)return Promise.resolve({id:o,ttl:i});var u={user_id:e};return t&&(u.email_id=t),Promise.resolve(n.client.post("/passcode/login/initialize",u)).then(function(r){if(429===r.status)throw c=r.parseNumericHeader("Retry-After"),n.state.setResendAfter(e,c).write(),new m(c);if(!r.ok)throw new a;var i=r.json();return n.state.setActiveID(e,i.id).setTTL(e,i.ttl),t&&n.state.setEmailID(e,t),n.state.write(),i})}catch(e){return Promise.reject(e)}},n.finalize=function(e,t){try{var r=this,n=r.state.read().getActiveID(e);if(r.state.getTTL(e)<=0)throw new f;return Promise.resolve(r.client.post("/passcode/login/finalize",{id:n,code:t})).then(function(t){if(401===t.status)throw new l;if(410===t.status)throw r.state.reset(e).write(),new v;if(!t.ok)throw new a;r.client.processResponseHeadersOnLogin(e,t)})}catch(e){return Promise.reject(e)}},n.getTTL=function(e){return this.state.read().getTTL(e)},n.getResendAfter=function(e){return this.state.read().getResendAfter(e)},r}(F),K=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getState=function(e){var r;return(r=t.prototype.getUserState.call(this,e)).password||(r.password={})},n.read=function(){return t.prototype.read.call(this),this},n.getRetryAfter=function(e){return b.timeToRemainingSeconds(this.getState(e).retryAfter)},n.setRetryAfter=function(e,t){return this.getState(e).retryAfter=b.remainingSecondsToTime(t),this},r}(C),z=/*#__PURE__*/function(t){function r(e,r){var n;return void 0===r&&(r=13e3),(n=t.call(this,e,r)||this).passwordState=void 0,n.passcodeState=void 0,n.passwordState=new K,n.passcodeState=new k,n}e(r,t);var n=r.prototype;return n.login=function(e,t){try{var r=this;return Promise.resolve(r.client.post("/password/login",{user_id:e,password:t})).then(function(t){if(401===t.status)throw new d;if(429===t.status){var n=t.parseNumericHeader("Retry-After");throw r.passwordState.read().setRetryAfter(e,n).write(),new m(n)}if(!t.ok)throw new a;r.client.processResponseHeadersOnLogin(e,t)})}catch(e){return Promise.reject(e)}},n.update=function(e,t){try{var r=this;return Promise.resolve(r.client.put("/password",{user_id:e,password:t})).then(function(e){if(401===e.status)throw r.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a})}catch(e){return Promise.reject(e)}},n.getRetryAfter=function(e){return this.passwordState.read().getRetryAfter(e)},r}(F),J=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getInfo=function(e){try{return Promise.resolve(this.client.post("/user",{email:e})).then(function(e){if(404===e.status)throw new w;if(!e.ok)throw new a;return e.json()})}catch(e){return Promise.reject(e)}},n.create=function(e){try{var t=this;return Promise.resolve(t.client.post("/users",{email:e})).then(function(e){if(409===e.status)throw new c;if(!e.ok)throw new a;var r=e.json();return r&&r.user_id&&t.client.processResponseHeadersOnLogin(r.user_id,e),r})}catch(e){return Promise.reject(e)}},n.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 y;if(!t.ok)throw new a;var r=t.json();return Promise.resolve(e.client.get("/users/"+r.id)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a;return t.json()})})}catch(e){return Promise.reject(e)}},n.delete=function(){try{var e=this;return Promise.resolve(e.client.delete("/user")).then(function(t){if(t.ok)return e.client.cookie.removeAuthCookie(),e.client.sessionState.reset().write(),void e.client.dispatcher.dispatchUserDeletedEvent();if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;throw new a})}catch(e){return Promise.reject(e)}},n.logout=function(){try{var e=this;return Promise.resolve(e.client.post("/logout")).then(function(t){if(e.client.cookie.removeAuthCookie(),e.client.sessionState.reset().write(),e.client.dispatcher.dispatchUserLoggedOutEvent(),401===t.status);else if(!t.ok)throw new a})}catch(e){return Promise.reject(e)}},r}(F);function B(e){const t="==".slice(0,(4-e.length%4)%4),r=e.replace(/-/g,"+").replace(/_/g,"/")+t,n=atob(r),i=new ArrayBuffer(n.length),o=new Uint8Array(i);for(let e=0;e<n.length;e++)o[e]=n.charCodeAt(e);return i}function V(e){const t=new Uint8Array(e);let r="";for(const e of t)r+=String.fromCharCode(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var X="copy",G="convert";function $(e,t,r){if(t===X)return r;if(t===G)return e(r);if(t instanceof Array)return r.map(r=>$(e,t[0],r));if(t instanceof Object){const n={};for(const[i,o]of Object.entries(t)){if(o.derive){const e=o.derive(r);void 0!==e&&(r[i]=e)}if(i in r)n[i]=null!=r[i]?$(e,o.schema,r[i]):null;else if(o.required)throw new Error(`Missing key: ${i}`)}return n}}function Q(e,t){return{required:!0,schema:e,derive:t}}function Y(e){return{required:!0,schema:e}}function Z(e){return{required:!1,schema:e}}var ee={type:Y(X),id:Y(G),transports:Z(X)},te={appid:Z(X),appidExclude:Z(X),credProps:Z(X)},re={appid:Z(X),appidExclude:Z(X),credProps:Z(X)},ne={publicKey:Y({rp:Y(X),user:Y({id:Y(G),name:Y(X),displayName:Y(X)}),challenge:Y(G),pubKeyCredParams:Y(X),timeout:Z(X),excludeCredentials:Z([ee]),authenticatorSelection:Z(X),attestation:Z(X),extensions:Z(te)}),signal:Z(X)},ie={type:Y(X),id:Y(X),rawId:Y(G),authenticatorAttachment:Z(X),response:Y({clientDataJSON:Y(G),attestationObject:Y(G),transports:Q(X,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:Q(re,e=>e.getClientExtensionResults())},oe={mediation:Z(X),publicKey:Y({challenge:Y(G),timeout:Z(X),rpId:Z(X),allowCredentials:Z([ee]),userVerification:Z(X),extensions:Z(te)}),signal:Z(X)},se={type:Y(X),id:Y(X),rawId:Y(G),authenticatorAttachment:Z(X),response:Y({clientDataJSON:Y(G),authenticatorData:Y(G),signature:Y(G),userHandle:Y(G)}),clientExtensionResults:Q(re,e=>e.getClientExtensionResults())};async function ae(e){const t=await navigator.credentials.create(function(e){return $(B,ne,e)}(e));return function(e){return $(V,ie,e)}(t)}async function ce(e){const t=await navigator.credentials.get(function(e){return $(B,oe,e)}(e));return function(e){return $(V,se,e)}(t)}var ue=/*#__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}(),he=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.getState=function(e){var r;return(r=t.prototype.getUserState.call(this,e)).webauthn||(r.webauthn={})},n.read=function(){return t.prototype.read.call(this),this},n.getCredentials=function(e){var t;return(t=this.getState(e)).credentials||(t.credentials=[])},n.addCredential=function(e,t){return this.getCredentials(e).push(t),this},n.matchCredentials=function(e,t){return this.getCredentials(e).filter(function(e){return t.find(function(t){return t.id===e})}).map(function(e){return{id:e}})},r}(C);function de(e,t){try{var r=e()}catch(e){return t(e)}return r&&r.then?r.then(void 0,t):r}var le=/*#__PURE__*/function(t){function r(e,r){var n;return void 0===r&&(r=13e3),(n=t.call(this,e,r)||this).webauthnState=void 0,n.passcodeState=void 0,n.controller=void 0,n._getCredential=ce,n._createCredential=ae,n.webauthnState=new he,n.passcodeState=new k,n}e(r,t);var n=r.prototype;return n.login=function(e,t){try{var r=this;return Promise.resolve(r.client.post("/webauthn/login/initialize",{user_id:e})).then(function(e){var n;function i(e){return n?e:Promise.resolve(r.client.post("/webauthn/login/finalize",o)).then(function(e){if(400===e.status||401===e.status)throw new p;if(!e.ok)throw new a;var t=e.json();return r.webauthnState.read().addCredential(t.user_id,t.credential_id).write(),r.client.processResponseHeadersOnLogin(t.user_id,e),t})}if(!e.ok)throw new a;var o,s=e.json();s.signal=r._createAbortSignal(),t&&(s.mediation="conditional");var c=de(function(){return Promise.resolve(r._getCredential(s)).then(function(e){o=e})},function(e){throw new h(e)});return c&&c.then?c.then(i):i(c)})}catch(e){return Promise.reject(e)}},n.register=function(){try{var e=this;return Promise.resolve(e.client.post("/webauthn/registration/initialize")).then(function(t){function r(t){return n.transports=n.response.transports,Promise.resolve(e.client.post("/webauthn/registration/finalize",n)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(422===t.status)throw new g;if(!t.ok)throw new a;var r=t.json();e.webauthnState.read().addCredential(r.user_id,r.credential_id).write()})}if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a;var n,i=t.json();i.signal=e._createAbortSignal();var o=de(function(){return Promise.resolve(e._createCredential(i)).then(function(e){n=e})},function(e){throw new h(e)});return o&&o.then?o.then(r):r()})}catch(e){return Promise.reject(e)}},n.listCredentials=function(){try{var e=this;return Promise.resolve(e.client.get("/webauthn/credentials")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!t.ok)throw new a;return t.json()})}catch(e){return Promise.reject(e)}},n.updateCredential=function(e,t){try{var r=this;return Promise.resolve(r.client.patch("/webauthn/credentials/"+e,{name:t})).then(function(e){if(401===e.status)throw r.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a})}catch(e){return Promise.reject(e)}},n.deleteCredential=function(e){try{var t=this;return Promise.resolve(t.client.delete("/webauthn/credentials/"+e)).then(function(e){if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(!e.ok)throw new a})}catch(e){return Promise.reject(e)}},n.shouldRegister=function(e){try{var t=ue.supported();if(!e.webauthn_credentials||!e.webauthn_credentials.length)return Promise.resolve(t);var r=this.webauthnState.read().matchCredentials(e.id,e.webauthn_credentials);return Promise.resolve(t&&!r.length)}catch(e){return Promise.reject(e)}},n._createAbortSignal=function(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal},r}(F),pe=/*#__PURE__*/function(t){function r(){return t.apply(this,arguments)||this}e(r,t);var n=r.prototype;return n.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 y;if(!t.ok)throw new a;return t.json()})}catch(e){return Promise.reject(e)}},n.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 S;if(401===e.status)throw t.client.dispatcher.dispatchSessionExpiredEvent(),new y;if(409===e.status)throw new E;throw new a})}catch(e){return Promise.reject(e)}},n.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 y;if(!e.ok)throw new a})}catch(e){return Promise.reject(e)}},n.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 y;if(!e.ok)throw new a})}catch(e){return Promise.reject(e)}},r}(F),fe=/*#__PURE__*/function(t){function r(e,r){return void 0===r&&(r=13e3),t.call(this,e,r)||this}e(r,t);var n=r.prototype;return n.auth=function(e,t){try{var r=new URL("/thirdparty/auth",this.client.api);if(!e)throw new P("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new P("somethingWentWrong",new Error("redirectTo missing from request"));return r.searchParams.append("provider",e),r.searchParams.append("redirect_to",t),window.location.assign(r.href),Promise.resolve()}catch(e){return Promise.reject(e)}},n.getError=function(){var e=new URLSearchParams(window.location.search),t=e.get("error"),r=e.get("error_description");if(t){var n="";switch(t){case"access_denied":n="thirdPartyAccessDenied";break;case"user_conflict":n="emailAddressAlreadyExistsError";break;case"multiple_accounts":n="thirdPartyMultipleAccounts";break;case"unverified_email":n="thirdPartyUnverifiedEmail";break;case"email_maxnum":n="maxNumOfEmailAddressesReached";break;default:n="somethingWentWrong"}return new P(n,new Error(r))}},r}(F),ve=/*#__PURE__*/function(t){function r(e,r){return void 0===r&&(r=13e3),t.call(this,e,r)||this}return e(r,t),r.prototype.validate=function(){try{var e=this,t=new URLSearchParams(window.location.search).get("hanko_token");return t?(window.history.replaceState(null,null,window.location.pathname),Promise.resolve(e.client.post("/token",{value:t})).then(function(t){if(!t.ok)throw new a;var r=t.json();e.client.processResponseHeadersOnLogin(r.user_id,t)})):Promise.resolve()}catch(e){return Promise.reject(e)}},r}(F),we=/*#__PURE__*/function(){function e(){}return e.throttle=function(e,t,r){void 0===r&&(r={});var n,i,o,s=r.leading,a=void 0===s||s,c=r.trailing,u=void 0===c||c,h=0,d=function(){h=!1===a?0:Date.now(),o=null,e.apply(n,i)};return function(){var r=Date.now();h||!1!==a||(h=r);var s=t-(r-h);n=this,i=[].slice.call(arguments),s<=0||s>t?(o&&(window.clearTimeout(o),o=null),h=r,e.apply(n,i)):o||!1===u||(o=window.setTimeout(d,s))}},e}(),me=/*#__PURE__*/function(){function e(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=we.throttle}var t=e.prototype;return t.wrapCallback=function(e,t){var r=function(t){e(t.detail)};return t?this._throttle(r,this.throttleLimit,{leading:!0,trailing:!1}):r},t.addEventListenerWithType=function(e){var t=this,r=e.type,n=e.once,i=void 0!==n&&n,o=e.throttle,s=this.wrapCallback(e.callback,void 0!==o&&o);return this._addEventListener(r,s,{once:i}),function(){return t._removeEventListener(r,s)}},e.mapAddEventListenerParams=function(e,t,r){return{type:e,callback:t.callback,once:t.once,throttle:r}},t.addEventListener=function(t,r,n){return this.addEventListenerWithType(e.mapAddEventListenerParams(t,r,n))},t.onSessionCreated=function(e,t){return this.addEventListener(_,{callback:e,once:t},!0)},t.onSessionExpired=function(e,t){return this.addEventListener(A,{callback:e,once:t},!0)},t.onUserLoggedOut=function(e,t){return this.addEventListener(O,{callback:e,once:t})},t.onUserDeleted=function(e,t){return this.addEventListener(T,{callback:e,once:t})},t.onAuthFlowCompleted=function(e,t){return this.addEventListener(j,{callback:e,once:t})},e}(),ye=/*#__PURE__*/function(){function e(){this._tasks=[]}var t=e.prototype;return t.removeTask=function(e){window.clearTimeout(e.timeoutID),this._tasks=this._tasks.filter(function(t){return t!==e})},t.removeTasksWithType=function(e){var t=this;this._tasks.filter(function(t){return t.type===e}).forEach(function(e){return t.removeTask(e)})},t.scheduleTask=function(e,t,r){var n=this,i={timeoutID:window.setTimeout(function(){t(),n.removeTask(i)},1e3*r),type:e,func:t};this._tasks.push(i)},e}(),ge=/*#__PURE__*/function(){function e(){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new x,this._cookie=new U}var t=e.prototype;return t.get=function(){var t=this._get();return e.validate(t)?t:null},t.isValid=function(){var t=this._get();return e.validate(t)},t._get=function(){return this._sessionState.read(),{userID:this._sessionState.getUserID(),expirationSeconds:this._sessionState.getExpirationSeconds(),jwt:this._cookie.getAuthCookie()}},t.isAuthFlowCompleted=function(){return this._sessionState.read(),this._sessionState.getAuthFlowCompleted()},e.validate=function(e){var t;return!!(e.expirationSeconds>0&&null!=(t=e.userID)&&t.length)},e}(),Ee=/*#__PURE__*/function(t){function r(){var e;return(e=t.call(this)||this)._listener=new me,e._scheduler=new ye,e._session=new ge,e.scheduleSessionExpiredEvent=function(t){e._scheduler.removeTasksWithType(A),e._scheduler.scheduleTask(A,function(){return e.dispatchSessionExpiredEvent()},t.expirationSeconds)},e.cancelSessionExpiredEvent=function(){e._scheduler.removeTasksWithType(A)},e.handleStorageEvent=function(t){if("hanko_session"===t.key){var r=e._session.get();r?e._session.isAuthFlowCompleted()?e.dispatchAuthFlowCompletedEvent({userID:r.userID}):e.dispatchSessionCreatedEvent(r):e.dispatchSessionExpiredEvent()}},e.listenEventDependencies(),e}return e(r,t),r.prototype.listenEventDependencies=function(){this._listener.onSessionCreated(this.scheduleSessionExpiredEvent),this._listener.onSessionExpired(this.cancelSessionExpiredEvent),this._listener.onUserDeleted(this.cancelSessionExpiredEvent),this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent),window.addEventListener("storage",this.handleStorageEvent);var e=this._session.get();e&&this.scheduleSessionExpiredEvent(e)},r}(I),Se=/*#__PURE__*/function(t){function r(e,r){var n;return void 0===r&&(r=13e3),(n=t.call(this)||this).api=void 0,n.config=void 0,n.user=void 0,n.webauthn=void 0,n.password=void 0,n.passcode=void 0,n.email=void 0,n.thirdParty=void 0,n.token=void 0,n.relay=void 0,n.session=void 0,n.api=e,n.config=new q(e,r),n.user=new J(e,r),n.webauthn=new le(e,r),n.password=new z(e,r),n.passcode=new M(e,r),n.email=new pe(e,r),n.thirdParty=new fe(e,r),n.token=new ve(e,r),n.relay=new Ee,n.session=new ge,n}return e(r,t),r}(me);exports.ConfigClient=q,exports.ConflictError=c,exports.CustomEventWithDetail=R,exports.EmailAddressAlreadyExistsError=S,exports.EmailClient=pe,exports.Hanko=Se,exports.HankoError=s,exports.InvalidPasscodeError=l,exports.InvalidPasswordError=d,exports.InvalidWebauthnCredentialError=p,exports.MaxNumOfEmailAddressesReachedError=E,exports.MaxNumOfPasscodeAttemptsReachedError=v,exports.NotFoundError=w,exports.PasscodeClient=M,exports.PasscodeExpiredError=f,exports.PasswordClient=z,exports.RequestTimeoutError=u,exports.TechnicalError=a,exports.ThirdPartyClient=fe,exports.ThirdPartyError=P,exports.TokenClient=ve,exports.TooManyRequestsError=m,exports.UnauthorizedError=y,exports.UserClient=J,exports.UserVerificationError=g,exports.WebauthnClient=le,exports.WebauthnRequestCancelledError=h,exports.WebauthnSupport=ue,exports.authFlowCompletedType=j,exports.sessionCreatedType=_,exports.sessionExpiredType=A,exports.userDeletedType=T,exports.userLoggedOutType=O;
|
|
2
2
|
//# sourceMappingURL=sdk.cjs.map
|