@teamhanko/hanko-frontend-sdk 0.0.9-alpha → 0.1.1-alpha

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 CHANGED
@@ -67,6 +67,8 @@ To see the latest documentation, please click [here](https://docs.hanko.io/jsdoc
67
67
  - `Credential`
68
68
  - `UserInfo`
69
69
  - `User`
70
+ - `Email`
71
+ - `Emails`
70
72
  - `Passcode`
71
73
 
72
74
  ### Errors
package/dist/Hanko.d.ts CHANGED
@@ -3,6 +3,7 @@ import { PasscodeClient } from "./lib/client/PasscodeClient";
3
3
  import { PasswordClient } from "./lib/client/PasswordClient";
4
4
  import { UserClient } from "./lib/client/UserClient";
5
5
  import { WebauthnClient } from "./lib/client/WebauthnClient";
6
+ import { EmailClient } from "./lib/client/EmailClient";
6
7
  /**
7
8
  * A class that bundles all available SDK functions.
8
9
  *
@@ -15,6 +16,7 @@ declare class Hanko {
15
16
  webauthn: WebauthnClient;
16
17
  password: PasswordClient;
17
18
  passcode: PasscodeClient;
19
+ email: EmailClient;
18
20
  constructor(api: string, timeout?: number);
19
21
  }
20
22
  export { Hanko };
package/dist/index.d.ts CHANGED
@@ -5,10 +5,11 @@ import { PasscodeClient } from "./lib/client/PasscodeClient";
5
5
  import { PasswordClient } from "./lib/client/PasswordClient";
6
6
  import { UserClient } from "./lib/client/UserClient";
7
7
  import { WebauthnClient } from "./lib/client/WebauthnClient";
8
- export { ConfigClient, UserClient, WebauthnClient, PasswordClient, PasscodeClient, };
8
+ import { EmailClient } from "./lib/client/EmailClient";
9
+ export { ConfigClient, UserClient, WebauthnClient, PasswordClient, PasscodeClient, EmailClient, };
9
10
  import { WebauthnSupport } from "./lib/WebauthnSupport";
10
11
  export { WebauthnSupport };
11
- import { PasswordConfig, Config, WebauthnFinalized, Credential, UserInfo, User, Passcode } from "./lib/Dto";
12
- export type { PasswordConfig, Config, WebauthnFinalized, Credential, UserInfo, User, Passcode, };
13
- import { HankoError, TechnicalError, ConflictError, RequestTimeoutError, WebauthnRequestCancelledError, InvalidPasswordError, InvalidPasscodeError, InvalidWebauthnCredentialError, PasscodeExpiredError, MaxNumOfPasscodeAttemptsReachedError, NotFoundError, TooManyRequestsError, UnauthorizedError, UserVerificationError } from "./lib/Errors";
14
- export { HankoError, TechnicalError, ConflictError, RequestTimeoutError, WebauthnRequestCancelledError, InvalidPasswordError, InvalidPasscodeError, InvalidWebauthnCredentialError, PasscodeExpiredError, MaxNumOfPasscodeAttemptsReachedError, NotFoundError, TooManyRequestsError, UnauthorizedError, UserVerificationError, };
12
+ import { PasswordConfig, Config, WebauthnFinalized, Credential, UserInfo, User, Email, Emails, WebauthnCredential, WebauthnCredentials, Passcode } from "./lib/Dto";
13
+ export type { PasswordConfig, Config, WebauthnFinalized, Credential, UserInfo, User, Email, Emails, WebauthnCredential, WebauthnCredentials, Passcode, };
14
+ import { HankoError, ConflictError, EmailAddressAlreadyExistsError, InvalidPasswordError, InvalidPasscodeError, InvalidWebauthnCredentialError, MaxNumOfEmailAddressesReachedError, MaxNumOfPasscodeAttemptsReachedError, NotFoundError, PasscodeExpiredError, RequestTimeoutError, TechnicalError, TooManyRequestsError, UnauthorizedError, UserVerificationError, WebauthnRequestCancelledError } from "./lib/Errors";
15
+ export { HankoError, ConflictError, EmailAddressAlreadyExistsError, InvalidPasswordError, InvalidPasscodeError, InvalidWebauthnCredentialError, MaxNumOfEmailAddressesReachedError, MaxNumOfPasscodeAttemptsReachedError, NotFoundError, PasscodeExpiredError, RequestTimeoutError, TechnicalError, TooManyRequestsError, UnauthorizedError, UserVerificationError, WebauthnRequestCancelledError, };
package/dist/lib/Dto.d.ts CHANGED
@@ -4,9 +4,22 @@ import { PublicKeyCredentialWithAttestationJSON } from "@github/webauthn-json";
4
4
  * @category SDK
5
5
  * @subcategory DTO
6
6
  * @property {boolean} enabled - Indicates passwords are enabled, so the API accepts login attempts using passwords.
7
+ * @property {number} min_password_length - The minimum length of a password. To be used for password validation.
7
8
  */
8
9
  interface PasswordConfig {
9
10
  enabled: boolean;
11
+ min_password_length: number;
12
+ }
13
+ /**
14
+ * @interface
15
+ * @category SDK
16
+ * @subcategory DTO
17
+ * @property {boolean} require_verification - Indicates that email addresses must be verified.
18
+ * @property {number} max_num_of_addresses - The maximum number of email addresses a user can have.
19
+ */
20
+ interface EmailConfig {
21
+ require_verification: boolean;
22
+ max_num_of_addresses: number;
10
23
  }
11
24
  /**
12
25
  * @interface
@@ -16,6 +29,7 @@ interface PasswordConfig {
16
29
  */
17
30
  interface Config {
18
31
  password: PasswordConfig;
32
+ emails: EmailConfig;
19
33
  }
20
34
  /**
21
35
  * @interface
@@ -34,11 +48,13 @@ interface WebauthnFinalized {
34
48
  * @subcategory DTO
35
49
  * @property {string} id - The UUID of the user.
36
50
  * @property {boolean} verified - Indicates whether the user's email address is verified.
51
+ * @property {string} email_id - The UUID of the email address.
37
52
  * @property {boolean} has_webauthn_credential - Indicates that the user has registered a WebAuthn credential in the past.
38
53
  */
39
54
  interface UserInfo {
40
55
  id: string;
41
56
  verified: boolean;
57
+ email_id: string;
42
58
  has_webauthn_credential: boolean;
43
59
  }
44
60
  /**
@@ -70,7 +86,7 @@ interface Credential {
70
86
  */
71
87
  interface User {
72
88
  id: string;
73
- email: string;
89
+ email_id: string;
74
90
  webauthn_credentials: Credential[];
75
91
  }
76
92
  /**
@@ -88,10 +104,70 @@ interface Passcode {
88
104
  * @interface
89
105
  * @category SDK
90
106
  * @subcategory DTO
91
- * @property {string[]} transports - A list of WebAuthn AuthenticatorTransport, e.g.: "usb", "internal",...
107
+ * @property {string[]} - Transports which may be used by the authenticator. E.g. "internal", "ble",...
108
+ */
109
+ interface WebauthnTransports extends Array<string> {
110
+ }
111
+ /**
112
+ * @interface
113
+ * @category SDK
114
+ * @subcategory DTO
115
+ * @property {WebauthnTransports} transports
92
116
  * @ignore
93
117
  */
94
118
  interface Attestation extends PublicKeyCredentialWithAttestationJSON {
95
- transports: string[];
119
+ transports: WebauthnTransports;
120
+ }
121
+ /**
122
+ * @interface
123
+ * @category SDK
124
+ * @subcategory DTO
125
+ * @property {string} id - The UUID of the email address.
126
+ * @property {string} address - The email address.
127
+ * @property {boolean} is_verified - Indicates whether the email address is verified.
128
+ * @property {boolean} is_primary - Indicates it's the primary email address.
129
+ */
130
+ interface Email {
131
+ id: string;
132
+ address: string;
133
+ is_verified: boolean;
134
+ is_primary: boolean;
135
+ }
136
+ /**
137
+ * @interface
138
+ * @category SDK
139
+ * @subcategory DTO
140
+ * @property {Email[]} - A list of emails assigned to the current user.
141
+ */
142
+ interface Emails extends Array<Email> {
143
+ }
144
+ /**
145
+ * @interface
146
+ * @category SDK
147
+ * @subcategory DTO
148
+ * @property {string} id - The credential id.
149
+ * @property {string=} name - The credential name.
150
+ * @property {string} public_key - The public key.
151
+ * @property {string} attestation_type - The attestation type.
152
+ * @property {string} aaguid - The AAGUID of the authenticator.
153
+ * @property {string} created_at - Time of credential creation.
154
+ * @property {WebauthnTransports} transports
155
+ */
156
+ interface WebauthnCredential {
157
+ id: string;
158
+ name?: string;
159
+ public_key: string;
160
+ attestation_type: string;
161
+ aaguid: string;
162
+ created_at: string;
163
+ transports: WebauthnTransports;
164
+ }
165
+ /**
166
+ * @interface
167
+ * @category SDK
168
+ * @subcategory DTO
169
+ * @property {WebauthnCredential[]} - A list of WebAuthn credential assigned to the current user.
170
+ */
171
+ interface WebauthnCredentials extends Array<WebauthnCredential> {
96
172
  }
97
- export type { PasswordConfig, Config, WebauthnFinalized, Credential, UserInfo, Me, User, Passcode, Attestation, };
173
+ export type { PasswordConfig, Config, WebauthnFinalized, Credential, UserInfo, Me, User, Email, Emails, Passcode, Attestation, WebauthnCredential, WebauthnCredentials, };
@@ -147,4 +147,25 @@ declare class UnauthorizedError extends HankoError {
147
147
  declare class UserVerificationError extends HankoError {
148
148
  constructor(cause?: Error);
149
149
  }
150
- export { HankoError, TechnicalError, ConflictError, RequestTimeoutError, WebauthnRequestCancelledError, InvalidPasswordError, InvalidPasscodeError, InvalidWebauthnCredentialError, PasscodeExpiredError, MaxNumOfPasscodeAttemptsReachedError, NotFoundError, TooManyRequestsError, UnauthorizedError, UserVerificationError };
150
+ /**
151
+ * A 'MaxNumOfEmailAddressesReachedError' occurs when the user tries to add a new email address while the maximum number
152
+ * of email addresses (see backend configuration) equals the number of email addresses already registered.
153
+ *
154
+ * @category SDK
155
+ * @subcategory Errors
156
+ * @extends {HankoError}
157
+ */
158
+ declare class MaxNumOfEmailAddressesReachedError extends HankoError {
159
+ constructor(cause?: Error);
160
+ }
161
+ /**
162
+ * An 'EmailAddressAlreadyExistsError' occurs when the user tries to add a new email address which already exists.
163
+ *
164
+ * @category SDK
165
+ * @subcategory Errors
166
+ * @extends {HankoError}
167
+ */
168
+ declare class EmailAddressAlreadyExistsError extends HankoError {
169
+ constructor(cause?: Error);
170
+ }
171
+ export { HankoError, TechnicalError, ConflictError, RequestTimeoutError, WebauthnRequestCancelledError, InvalidPasswordError, InvalidPasscodeError, InvalidWebauthnCredentialError, PasscodeExpiredError, MaxNumOfPasscodeAttemptsReachedError, NotFoundError, TooManyRequestsError, UnauthorizedError, UserVerificationError, MaxNumOfEmailAddressesReachedError, EmailAddressAlreadyExistsError, };
@@ -0,0 +1,58 @@
1
+ import { Client } from "./Client";
2
+ import { Email, Emails } from "../Dto";
3
+ /**
4
+ * Manages email addresses of the current user.
5
+ *
6
+ * @constructor
7
+ * @category SDK
8
+ * @subcategory Clients
9
+ * @extends {Client}
10
+ */
11
+ declare class EmailClient extends Client {
12
+ /**
13
+ * Returns a list of all email addresses assigned to the current user.
14
+ *
15
+ * @return {Promise<Emails>}
16
+ * @throws {UnauthorizedError}
17
+ * @throws {RequestTimeoutError}
18
+ * @throws {TechnicalError}
19
+ * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/listEmails
20
+ */
21
+ list(): Promise<Emails>;
22
+ /**
23
+ * Adds a new email address to the current user.
24
+ *
25
+ * @param {string} address - The email address to be added.
26
+ * @return {Promise<Email>}
27
+ * @throws {EmailAddressAlreadyExistsError}
28
+ * @throws {MaxNumOfEmailAddressesReachedError}
29
+ * @throws {UnauthorizedError}
30
+ * @throws {RequestTimeoutError}
31
+ * @throws {TechnicalError}
32
+ * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/createEmail
33
+ */
34
+ create(address: string): Promise<Email>;
35
+ /**
36
+ * Marks the specified email address as primary.
37
+ *
38
+ * @param {string} emailID - The ID of the email address to be updated
39
+ * @return {Promise<void>}
40
+ * @throws {UnauthorizedError}
41
+ * @throws {RequestTimeoutError}
42
+ * @throws {TechnicalError}
43
+ * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/setPrimaryEmail
44
+ */
45
+ setPrimaryEmail(emailID: string): Promise<void>;
46
+ /**
47
+ * Deletes the specified email address.
48
+ *
49
+ * @param {string} emailID - The ID of the email address to be deleted
50
+ * @return {Promise<void>}
51
+ * @throws {UnauthorizedError}
52
+ * @throws {RequestTimeoutError}
53
+ * @throws {TechnicalError}
54
+ * @see https://docs.hanko.io/api/public#tag/Email-Management/operation/deleteEmail
55
+ */
56
+ delete(emailID: string): Promise<void>;
57
+ }
58
+ export { EmailClient };
@@ -32,6 +32,7 @@ declare class Response {
32
32
  statusText: string;
33
33
  url: string;
34
34
  _decodedJSON: any;
35
+ private xhr;
35
36
  constructor(xhr: XMLHttpRequest);
36
37
  /**
37
38
  * Returns the JSON decoded response.
@@ -39,6 +40,12 @@ declare class Response {
39
40
  * @return {any}
40
41
  */
41
42
  json(): any;
43
+ /**
44
+ * Returns the value for Retry-After contained in the response header.
45
+ *
46
+ * @return {number}
47
+ */
48
+ parseRetryAfterHeader(): number;
42
49
  }
43
50
  /**
44
51
  * Internally used for communication with the Hanko API. It also handles authorization tokens to enable authorized
@@ -88,5 +95,24 @@ declare class HttpClient {
88
95
  * @throws {TechnicalError}
89
96
  */
90
97
  put(path: string, body?: any): Promise<Response>;
98
+ /**
99
+ * Performs a PATCH request.
100
+ *
101
+ * @param {string} path - The path to the requested resource.
102
+ * @param {any=} body - The request body.
103
+ * @return {Promise<Response>}
104
+ * @throws {RequestTimeoutError}
105
+ * @throws {TechnicalError}
106
+ */
107
+ patch(path: string, body?: any): Promise<Response>;
108
+ /**
109
+ * Performs a DELETE request.
110
+ *
111
+ * @param {string} path - The path to the requested resource.
112
+ * @return {Promise<Response>}
113
+ * @throws {RequestTimeoutError}
114
+ * @throws {TechnicalError}
115
+ */
116
+ delete(path: string): Promise<Response>;
91
117
  }
92
118
  export { Headers, Response, HttpClient };
@@ -16,13 +16,16 @@ declare class PasscodeClient extends Client {
16
16
  * Causes the API to send a new passcode to the user's email address.
17
17
  *
18
18
  * @param {string} userID - The UUID of the user.
19
+ * @param {string=} emailID - The UUID of the email address. If unspecified, the email will be sent to the primary email address.
20
+ * @param {boolean=} force - Indicates the passcode should be sent, even if there is another active passcode.
19
21
  * @return {Promise<Passcode>}
20
22
  * @throws {TooManyRequestsError}
21
23
  * @throws {RequestTimeoutError}
24
+ * @throws {UnauthorizedError}
22
25
  * @throws {TechnicalError}
23
26
  * @see https://docs.hanko.io/api/public#tag/Passcode/operation/passcodeInit
24
27
  */
25
- initialize(userID: string): Promise<Passcode>;
28
+ initialize(userID: string, emailID?: string, force?: boolean): Promise<Passcode>;
26
29
  /**
27
30
  * Validates the passcode obtained from the email.
28
31
  *
@@ -1,4 +1,5 @@
1
1
  import { PasswordState } from "../state/PasswordState";
2
+ import { PasscodeState } from "../state/PasscodeState";
2
3
  import { Client } from "./Client";
3
4
  /**
4
5
  * A class to handle passwords.
@@ -9,7 +10,8 @@ import { Client } from "./Client";
9
10
  * @extends {Client}
10
11
  */
11
12
  declare class PasswordClient extends Client {
12
- state: PasswordState;
13
+ passwordState: PasswordState;
14
+ passcodeState: PasscodeState;
13
15
  constructor(api: string, timeout?: number);
14
16
  /**
15
17
  * Logs in a user with a password.
@@ -1,7 +1,8 @@
1
- import { WebauthnState } from "../state/WebauthnState";
2
1
  import { create as createWebauthnCredential, get as getWebauthnCredential } from "@github/webauthn-json";
3
- import { User } from "../Dto";
4
2
  import { Client } from "./Client";
3
+ import { PasscodeState } from "../state/PasscodeState";
4
+ import { WebauthnState } from "../state/WebauthnState";
5
+ import { User, WebauthnCredentials } from "../Dto";
5
6
  /**
6
7
  * A class that handles WebAuthn authentication and registration.
7
8
  *
@@ -11,7 +12,8 @@ import { Client } from "./Client";
11
12
  * @extends {Client}
12
13
  */
13
14
  declare class WebauthnClient extends Client {
14
- state: WebauthnState;
15
+ webauthnState: WebauthnState;
16
+ passcodeState: PasscodeState;
15
17
  controller: AbortController;
16
18
  _getCredential: typeof getWebauthnCredential;
17
19
  _createCredential: typeof createWebauthnCredential;
@@ -46,6 +48,41 @@ declare class WebauthnClient extends Client {
46
48
  * @see https://www.w3.org/TR/webauthn-2/#sctn-registering-a-new-credential
47
49
  */
48
50
  register(): Promise<void>;
51
+ /**
52
+ * Returns a list of all WebAuthn credentials assigned to the current user.
53
+ *
54
+ * @return {Promise<WebauthnCredentials>}
55
+ * @throws {UnauthorizedError}
56
+ * @throws {RequestTimeoutError}
57
+ * @throws {TechnicalError}
58
+ * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/listCredentials
59
+ */
60
+ listCredentials(): Promise<WebauthnCredentials>;
61
+ /**
62
+ * Updates the WebAuthn credential.
63
+ *
64
+ * @param {string=} credentialID - The credential's UUID.
65
+ * @param {string} name - The new credential name.
66
+ * @return {Promise<void>}
67
+ * @throws {NotFoundError}
68
+ * @throws {UnauthorizedError}
69
+ * @throws {RequestTimeoutError}
70
+ * @throws {TechnicalError}
71
+ * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/updateCredential
72
+ */
73
+ updateCredential(credentialID: string, name: string): Promise<void>;
74
+ /**
75
+ * Deletes the WebAuthn credential.
76
+ *
77
+ * @param {string=} credentialID - The credential's UUID.
78
+ * @return {Promise<void>}
79
+ * @throws {NotFoundError}
80
+ * @throws {UnauthorizedError}
81
+ * @throws {RequestTimeoutError}
82
+ * @throws {TechnicalError}
83
+ * @see https://docs.hanko.io/api/public#tag/WebAuthn/operation/deleteCredential
84
+ */
85
+ deleteCredential(credentialID: string): Promise<void>;
49
86
  /**
50
87
  * Determines whether a credential registration ceremony should be performed. Returns 'true' when WebAuthn
51
88
  * is supported and the user's credentials do not intersect with the credentials already known on the
@@ -6,11 +6,13 @@ import { UserState } from "./UserState";
6
6
  * @property {string=} id - The UUID of the active passcode.
7
7
  * @property {number=} ttl - Timestamp until when the passcode is valid in seconds (since January 1, 1970 00:00:00 UTC).
8
8
  * @property {number=} resendAfter - Seconds until a passcode can be resent.
9
+ * @property {emailID=} emailID - The email address ID.
9
10
  */
10
11
  export interface LocalStoragePasscode {
11
12
  id?: string;
12
13
  ttl?: number;
13
14
  resendAfter?: number;
15
+ emailID?: string;
14
16
  }
15
17
  /**
16
18
  * A class that manages passcodes via local storage.
@@ -50,6 +52,21 @@ declare class PasscodeState extends UserState {
50
52
  * @return {PasscodeState}
51
53
  */
52
54
  setActiveID(userID: string, passcodeID: string): PasscodeState;
55
+ /**
56
+ * Gets the UUID of the email address.
57
+ *
58
+ * @param {string} userID - The UUID of the user.
59
+ * @return {string}
60
+ */
61
+ getEmailID(userID: string): string;
62
+ /**
63
+ * Sets the UUID of the email address.
64
+ *
65
+ * @param {string} userID - The UUID of the user.
66
+ * @param {string} emailID - The UUID of the email address.
67
+ * @return {PasscodeState}
68
+ */
69
+ setEmailID(userID: string, emailID: string): PasscodeState;
53
70
  /**
54
71
  * Removes the active passcode.
55
72
  *
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(){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}}function o(t,e,i){return o=n()?Reflect.construct.bind():function(t,e,n){var o=[null];o.push.apply(o,e);var i=new(Function.bind.apply(t,o));return n&&r(i,n.prototype),i},o.apply(null,arguments)}function i(t){var n="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!==n){if(n.has(t))return n.get(t);n.set(t,i)}function i(){return o(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 s(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var a=/*#__PURE__*/function(e){function r(t,n,o){var i;return(i=e.call(this,t)||this).code=void 0,i.cause=void 0,i.code=n,i.cause=o,Object.setPrototypeOf(s(i),r.prototype),i}return t(r,e),r}(/*#__PURE__*/i(Error)),c=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),u=/*#__PURE__*/function(e){function r(t,n){var o;return o=e.call(this,"Conflict error","conflict",n)||this,Object.setPrototypeOf(s(o),r.prototype),o}return t(r,e),r}(a),l=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),f=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),d=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),p=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),h=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),v=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),y=/*#__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(s(n),r.prototype),n}return t(r,e),r}(a),w=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),g=/*#__PURE__*/function(e){function r(t,n){var o;return(o=e.call(this,"Too many requests error","tooManyRequests",n)||this).retryAfter=void 0,o.retryAfter=t,Object.setPrototypeOf(s(o),r.prototype),o}return t(r,e),r}(a),m=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),b=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a);function P(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 C=function t(e,r){function n(t,n,o){if("undefined"!=typeof document){"number"==typeof(o=P({},r,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in o)o[s]&&(i+="; "+s,!0!==o[s]&&(i+="="+o[s].split(";")[0]));return document.cookie=t+"="+e.write(n,t)+i}}return Object.create({set:n,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var r=document.cookie?document.cookie.split("; "):[],n={},o=0;o<r.length;o++){var i=r[o].split("="),s=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(n[a]=e.read(s,a),t===a)break}catch(t){}}return t?n[t]:n}},remove:function(t,e){n(t,"",P({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,P({},this.attributes,e))},withConverter:function(e){return t(P({},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:"/"}),O=/*#__PURE__*/function(){function t(t){this._xhr=void 0,this._xhr=t}return t.prototype.get=function(t){return this._xhr.getResponseHeader(t)},t}(),j=/*#__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.headers=new O(t),this.ok=t.status>=200&&t.status<=299,this.status=t.status,this.statusText=t.statusText,this.url=t.responseURL,this._decodedJSON=JSON.parse(t.response)}return t.prototype.json=function(){return this._decodedJSON},t}(),A=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e=13e3),this.timeout=void 0,this.api=void 0,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.api,o=n+t,i=this.timeout,s="hanko",a=C.get(s);return new Promise(function(t,u){r.open(e.method,o,!0),r.setRequestHeader("Accept","application/json"),r.setRequestHeader("Content-Type","application/json"),a&&r.setRequestHeader("Authorization","Bearer "+a),r.timeout=i,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");if(e){var o=!!n.match("^https://");C.set(s,e,{secure:o})}}t(new j(r))},r.onerror=function(){u(new c)},r.ontimeout=function(){u(new l)},r.send(e.body?e.body.toString():null)})},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)})},t}(),x=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new A(t,e)},S=/*#__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 c;return t.json()})}catch(t){return Promise.reject(t)}},r}(x),R=/*#__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}(),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}(R),_=/*#__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.reset=function(t){var e=this.getState(t);return delete e.id,delete e.ttl,delete e.resendAfter,this},n.getTTL=function(t){return R.timeToRemainingSeconds(this.getState(t).ttl)},n.setTTL=function(t,e){return this.getState(t).ttl=R.remainingSecondsToTime(e),this},n.getResendAfter=function(t){return R.timeToRemainingSeconds(this.getState(t).resendAfter)},n.setResendAfter=function(t,e){return this.getState(t).resendAfter=R.remainingSecondsToTime(e),this},r}(T),k=/*#__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 _,n}t(r,e);var n=r.prototype;return n.initialize=function(t){try{var e=this;return Promise.resolve(e.client.post("/passcode/login/initialize",{user_id:t})).then(function(r){if(429===r.status){var n=parseInt(r.headers.get("X-Retry-After")||"0",10);throw e.state.read().setResendAfter(t,n).write(),new g(n)}if(!r.ok)throw new c;var o=r.json();return e.state.read().setActiveID(t,o.id).setTTL(t,o.ttl).write(),o})}catch(t){return Promise.reject(t)}},n.finalize=function(t,e){try{var r=this,n=r.state.read().getActiveID(t);return Promise.resolve(r.client.post("/passcode/login/finalize",{id:n,code:e})).then(function(e){if(401===e.status)throw new p;if(410===e.status)throw r.state.reset(t).write(),new y;if(!e.ok)throw new c;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}(x),E=/*#__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 R.timeToRemainingSeconds(this.getState(t).retryAfter)},n.setRetryAfter=function(t,e){return this.getState(t).retryAfter=R.remainingSecondsToTime(e),this},r}(T),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 E,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 d;if(429===e.status){var n=parseInt(e.headers.get("X-Retry-After")||"0",10);throw r.state.read().setRetryAfter(t,n).write(),new g(n)}if(!e.ok)throw new c})}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(!t.ok)throw new c})}catch(t){return Promise.reject(t)}},n.getRetryAfter=function(t){return this.state.read().getRetryAfter(t)},r}(x),U=/*#__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 w;if(!t.ok)throw new c;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 c;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 m;if(!e.ok)throw new c;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 m;if(!t.ok)throw new c;return t.json()})})}catch(t){return Promise.reject(t)}},r}(x),q=/*#__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}(T);function K(t){const e="==".slice(0,(4-t.length%4)%4),r=t.replace(/-/g,"+").replace(/_/g,"/")+e,n=atob(r),o=new ArrayBuffer(n.length),i=new Uint8Array(o);for(let t=0;t<n.length;t++)i[t]=n.charCodeAt(t);return o}function z(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,"")}function N(t,e,r){if("copy"===e)return r;if("convert"===e)return t(r);if(e instanceof Array)return r.map(r=>N(t,e[0],r));if(e instanceof Object){const n={};for(const[o,i]of Object.entries(e)){if(i.derive){const t=i.derive(r);void 0!==t&&(r[o]=t)}if(o in r)n[o]=null!=r[o]?N(t,i.schema,r[o]):null;else if(i.required)throw new Error(`Missing key: ${o}`)}return n}}function D(t,e){return{required:!0,schema:t,derive:e}}function M(t){return{required:!0,schema:t}}function H(t){return{required:!1,schema:t}}var J={type:M("copy"),id:M("convert"),transports:H("copy")},W={appid:H("copy"),appidExclude:H("copy"),credProps:H("copy")},B={appid:H("copy"),appidExclude:H("copy"),credProps:H("copy")},L={publicKey:M({rp:M("copy"),user:M({id:M("convert"),name:M("copy"),displayName:M("copy")}),challenge:M("convert"),pubKeyCredParams:M("copy"),timeout:H("copy"),excludeCredentials:H([J]),authenticatorSelection:H("copy"),attestation:H("copy"),extensions:H(W)}),signal:H("copy")},F={type:M("copy"),id:M("copy"),rawId:M("convert"),authenticatorAttachment:H("copy"),response:M({clientDataJSON:M("convert"),attestationObject:M("convert"),transports:D("copy",t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:D(B,t=>t.getClientExtensionResults())},V={mediation:H("copy"),publicKey:M({challenge:M("convert"),timeout:H("copy"),rpId:H("copy"),allowCredentials:H([J]),userVerification:H("copy"),extensions:H(W)}),signal:H("copy")},X={type:M("copy"),id:M("copy"),rawId:M("convert"),authenticatorAttachment:H("copy"),response:M({clientDataJSON:M("convert"),authenticatorData:M("convert"),signature:M("convert"),userHandle:M("convert")}),clientExtensionResults:D(B,t=>t.getClientExtensionResults())};async function G(t){const e=await navigator.credentials.create(function(t){return N(K,L,t)}(t));return function(t){return N(z,F,t)}(e)}async function $(t){const e=await navigator.credentials.get(function(t){return N(K,V,t)}(t));return function(t){return N(z,X,t)}(e)}var Q=/*#__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}();function Y(t,e){try{var r=t()}catch(t){return e(t)}return r&&r.then?r.then(void 0,e):r}var Z=/*#__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.controller=void 0,n._getCredential=$,n._createCredential=G,n.state=new q,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(t){function n(t){return Promise.resolve(r.client.post("/webauthn/login/finalize",o)).then(function(t){if(400===t.status||401===t.status)throw new h;if(!t.ok)throw new c;var e=t.json();r.state.read().addCredential(e.user_id,e.credential_id).write()})}if(!t.ok)throw new c;var o,i=t.json();i.signal=r._createAbortSignal(),e&&(i.mediation="conditional");var s=Y(function(){return Promise.resolve(r._getCredential(i)).then(function(t){o=t})},function(t){throw new f(t)});return s&&s.then?s.then(n):n()})}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 b;throw new m}if(!e.ok)throw new c;var r=e.json();t.state.read().addCredential(r.user_id,r.credential_id).write()})}if(e.status>=400&&e.status<=499)throw new m;if(!e.ok)throw new c;var n,o=e.json();o.signal=t._createAbortSignal();var i=Y(function(){return Promise.resolve(t._createCredential(o)).then(function(t){n=t})},function(t){throw new f(t)});return i&&i.then?i.then(r):r()})}catch(t){return Promise.reject(t)}},n.shouldRegister=function(t){try{var e=Q.supported();if(!t.webauthn_credentials||!t.webauthn_credentials.length)return Promise.resolve(e);var r=this.state.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}(x);exports.ConfigClient=S,exports.ConflictError=u,exports.Hanko=function(t,e){void 0===e&&(e=13e3),this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.config=new S(t,e),this.user=new U(t,e),this.webauthn=new Z(t,e),this.password=new I(t,e),this.passcode=new k(t,e)},exports.HankoError=a,exports.InvalidPasscodeError=p,exports.InvalidPasswordError=d,exports.InvalidWebauthnCredentialError=h,exports.MaxNumOfPasscodeAttemptsReachedError=y,exports.NotFoundError=w,exports.PasscodeClient=k,exports.PasscodeExpiredError=v,exports.PasswordClient=I,exports.RequestTimeoutError=l,exports.TechnicalError=c,exports.TooManyRequestsError=g,exports.UnauthorizedError=m,exports.UserClient=U,exports.UserVerificationError=b,exports.WebauthnClient=Z,exports.WebauthnRequestCancelledError=f,exports.WebauthnSupport=Q;
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(){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}}function o(t,e,i){return o=n()?Reflect.construct.bind():function(t,e,n){var o=[null];o.push.apply(o,e);var i=new(Function.bind.apply(t,o));return n&&r(i,n.prototype),i},o.apply(null,arguments)}function i(t){var n="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!==n){if(n.has(t))return n.get(t);n.set(t,i)}function i(){return o(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 s(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}var a=/*#__PURE__*/function(e){function r(t,n,o){var i;return(i=e.call(this,t)||this).code=void 0,i.cause=void 0,i.code=n,i.cause=o,Object.setPrototypeOf(s(i),r.prototype),i}return t(r,e),r}(/*#__PURE__*/i(Error)),c=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Technical error","somethingWentWrong",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),u=/*#__PURE__*/function(e){function r(t,n){var o;return o=e.call(this,"Conflict error","conflict",n)||this,Object.setPrototypeOf(s(o),r.prototype),o}return t(r,e),r}(a),l=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request timed out error","requestTimeout",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),h=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Request cancelled error","requestCancelled",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),f=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid password error","invalidPassword",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),d=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid Passcode error","invalidPasscode",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),p=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),w=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Passcode expired error","passcodeExpired",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),v=/*#__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(s(n),r.prototype),n}return t(r,e),r}(a),y=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Not found error","notFound",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),m=/*#__PURE__*/function(e){function r(t,n){var o;return(o=e.call(this,"Too many requests error","tooManyRequests",n)||this).retryAfter=void 0,o.retryAfter=t,Object.setPrototypeOf(s(o),r.prototype),o}return t(r,e),r}(a),g=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"Unauthorized error","unauthorized",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),P=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"User verification error","userVerification",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a),b=/*#__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(s(n),r.prototype),n}return t(r,e),r}(a),S=/*#__PURE__*/function(e){function r(t){var n;return n=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",t)||this,Object.setPrototypeOf(s(n),r.prototype),n}return t(r,e),r}(a);function O(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 C=function t(e,r){function n(t,n,o){if("undefined"!=typeof document){"number"==typeof(o=O({},r,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in o)o[s]&&(i+="; "+s,!0!==o[s]&&(i+="="+o[s].split(";")[0]));return document.cookie=t+"="+e.write(n,t)+i}}return Object.create({set:n,get:function(t){if("undefined"!=typeof document&&(!arguments.length||t)){for(var r=document.cookie?document.cookie.split("; "):[],n={},o=0;o<r.length;o++){var i=r[o].split("="),s=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(n[a]=e.read(s,a),t===a)break}catch(t){}}return t?n[t]:n}},remove:function(t,e){n(t,"",O({},e,{expires:-1}))},withAttributes:function(e){return t(this.converter,O({},this.attributes,e))},withConverter:function(e){return t(O({},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}(),x=/*#__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}(),A=/*#__PURE__*/function(){function t(t,e){void 0===e&&(e=13e3),this.timeout=void 0,this.api=void 0,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.api,o=n+t,i=this.timeout,s="hanko",a=C.get(s);return new Promise(function(t,u){r.open(e.method,o,!0),r.setRequestHeader("Accept","application/json"),r.setRequestHeader("Content-Type","application/json"),a&&r.setRequestHeader("Authorization","Bearer "+a),r.timeout=i,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");if(e){var o=!!n.match("^https://");C.set(s,e,{secure:o})}}t(new x(r))},r.onerror=function(){u(new c)},r.ontimeout=function(){u(new l)},r.send(e.body?e.body.toString():null)})},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}(),R=function(t,e){void 0===e&&(e=13e3),this.client=void 0,this.client=new A(t,e)},E=/*#__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 c;return t.json()})}catch(t){return Promise.reject(t)}},r}(R),T=/*#__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}(T),k=/*#__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 T.timeToRemainingSeconds(this.getState(t).ttl)},n.setTTL=function(t,e){return this.getState(t).ttl=T.remainingSecondsToTime(e),this},n.getResendAfter=function(t){return T.timeToRemainingSeconds(this.getState(t).resendAfter)},n.setResendAfter=function(t,e){return this.getState(t).resendAfter=T.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 k,n}t(r,e);var n=r.prototype;return n.initialize=function(t,e,r){try{var n=this;n.state.read();var o=n.state.getTTL(t),i=n.state.getActiveID(t),s=n.state.getEmailID(t),a=n.state.getResendAfter(t);if(!r&&o>0&&e===s)return Promise.resolve({id:i,ttl:o});if(a>0)throw new m(a);var u={user_id:t};return e&&(u.email_id=e),Promise.resolve(n.client.post("/passcode/login/initialize",u)).then(function(r){if(429===r.status)throw a=r.parseRetryAfterHeader(),n.state.setResendAfter(t,a).write(),new m(a);if(401===r.status)throw new g;if(!r.ok)throw new c;var o=r.json();return n.state.setActiveID(t,o.id).setTTL(t,o.ttl),e&&n.state.setEmailID(t,e),n.state.write(),o})}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 w;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 v;if(!e.ok)throw new c;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}(R),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 T.timeToRemainingSeconds(this.getState(t).retryAfter)},n.setRetryAfter=function(t,e){return this.getState(t).retryAfter=T.remainingSecondsToTime(e),this},r}(_),D=/*#__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 k,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 f;if(429===e.status){var n=e.parseRetryAfterHeader();throw r.passwordState.read().setRetryAfter(t,n).write(),new m(n)}if(!e.ok)throw new c;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 g;if(!t.ok)throw new c})}catch(t){return Promise.reject(t)}},n.getRetryAfter=function(t){return this.passwordState.read().getRetryAfter(t)},r}(R),N=/*#__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 y;if(!t.ok)throw new c;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 c;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 g;if(!e.ok)throw new c;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 g;if(!t.ok)throw new c;return t.json()})})}catch(t){return Promise.reject(t)}},r}(R);function q(t){const e="==".slice(0,(4-t.length%4)%4),r=t.replace(/-/g,"+").replace(/_/g,"/")+e,n=atob(r),o=new ArrayBuffer(n.length),i=new Uint8Array(o);for(let t=0;t<n.length;t++)i[t]=n.charCodeAt(t);return o}function K(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,"")}function M(t,e,r){if("copy"===e)return r;if("convert"===e)return t(r);if(e instanceof Array)return r.map(r=>M(t,e[0],r));if(e instanceof Object){const n={};for(const[o,i]of Object.entries(e)){if(i.derive){const t=i.derive(r);void 0!==t&&(r[o]=t)}if(o in r)n[o]=null!=r[o]?M(t,i.schema,r[o]):null;else if(i.required)throw new Error(`Missing key: ${o}`)}return n}}function z(t,e){return{required:!0,schema:t,derive:e}}function H(t){return{required:!0,schema:t}}function J(t){return{required:!1,schema:t}}var L={type:H("copy"),id:H("convert"),transports:J("copy")},W={appid:J("copy"),appidExclude:J("copy"),credProps:J("copy")},B={appid:J("copy"),appidExclude:J("copy"),credProps:J("copy")},F={publicKey:H({rp:H("copy"),user:H({id:H("convert"),name:H("copy"),displayName:H("copy")}),challenge:H("convert"),pubKeyCredParams:H("copy"),timeout:J("copy"),excludeCredentials:J([L]),authenticatorSelection:J("copy"),attestation:J("copy"),extensions:J(W)}),signal:J("copy")},V={type:H("copy"),id:H("copy"),rawId:H("convert"),authenticatorAttachment:J("copy"),response:H({clientDataJSON:H("convert"),attestationObject:H("convert"),transports:z("copy",t=>{var e;return(null==(e=t.getTransports)?void 0:e.call(t))||[]})}),clientExtensionResults:z(B,t=>t.getClientExtensionResults())},X={mediation:J("copy"),publicKey:H({challenge:H("convert"),timeout:J("copy"),rpId:J("copy"),allowCredentials:J([L]),userVerification:J("copy"),extensions:J(W)}),signal:J("copy")},G={type:H("copy"),id:H("copy"),rawId:H("convert"),authenticatorAttachment:J("copy"),response:H({clientDataJSON:H("convert"),authenticatorData:H("convert"),signature:H("convert"),userHandle:H("convert")}),clientExtensionResults:z(B,t=>t.getClientExtensionResults())};async function $(t){const e=await navigator.credentials.create(function(t){return M(q,F,t)}(t));return function(t){return M(K,V,t)}(e)}async function Q(t){const e=await navigator.credentials.get(function(t){return M(q,X,t)}(t));return function(t){return M(K,G,t)}(e)}var Y=/*#__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}(),Z=/*#__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 tt(t,e){try{var r=t()}catch(t){return e(t)}return r&&r.then?r.then(void 0,e):r}var et=/*#__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=Q,n._createCredential=$,n.webauthnState=new Z,n.passcodeState=new k,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){function o(e){return Promise.resolve(r.client.post("/webauthn/login/finalize",i)).then(function(e){if(400===e.status||401===e.status)throw new p;if(!e.ok)throw new c;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 c;var i,s=n.json();s.signal=r._createAbortSignal(),e&&(s.mediation="conditional");var a=tt(function(){return Promise.resolve(r._getCredential(s)).then(function(t){i=t})},function(t){throw new h(t)});return a&&a.then?a.then(o):o()})}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 P;throw new g}if(!e.ok)throw new c;var r=e.json();t.webauthnState.read().addCredential(r.user_id,r.credential_id).write()})}if(e.status>=400&&e.status<=499)throw new g;if(!e.ok)throw new c;var n,o=e.json();o.signal=t._createAbortSignal();var i=tt(function(){return Promise.resolve(t._createCredential(o)).then(function(t){n=t})},function(t){throw new h(t)});return i&&i.then?i.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 g;if(!t.ok)throw new c;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 g;if(!t.ok)throw new c})}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 g;if(!t.ok)throw new c})}catch(t){return Promise.reject(t)}},n.shouldRegister=function(t){try{var e=Y.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}(R),rt=/*#__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 g;if(!t.ok)throw new c;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 S;if(401===t.status)throw new g;if(409===t.status)throw new b;throw new c})}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 g;if(!t.ok)throw new c})}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 g;if(!t.ok)throw new c})}catch(t){return Promise.reject(t)}},r}(R);exports.ConfigClient=E,exports.ConflictError=u,exports.EmailAddressAlreadyExistsError=S,exports.EmailClient=rt,exports.Hanko=function(t,e){void 0===e&&(e=13e3),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.config=new E(t,e),this.user=new N(t,e),this.webauthn=new et(t,e),this.password=new D(t,e),this.passcode=new I(t,e),this.email=new rt(t,e)},exports.HankoError=a,exports.InvalidPasscodeError=d,exports.InvalidPasswordError=f,exports.InvalidWebauthnCredentialError=p,exports.MaxNumOfEmailAddressesReachedError=b,exports.MaxNumOfPasscodeAttemptsReachedError=v,exports.NotFoundError=y,exports.PasscodeClient=I,exports.PasscodeExpiredError=w,exports.PasswordClient=D,exports.RequestTimeoutError=l,exports.TechnicalError=c,exports.TooManyRequestsError=m,exports.UnauthorizedError=g,exports.UserClient=N,exports.UserVerificationError=P,exports.WebauthnClient=et,exports.WebauthnRequestCancelledError=h,exports.WebauthnSupport=Y;
2
2
  //# sourceMappingURL=sdk.cjs.map