@transmitsecurity/platform-web-sdk 2.2.0 → 2.3.1

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/dist/web-sdk.d.ts CHANGED
@@ -58,6 +58,7 @@ interface initConfigParams {
58
58
  };
59
59
  ido?: {
60
60
  serverPath?: string;
61
+ collectRiskData?: boolean;
61
62
  [key: string]: any;
62
63
  };
63
64
  [key: string]: any;
@@ -130,10 +131,12 @@ declare namespace storage {
130
131
 
131
132
  declare const INIT_ROTATION_RESPONSE = "init";
132
133
  declare const COMPLETED_ROTATION_RESPONSE = "completed";
134
+ type CryptoKeyInvalidReason = 'IDB_WRITE_TIMEOUT';
133
135
  type CryptoBindingPublicData = {
134
136
  publicKey: string;
135
137
  keyIdentifier: string;
136
138
  publicKeyId: string;
139
+ errors?: CryptoKeyInvalidReason[];
137
140
  };
138
141
  type CryptoBindingRotationPayload = {
139
142
  data: string;
@@ -157,6 +160,9 @@ type CryptoBindingOptions = {
157
160
  startedAt: number;
158
161
  tenantId: string;
159
162
  };
163
+ /** Timeout in milliseconds for IDB write transactions. If not set, no timeout is applied.
164
+ * Use to guard against browsers that silently freeze IDB (e.g. iOS 18.7 WKWebView ephemeral sessions). */
165
+ idbWriteTimeoutMs?: number;
160
166
  /** @internal
161
167
  * Warning! This flag shouldn't be used, it was added temporarily for multi-tenant support.
162
168
  *
@@ -180,6 +186,7 @@ declare class CryptoBinding {
180
186
  private keyIdentifier;
181
187
  private publicKeyId;
182
188
  private _extractingKeysPromise;
189
+ private cryptoBindingErrors;
183
190
  constructor(agent: Agent, keysType?: 'encrypt' | 'sign', options?: CryptoBindingOptions);
184
191
  private getClientConfiguration;
185
192
  private getKeysRecordKey;
@@ -250,11 +257,17 @@ type TransactionOperation = {
250
257
  type: 'delete';
251
258
  key: string;
252
259
  };
260
+ declare class IDBWriteTimeoutError extends Error {
261
+ constructor();
262
+ }
253
263
 
264
+ type indexedDB_IDBWriteTimeoutError = IDBWriteTimeoutError;
265
+ declare const indexedDB_IDBWriteTimeoutError: typeof IDBWriteTimeoutError;
254
266
  type indexedDB_QueryObjectStoreOptions = QueryObjectStoreOptions;
255
267
  type indexedDB_TransactionOperation = TransactionOperation;
256
268
  declare namespace indexedDB {
257
269
  export {
270
+ indexedDB_IDBWriteTimeoutError as IDBWriteTimeoutError,
258
271
  indexedDB_QueryObjectStoreOptions as QueryObjectStoreOptions,
259
272
  indexedDB_TransactionOperation as TransactionOperation,
260
273
  };
@@ -620,11 +633,17 @@ declare class TSAccountProtection {
620
633
  /** @ignore */
621
634
  getActions(): Promise<string[]>;
622
635
  getSessionToken(): Promise<any>;
636
+ /**
637
+ * Returns the lightweight (citadel) device payload to be forwarded to citadel via the caller's backend.
638
+ * The response from citadel includes a `deviceId` that must be passed back via {@link setDeviceId}
639
+ * — the server may issue a new one or rotate it, and the SDK only persists it when told to.
640
+ */
623
641
  getPayload(): Promise<LightweightPayload>;
624
642
  clearQueue(): void;
625
643
  /**
626
644
  * Sets the deviceId for lightweight mode (citadel).
627
- * Should be called after receiving deviceId from backend on first request.
645
+ * Should be called after every response from citadel the server may rotate the deviceId
646
+ * (e.g. after schema validation), so always propagate the returned value back into the SDK.
628
647
  * @param deviceId - The JWT deviceId returned from citadel backend
629
648
  */
630
649
  setDeviceId(deviceId: string): void;
@@ -1390,6 +1409,10 @@ interface StartJourneyOptions {
1390
1409
  * Should client-server communication be double encrypted? Defaults to false.
1391
1410
  */
1392
1411
  encrypted?: boolean;
1412
+ /**
1413
+ * An optional admin debug token to be passed to the Journey.
1414
+ */
1415
+ adminDebugToken?: string;
1393
1416
  }
1394
1417
  /**
1395
1418
  * @interface
@@ -1400,6 +1423,10 @@ interface StartSsoJourneyOptions {
1400
1423
  * Should client-server communication be double encrypted? Defaults to false.
1401
1424
  */
1402
1425
  encrypted?: boolean;
1426
+ /**
1427
+ * An optional admin debug token to be passed to the Journey.
1428
+ */
1429
+ adminDebugToken?: string;
1403
1430
  }
1404
1431
  /**
1405
1432
  * @enum
@@ -1556,7 +1583,7 @@ declare enum IdoServiceResponseType {
1556
1583
  /**
1557
1584
  * @enum
1558
1585
  * @description The enum for the Journey step ID, used when the journey step is a predefined typed action.
1559
- * The actions that do not use this are "Get Information from Client" and "Login Form" which allow the journey author to define a custom ID.
1586
+ * The actions that do not use this are "Collect information" and "Login Form" which allow the journey author to define a custom ID.
1560
1587
  * See also {@link IdoServiceResponse.journeyStepId}.
1561
1588
  */
1562
1589
  declare enum IdoJourneyActionType {
@@ -1583,7 +1610,7 @@ declare enum IdoJourneyActionType {
1583
1610
  * }
1584
1611
  * }
1585
1612
  * ```
1586
- * The client response does not need to include any data: `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1613
+ * The client response does not need to include any data: `ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1587
1614
  */
1588
1615
  Information = "action:information",
1589
1616
  /**
@@ -1593,7 +1620,7 @@ declare enum IdoJourneyActionType {
1593
1620
  *
1594
1621
  * The {@link IdoServiceResponse} object does not include any data.
1595
1622
  *
1596
- * The client response does not need to include any data: `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1623
+ * The client response does not need to include any data: `ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1597
1624
  */
1598
1625
  DebugBreak = "action:debug_break",
1599
1626
  /**
@@ -1602,7 +1629,7 @@ declare enum IdoJourneyActionType {
1602
1629
  * The {@link IdoServiceResponse} object includes information that can be presented as a QR to scan by another device.
1603
1630
  * The response will remain the same while the cross session message was not consumed by the journey executed by the other device.
1604
1631
  *
1605
- * The client response does not need to include any data: `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1632
+ * The client response does not need to include any data: `ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1606
1633
  */
1607
1634
  WaitForAnotherDevice = "action:wait_for_another_device",
1608
1635
  /**
@@ -1630,7 +1657,7 @@ declare enum IdoJourneyActionType {
1630
1657
  /**
1631
1658
  * @description `journeyStepId` for WebAuthn Registration action.
1632
1659
  *
1633
- * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `tsPlatform.webauthn.register()`
1660
+ * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `webauthn.register()`
1634
1661
  * ```json
1635
1662
  * {
1636
1663
  * "data": {
@@ -1642,10 +1669,10 @@ declare enum IdoJourneyActionType {
1642
1669
  * }
1643
1670
  * ```
1644
1671
  *
1645
- * Before responding, activate `tsPlatform.webauthn.register()` to obtain the `webauthn_encoded_result` value.
1672
+ * Before responding, activate `webauthn.register()` to obtain the `webauthn_encoded_result` value.
1646
1673
  * This will present the user with the WebAuthn registration UI. Use the result to send the client response:
1647
1674
  * ```json
1648
- * tsPlatform.ido.submitClientResponse(
1675
+ * ido.submitClientResponse(
1649
1676
  * ClientResponseOptionType.ClientInput,
1650
1677
  * {
1651
1678
  * "webauthn_encoded_result": "<WEBAUTHN_ENCODED_RESULT_FROM_SDK>"
@@ -1654,9 +1681,9 @@ declare enum IdoJourneyActionType {
1654
1681
  */
1655
1682
  WebAuthnRegistration = "action:webauthn_registration",
1656
1683
  /**
1657
- * @description `journeyStepId` for instructing the use of DRS trigger action, as part of the Risk Recommendation journey step.
1684
+ * @description `journeyStepId` for instructing the use of Fraud Prevention trigger action, as part of the Risk Recommendation journey step.
1658
1685
  *
1659
- * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `tsPlatform.drs.triggerActionEvent()`
1686
+ * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `drs.triggerActionEvent()`
1660
1687
  * ```json
1661
1688
  * {
1662
1689
  * "data": {
@@ -1666,13 +1693,13 @@ declare enum IdoJourneyActionType {
1666
1693
  * },
1667
1694
  * }
1668
1695
  * ```
1669
- * Before responding, activate `tsPlatform.drs.triggerActionEvent()` to obtain the `action_token` value. This is a silent action, and does not require user interaction.
1696
+ * Before responding, activate `drs.triggerActionEvent()` to obtain the `action_token` value. This is a silent action, and does not require user interaction.
1670
1697
  * Use the result to send the client response:
1671
1698
  * ```json
1672
- * tsPlatform.ido.submitClientResponse(
1699
+ * ido.submitClientResponse(
1673
1700
  * ClientResponseOptionType.ClientInput,
1674
1701
  * {
1675
- * "action_token": "<DRS action token>"
1702
+ * "action_token": "<Fraud Prevention action token>"
1676
1703
  * })
1677
1704
  * ```
1678
1705
  */
@@ -1695,12 +1722,12 @@ declare enum IdoJourneyActionType {
1695
1722
  * }
1696
1723
  * ```
1697
1724
  * Use this data to redirect the user to the identity verification endpoint.
1698
- * Since this redirects to a different page, make sure you store the SDK state by calling `tsPlatform.ido.serializeState()`, and saving the response data in the session storage.
1699
- * After the user completes the identity verification, you can restore the SDK state and continue the journey, by calling `tsPlatform.ido.restoreFromSerializedState()` with the stored state.
1725
+ * Since this redirects to a different page, make sure you store the SDK state by calling `ido.serializeState()`, and saving the response data in the session storage.
1726
+ * After the user completes the identity verification, you can restore the SDK state and continue the journey, by calling `ido.restoreFromSerializedState()` with the stored state.
1700
1727
  *
1701
1728
  * Once done, send the following client response:
1702
1729
  * ```json
1703
- * tsPlatform.ido.submitClientResponse(
1730
+ * ido.submitClientResponse(
1704
1731
  * ClientResponseOptionType.ClientInput,
1705
1732
  * {
1706
1733
  * "payload": {
@@ -1733,7 +1760,7 @@ declare enum IdoJourneyActionType {
1733
1760
  *
1734
1761
  * - For simple submit of OTP passcode:
1735
1762
  * ```json
1736
- * tsPlatform.ido.submitClientResponse(
1763
+ * ido.submitClientResponse(
1737
1764
  * ClientResponseOptionType.ClientInput,
1738
1765
  * {
1739
1766
  * "passcode": "<passcode>"
@@ -1741,7 +1768,7 @@ declare enum IdoJourneyActionType {
1741
1768
  * ```
1742
1769
  *
1743
1770
  * - In Order to request resend of OTP (restart the action):
1744
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1771
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1745
1772
  *
1746
1773
  */
1747
1774
  EmailOTPAuthentication = "transmit_platform_email_otp_authentication",
@@ -1767,7 +1794,7 @@ declare enum IdoJourneyActionType {
1767
1794
  *
1768
1795
  * - For simple submit of OTP passcode:
1769
1796
  * ```json
1770
- * tsPlatform.ido.submitClientResponse(
1797
+ * ido.submitClientResponse(
1771
1798
  * ClientResponseOptionType.ClientInput,
1772
1799
  * {
1773
1800
  * "passcode": "<passcode>"
@@ -1775,7 +1802,7 @@ declare enum IdoJourneyActionType {
1775
1802
  * ```
1776
1803
  *
1777
1804
  * - In Order to request resend of OTP (restart the action):
1778
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1805
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1779
1806
  *
1780
1807
  */
1781
1808
  SmsOTPAuthentication = "transmit_platform_sms_otp_authentication",
@@ -1801,7 +1828,7 @@ declare enum IdoJourneyActionType {
1801
1828
  *
1802
1829
  * - For simple submit of OTP passcode:
1803
1830
  * ```json
1804
- * tsPlatform.ido.submitClientResponse(
1831
+ * ido.submitClientResponse(
1805
1832
  * ClientResponseOptionType.ClientInput,
1806
1833
  * {
1807
1834
  * "passcode": "<passcode>"
@@ -1809,7 +1836,7 @@ declare enum IdoJourneyActionType {
1809
1836
  * ```
1810
1837
  *
1811
1838
  * - In Order to request resend of OTP (restart the action):
1812
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1839
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1813
1840
  *
1814
1841
  */
1815
1842
  GenericOTPAuthentication = "transmit_platform_generic_otp_authentication",
@@ -1831,7 +1858,7 @@ declare enum IdoJourneyActionType {
1831
1858
  * The user should use this to register the TOTP secret in their authenticator app.
1832
1859
  * Once the user has completed the registration, send the following empty client response:
1833
1860
  * ```json
1834
- * tsPlatform.ido.submitClientResponse(
1861
+ * ido.submitClientResponse(
1835
1862
  * ClientResponseOptionType.ClientInput
1836
1863
  * )
1837
1864
  * ```
@@ -1860,7 +1887,7 @@ declare enum IdoJourneyActionType {
1860
1887
  *
1861
1888
  * - For simple submit of validation passcode:
1862
1889
  * ```json
1863
- * tsPlatform.ido.submitClientResponse(
1890
+ * ido.submitClientResponse(
1864
1891
  * ClientResponseOptionType.ClientInput,
1865
1892
  * {
1866
1893
  * "passcode": "<passcode>"
@@ -1868,7 +1895,7 @@ declare enum IdoJourneyActionType {
1868
1895
  * ```
1869
1896
  *
1870
1897
  * - In Order to request resend of OTP (restart the action):
1871
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1898
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1872
1899
  *
1873
1900
  */
1874
1901
  EmailValidation = "transmit_platform_email_validation",
@@ -1893,7 +1920,7 @@ declare enum IdoJourneyActionType {
1893
1920
  *
1894
1921
  * - For simple submit of validation passcode:
1895
1922
  * ```json
1896
- * tsPlatform.ido.submitClientResponse(
1923
+ * ido.submitClientResponse(
1897
1924
  * ClientResponseOptionType.ClientInput,
1898
1925
  * {
1899
1926
  * "passcode": "<passcode>"
@@ -1901,7 +1928,7 @@ declare enum IdoJourneyActionType {
1901
1928
  * ```
1902
1929
  *
1903
1930
  * - In Order to request resend of OTP (restart the action):
1904
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1931
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1905
1932
  *
1906
1933
  */
1907
1934
  SmsValidation = "transmit_platform_sms_validation",
@@ -1930,7 +1957,7 @@ declare enum IdoJourneyActionType {
1930
1957
  *
1931
1958
  * - For submitting the TOTP code:
1932
1959
  * ```json
1933
- * tsPlatform.ido.submitClientResponse(
1960
+ * ido.submitClientResponse(
1934
1961
  * ClientResponseOptionType.ClientInput,
1935
1962
  * {
1936
1963
  * "totp_code": "<6_DIGIT_TOTP_CODE>"
@@ -1963,7 +1990,7 @@ declare enum IdoJourneyActionType {
1963
1990
  *
1964
1991
  * Once done, send the following client response:
1965
1992
  * ```json
1966
- * tsPlatform.ido.submitClientResponse(
1993
+ * ido.submitClientResponse(
1967
1994
  * ClientResponseOptionType.ClientInput,
1968
1995
  * {
1969
1996
  * "idp_response" : {
@@ -1994,16 +2021,16 @@ declare enum IdoJourneyActionType {
1994
2021
  * }
1995
2022
  * }
1996
2023
  * ```
1997
- * Before responding, call `tsPlatform.webauthn.approve.modal()` to obtain the `webauthn_encoded_result` value.
2024
+ * Before responding, call `webauthn.approve.modal()` to obtain the `webauthn_encoded_result` value.
1998
2025
  * ```javascript
1999
- * const result = await tsPlatform.webauthn.approve.modal(
2026
+ * const result = await webauthn.approve.modal(
2000
2027
  * response.data.approval_data // Transaction details to be approved
2001
2028
  * );
2002
2029
  * ```
2003
2030
  *
2004
2031
  * Then submit the result:
2005
2032
  * ```javascript
2006
- * tsPlatform.ido.submitClientResponse(
2033
+ * ido.submitClientResponse(
2007
2034
  * ClientResponseOptionType.ClientInput,
2008
2035
  * {
2009
2036
  * "webauthn_encoded_result": result
@@ -2047,7 +2074,7 @@ declare enum IdoJourneyActionType {
2047
2074
  *
2048
2075
  * For organization selection, send the following client response:
2049
2076
  * ```javascript
2050
- * tsPlatform.ido.submitClientResponse(
2077
+ * ido.submitClientResponse(
2051
2078
  * ClientResponseOptionType.ClientInput,
2052
2079
  * {
2053
2080
  * "organization_id": "<ORGANIZATION_ID>"
@@ -2082,7 +2109,7 @@ declare enum IdoJourneyActionType {
2082
2109
  *
2083
2110
  * For device selection, send the following client response:
2084
2111
  * ```javascript
2085
- * tsPlatform.ido.submitClientResponse(
2112
+ * ido.submitClientResponse(
2086
2113
  * ClientResponseOptionType.ClientInput,
2087
2114
  * {
2088
2115
  * "selected_device_code": "<DEVICE_CODE>"
@@ -2114,17 +2141,17 @@ declare enum IdoJourneyActionType {
2114
2141
  * ```javascript
2115
2142
  * // The application should implement its own polling mechanism
2116
2143
  * // and call this method periodically to check the status
2117
- * tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput)
2144
+ * ido.submitClientResponse(ClientResponseOptionType.ClientInput)
2118
2145
  * ```
2119
2146
  *
2120
2147
  * - To cancel the authentication:
2121
2148
  * ```javascript
2122
- * tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Cancel)
2149
+ * ido.submitClientResponse(ClientResponseOptionType.Cancel)
2123
2150
  * ```
2124
2151
  *
2125
2152
  * - To resend the push notification:
2126
2153
  * ```javascript
2127
- * tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)
2154
+ * ido.submitClientResponse(ClientResponseOptionType.Resend)
2128
2155
  * ```
2129
2156
  *
2130
2157
  * Note: The application is responsible for implementing the polling mechanism
@@ -2135,7 +2162,98 @@ declare enum IdoJourneyActionType {
2135
2162
  * On failure, the `IdoServiceResponse` {@link IdoServiceResponse.errorData} field will contain
2136
2163
  * relevant error codes that can be used to handle various failure scenarios.
2137
2164
  */
2138
- MobileApproveAuthentication = "transmit_platform_mobile_approve_authentication"
2165
+ MobileApproveAuthentication = "transmit_platform_mobile_approve_authentication",
2166
+ /**
2167
+ * @description `journeyStepId` for a selfie acquisition action.
2168
+ * This action instructs the client to acquire a selfie image from the user, typically as part of an identity verification or face authentication process.
2169
+ *
2170
+ * Data received in the {@link IdoServiceResponse} object:
2171
+ * ```json
2172
+ * {
2173
+ * "data": {
2174
+ * "start_token": "<START_TOKEN>", // Optional: used to start an identity verification session if required
2175
+ * "acquisition_id": "<ACQUISITION_ID>" // Required: ID needed to start selfie capture
2176
+ * }
2177
+ * }
2178
+ * ```
2179
+ *
2180
+ * To perform the selfie acquisition:
2181
+ * 1. If a `start_token` is present, initialize the IDV SDK session:
2182
+ * ```javascript
2183
+ * if (response.data.start_token !== undefined) {
2184
+ * await idv.start(response.data.start_token);
2185
+ * }
2186
+ * ```
2187
+ * 2. Run the selfie acquisition by calling the IDV SDK's `captureSelfie()` method:
2188
+ * ```javascript
2189
+ * await idv.captureSelfie({ acquisitionId: response.data.acquisition_id });
2190
+ * ```
2191
+ *
2192
+ * After acquiring the selfie, the client response does not need to include any data:
2193
+ * ```javascript
2194
+ * ido.submitClientResponse(ClientResponseOptionType.ClientInput);
2195
+ * ```
2196
+ *
2197
+ * If an error occurs while capturing the selfie, the client should handle error states and inform the user
2198
+ * and/or retry as appropriate according to application requirements.
2199
+ *
2200
+ * For deeper understanding and more implementation details, refer to the IDV SDK documentation:
2201
+ * {@link https://developer.transmitsecurity.com/sdk-ref/idvsdk/overview IDV SDK Reference}
2202
+ */
2203
+ SelfieAcquisition = "transmit_platform_selfie_acquisition",
2204
+ /**
2205
+ * @description `journeyStepId` for a document acquisition action.
2206
+ * This action instructs the client to acquire a document image from the user, typically as part of an identity verification or face authentication process.
2207
+ *
2208
+ * Data received in the {@link IdoServiceResponse} object:
2209
+ * ```json
2210
+ * {
2211
+ * "data": {
2212
+ * "start_token": "<START_TOKEN>", // Optional: used to start an identity verification session if required
2213
+ * "acquisition_id": "<ACQUISITION_ID>" // Required: ID needed to start document capture
2214
+ * }
2215
+ * }
2216
+ * ```
2217
+ *
2218
+ * To perform the document acquisition:
2219
+ * 1. If a `start_token` is present, initialize the IDV SDK session:
2220
+ * ```javascript
2221
+ * if (response.data.start_token !== undefined) {
2222
+ * await idv.start(response.data.start_token);
2223
+ * }
2224
+ * ```
2225
+ * 2. Run the document acquisition by calling the IDV SDK's `captureDocument()` method:
2226
+ * ```javascript
2227
+ * await idv.captureDocument({ acquisitionId: response.data.acquisition_id });
2228
+ * ```
2229
+ *
2230
+ * After acquiring the document, the client response does not need to include any data:
2231
+ * ```javascript
2232
+ * ido.submitClientResponse(ClientResponseOptionType.ClientInput);
2233
+ * ```
2234
+ *
2235
+ * If an error occurs while capturing the document, the client should handle error states and inform the user
2236
+ * and/or retry as appropriate according to application requirements.
2237
+ *
2238
+ * For deeper understanding and more implementation details, refer to the IDV SDK documentation:
2239
+ * {@link https://developer.transmitsecurity.com/sdk-ref/idvsdk/overview IDV SDK Reference}
2240
+ */
2241
+ DocumentAcquisition = "transmit_platform_document_acquisition",
2242
+ /**
2243
+ * @description `journeyStepId` for IDV recommendation action.
2244
+ *
2245
+ * When this action is received, it indicates that identity verification (IDV) processing is being performed asynchronously on the backend.
2246
+ * The client is responsible for implementing a polling mechanism: keep calling
2247
+ * `ido.submitClientResponse(ClientResponseOptionType.ClientInput)` in a loop until the server responds with a new action or returns an error.
2248
+ *
2249
+ * Note: No data is provided by the server in the {@link IdoServiceResponse} object for this action at any time.
2250
+ *
2251
+ * It is recommended to show a blocking UI element (such as a loader or progress indicator) while polling,
2252
+ * to inform the user that processing is ongoing.
2253
+ *
2254
+ * This process can take a couple of seconds. The recommended polling interval is every 1 second.
2255
+ */
2256
+ WaitForIdvRecommendations = "transmit_platform_idv_recommendation"
2139
2257
  }
2140
2258
  /**
2141
2259
  * @interface
@@ -2157,7 +2275,7 @@ interface IdoServiceResponse {
2157
2275
  readonly errorData?: IdoSdkError;
2158
2276
  /**
2159
2277
  * @description Contains the Journey step ID, allowing the client side to choose the correct handler and UI.
2160
- * This will be either a form ID for the "Get Information from Client" and "Login Form" journey steps,
2278
+ * This will be either a form ID for the "Collect information" and "Login Form" journey steps,
2161
2279
  * or one of {@link IdoJourneyActionType} for other actions.
2162
2280
  */
2163
2281
  readonly journeyStepId?: IdoJourneyActionType | string;
@@ -2191,7 +2309,8 @@ interface IdoSdk {
2191
2309
  * @throws {@link ErrorCode.InvalidInitOptions} in case of invalid init options.
2192
2310
  * @example
2193
2311
  * // Initialize an instance of the Identity Orchestration SDK using the unified SDK
2194
- * await window.tsPlatform.initialize({
2312
+ * import { initialize } from '@transmitsecurity/platform-web-sdk';
2313
+ * initialize({
2195
2314
  * clientId: 'my-client-id',
2196
2315
  * ido: { serverPath: 'https://api.transmitsecurity.io/ido'}
2197
2316
  * });
@@ -2208,7 +2327,7 @@ interface IdoSdk {
2208
2327
  * @example
2209
2328
  * // Start a Journey with the id 'my-journey-id'
2210
2329
  * try {
2211
- * const idoResponse = await window.tsPlatform.ido.startJourney('my-journey-id', { additionalParams: 'additionalParams' });
2330
+ * const idoResponse = await ido.startJourney('my-journey-id', { additionalParams: 'additionalParams' });
2212
2331
  * // Handle Journey response
2213
2332
  * } catch(error) {
2214
2333
  * switch(sdkError.errorCode) ...
@@ -2225,7 +2344,7 @@ interface IdoSdk {
2225
2344
  * @example
2226
2345
  * // Start a Journey with the Interaction ID '2456E855-05A0-4992-85C1-A2519CBB4AA7'
2227
2346
  * try {
2228
- * const idoResponse = await window.tsPlatform.ido.startSsoJourney('2456E855-05A0-4992-85C1-A2519CBB4AA7');
2347
+ * const idoResponse = await ido.startSsoJourney('2456E855-05A0-4992-85C1-A2519CBB4AA7');
2229
2348
  * // Handle Journey response
2230
2349
  * } catch(error) {
2231
2350
  * switch(sdkError.errorCode) ...
@@ -2254,7 +2373,7 @@ interface IdoSdk {
2254
2373
  *
2255
2374
  * // Submit the client input. The data inside the JSON correspond to the expected fields from the Journey step.
2256
2375
  * try {
2257
- * const idoResponse = await window.tsPlatform.ido.submitClientResponse(selectedInputOption, {
2376
+ * const idoResponse = await ido.submitClientResponse(selectedInputOption, {
2258
2377
  * 'userEmail': 'user@input.email',
2259
2378
  * 'userPhone': '111-222-3333',
2260
2379
  * });
@@ -2271,7 +2390,7 @@ interface IdoSdk {
2271
2390
  serializeState(): string;
2272
2391
  /**
2273
2392
  * @description Restores the SDK state from a serialized state, can be used to recover from page redirects or refresh.
2274
- * The application code also receives the latest communication from the orchestration server.
2393
+ * The application code also receives the latest communication from the Mosaic server.
2275
2394
  * @param state - The state to restore from.
2276
2395
  * @returns The last {@link IdoServiceResponse} that was received before the state was saved.
2277
2396
  * @throws {@link ErrorCode.InvalidState} - Throws error if the provided state string is invalid.
@@ -2279,15 +2398,18 @@ interface IdoSdk {
2279
2398
  restoreFromSerializedState(state: string): IdoServiceResponse;
2280
2399
  /**
2281
2400
  * @description This method will generate a debug PIN
2282
- * const debugPin = await sdk.generateDebugPin();
2283
- * console.log(`Debug PIN: ${debugPin}`); // Output: Debug PIN: 1234
2401
+ * const debugPin = await ido.generateDebugPin();
2402
+ * console.log(`Debug PIN: ${debugPin}`); // Output: Debug PIN: 1234
2284
2403
  */
2285
2404
  generateDebugPin(): Promise<string>;
2286
2405
  }
2287
2406
 
2288
2407
  declare module "@transmit-security/web-sdk-common/dist/module-metadata/module-metadata" {
2289
2408
  interface initConfigParams {
2290
- ido?: IdoInitOptions;
2409
+ ido?: {
2410
+ serverPath?: string;
2411
+ [key: string]: any;
2412
+ };
2291
2413
  }
2292
2414
  }
2293
2415
 
@@ -2364,6 +2486,6 @@ declare class TSWebSDK {
2364
2486
  }
2365
2487
  declare const _default: TSWebSDK;
2366
2488
 
2367
- declare const PACKAGE_VERSION = "2.2.0";
2489
+ declare const PACKAGE_VERSION = "2.3.1";
2368
2490
 
2369
2491
  export { ActionEventOptions, ActionResponse, AuthenticationAutofillActivateHandlers, AutofillHandlers, CrossDeviceController, ErrorCode$1 as ErrorCode, PACKAGE_VERSION, SDK_VERSIONS, SdkError, WebauthnApis, WebauthnAuthenticationFlows, WebauthnCrossDeviceFlows, WebauthnCrossDeviceRegistrationOptions, WebauthnRegistrationOptions, authenticate, index_d$3 as common, crossDevice, _default as default, webSdkModule_d as drs, getDefaultPaths, index_d as ido, index_d$2 as idv, initConfigParams, initialize, isAutofillSupported, isPlatformAuthenticatorSupported, register, index_d$1 as webauthn };
package/dist/webauthn.cjs CHANGED
@@ -1 +1 @@
1
- "undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));var t=require("./common.cjs"),e=require("./common.cjs");function i(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var a=i.call(t,e||"default");if("object"!=typeof a)return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function a(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,a)}return i}function r(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?a(Object(r),!0).forEach((function(e){i(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):a(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}class n{static arrayBufferToBase64(t){return btoa(String.fromCharCode(...new Uint8Array(t)))}static base64ToArrayBuffer(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}static stringToBase64(t){return btoa(t)}static jsonToBase64(t){const e=JSON.stringify(t);return btoa(e)}static base64ToJson(t){const e=atob(t);return JSON.parse(e)}}const s={log:console.log,error:console.error};var o,c;!function(t){t.NotInitialized="not_initialized",t.AuthenticationFailed="authentication_failed",t.AuthenticationAbortedTimeout="authentication_aborted_timeout",t.AuthenticationCanceled="webauthn_authentication_canceled",t.RegistrationFailed="registration_failed",t.AlreadyRegistered="username_already_registered",t.RegistrationAbortedTimeout="registration_aborted_timeout",t.RegistrationCanceled="webauthn_registration_canceled",t.AutofillAuthenticationAborted="autofill_authentication_aborted",t.AuthenticationProcessAlreadyActive="authentication_process_already_active",t.InvalidApprovalData="invalid_approval_data",t.FailedToInitCrossDeviceSession="cross_device_init_failed",t.FailedToGetCrossDeviceStatus="cross_device_status_failed",t.Unknown="unknown"}(o||(o={}));class l extends Error{constructor(t,e){super(t),this.errorCode=o.NotInitialized,this.data=e}}class u extends l{constructor(t,e){super(null!=t?t:"WebAuthnSdk is not initialized",e),this.errorCode=o.NotInitialized}}class d extends l{constructor(t,e){super(null!=t?t:"Authentication failed with an error",e),this.errorCode=o.AuthenticationFailed}}class h extends l{constructor(t,e){super(null!=t?t:"Authentication was canceled by the user or got timeout",e),this.errorCode=o.AuthenticationCanceled}}class p extends l{constructor(t,e){super(null!=t?t:"Registration failed with an error",e),this.errorCode=o.RegistrationFailed}}class v extends l{constructor(t,e){super(null!=t?t:"Registration was canceled by the user or got timeout",e),this.errorCode=o.RegistrationCanceled}}class g extends l{constructor(t){super(null!=t?t:"Autofill flow was aborted"),this.errorCode=o.AutofillAuthenticationAborted}}class f extends l{constructor(t){super(null!=t?t:"Operation was aborted by timeout"),this.errorCode=o.AutofillAuthenticationAborted}}class w extends l{constructor(t){super(null!=t?t:"Passkey with this username is already registered with the relying party."),this.errorCode=o.AlreadyRegistered}}class m extends l{constructor(t,e){super(null!=t?t:"Authentication process is already active",e),this.errorCode=o.AuthenticationProcessAlreadyActive}}class y extends l{constructor(t,e){super(null!=t?t:"Invalid approval data",e),this.errorCode=o.InvalidApprovalData}}class b extends l{constructor(t,e){super(null!=t?t:"Failed to init cross device authentication",e),this.errorCode=o.FailedToInitCrossDeviceSession}}class C extends l{constructor(t,e){super(null!=t?t:"Failed to get cross device status",e),this.errorCode=o.FailedToGetCrossDeviceStatus}}function A(t){return t.errorCode&&Object.values(o).includes(t.errorCode)}!function(t){t[t.persistent=0]="persistent",t[t.session=1]="session"}(c||(c={}));class D{static get(t){return D.getStorageMedium(D.allowedKeys[t]).getItem(D.getStorageKey(t))||void 0}static set(t,e){return D.getStorageMedium(D.allowedKeys[t]).setItem(D.getStorageKey(t),e)}static remove(t){D.getStorageMedium(D.allowedKeys[t]).removeItem(D.getStorageKey(t))}static clear(t){for(const[e,i]of Object.entries(D.allowedKeys)){const a=e;t&&this.configurationKeys.includes(a)||D.getStorageMedium(i).removeItem(D.getStorageKey(a))}}static getStorageKey(t){return`WebAuthnSdk:${t}`}static getStorageMedium(t){return t===c.session?sessionStorage:localStorage}}D.allowedKeys={clientId:c.session},D.configurationKeys=["clientId"];class _{static isNewApiDomain(t){return t&&(this.newApiDomains.includes(t)||t.startsWith("api.")&&t.endsWith(".transmitsecurity.io"))}static dnsPrefetch(t){const e=document.createElement("link");e.rel="dns-prefetch",e.href=t,document.head.appendChild(e)}static preconnect(t,e){const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}static warmupConnection(t){this.dnsPrefetch(t),this.preconnect(t,!1),this.preconnect(t,!0)}static init(t,e){var i,a;try{this._serverPath=new URL(e.serverPath),this.isNewApiDomain(null===(i=this._serverPath)||void 0===i?void 0:i.hostname)&&this.warmupConnection(this._serverPath.origin),this._apiPaths=null!==(a=e.webauthnApiPaths)&&void 0!==a?a:this.getDefaultPaths(),this._clientId=t,D.set("clientId",t)}catch(t){throw new u("Invalid options.serverPath",{error:t})}}static getDefaultPaths(){var t;const e=this.isNewApiDomain(null===(t=this._serverPath)||void 0===t?void 0:t.hostname)?"/cis":"";return{startAuthentication:`${e}/v1/auth/webauthn/authenticate/start`,startRegistration:`${e}/v1/auth/webauthn/register/start`,initCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/init`,startCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/start`,startCrossDeviceRegistration:`${e}/v1/auth/webauthn/cross-device/register/start`,getCrossDeviceTicketStatus:`${e}/v1/auth/webauthn/cross-device/status`,attachDeviceToCrossDeviceSession:`${e}/v1/auth/webauthn/cross-device/attach-device`}}static getApiPaths(){return this._apiPaths}static async sendRequest(t,e,i){s.log(`[WebAuthn SDK] Calling ${e.method} ${t}...`);const a=new URL(this._serverPath);return a.pathname=t,i&&(a.search=i),fetch(a.toString(),e)}static async startRegistration(t){const e=await this.sendRequest(this._apiPaths.startRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r(r({client_id:this.getValidatedClientId(),username:t.username,display_name:t.displayName},t.timeout&&{timeout:t.timeout}),t.limitSingleCredentialToDevice&&{limit_single_credential_to_device:t.limitSingleCredentialToDevice}))});if(!(null==e?void 0:e.ok))throw new d("Failed to start registration",null==e?void 0:e.body);return await e.json()}static async startAuthentication(t){const e=await this.sendRequest(this._apiPaths.startAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r(r(r(r(r({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.identifier&&{identifier:t.identifier}),t.identifierType&&{identifier_type:t.identifierType}),t.approvalData&&{approval_data:t.approvalData}),t.timeout&&{timeout:t.timeout}))});if(!(null==e?void 0:e.ok))throw new d("Failed to start authentication",null==e?void 0:e.body);return await e.json()}static async initCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.initCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r(r({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}))});if(!(null==e?void 0:e.ok))throw new b(void 0,null==e?void 0:e.body);return await e.json()}static async getCrossDeviceTicketStatus(t){const e=await this.sendRequest(this._apiPaths.getCrossDeviceTicketStatus,{method:"GET"},`cross_device_ticket_id=${t.ticketId}`);if(!(null==e?void 0:e.ok))throw new C(void 0,null==e?void 0:e.body);return await e.json()}static async startCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new d("Failed to start cross device authentication",null==e?void 0:e.body);return await e.json()}static async startCrossDeviceRegistration(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new p("Failed to start cross device registration",null==e?void 0:e.body);return await e.json()}static async attachDeviceToCrossDeviceSession(t){const e=await this.sendRequest(this._apiPaths.attachDeviceToCrossDeviceSession,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new p("Failed to attach device to cross device session",null==e?void 0:e.body);return await e.json()}static getValidatedClientId(){var t;const e=null!==(t=this._clientId)&&void 0!==t?t:D.get("clientId");if(!e)throw new u("Missing clientId");return e}}var S,T,k,I;_.newApiDomains=["api.idsec-dev.com","api.idsec-stg.com"],function(t){t.InputAutofill="input-autofill",t.Modal="modal"}(S||(S={})),exports.WebauthnCrossDeviceStatus=void 0,(T=exports.WebauthnCrossDeviceStatus||(exports.WebauthnCrossDeviceStatus={})).Pending="pending",T.Scanned="scanned",T.Success="success",T.Error="error",T.Timeout="timeout",T.Aborted="aborted",function(t){t.toAuthenticationError=t=>A(t)?t:"NotAllowedError"===t.name?new h:"OperationError"===t.name?new m(t.message):"SecurityError"===t.name?new d(t.message):t===o.AuthenticationAbortedTimeout?new f:"AbortError"===t.name||t===o.AutofillAuthenticationAborted?new g:new d("Something went wrong during authentication",{error:t}),t.toRegistrationError=t=>A(t)?t:"NotAllowedError"===t.name?new v:"SecurityError"===t.name?new p(t.message):"InvalidStateError"===t.name?new w:t===o.RegistrationAbortedTimeout?new f:new p("Something went wrong during registration",{error:t})}(k||(k={})),function(t){t.processCredentialRequestOptions=t=>r(r({},t),{},{challenge:n.base64ToArrayBuffer(t.challenge),allowCredentials:t.allowCredentials.map((t=>r(r({},t),{},{id:n.base64ToArrayBuffer(t.id)})))}),t.processCredentialCreationOptions=(t,e)=>{var i;const a=JSON.parse(JSON.stringify(t));return a.challenge=n.base64ToArrayBuffer(t.challenge),a.user.id=n.base64ToArrayBuffer(t.user.id),(null==e?void 0:e.limitSingleCredentialToDevice)&&(a.excludeCredentials=null===(i=t.excludeCredentials)||void 0===i?void 0:i.map((t=>r(r({},t),{},{id:n.base64ToArrayBuffer(t.id)})))),(null==e?void 0:e.registerAsDiscoverable)?(a.authenticatorSelection.residentKey="preferred",a.authenticatorSelection.requireResidentKey=!0):(a.authenticatorSelection.residentKey="discouraged",a.authenticatorSelection.requireResidentKey=!1),a.authenticatorSelection.authenticatorAttachment=(null==e?void 0:e.allowCrossPlatformAuthenticators)?void 0:"platform",a},t.encodeAuthenticationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:n.arrayBufferToBase64(t.rawId),response:{authenticatorData:n.arrayBufferToBase64(i.authenticatorData),clientDataJSON:n.arrayBufferToBase64(i.clientDataJSON),signature:n.arrayBufferToBase64(i.signature),userHandle:n.arrayBufferToBase64(i.userHandle)},authenticatorAttachment:e,type:t.type}},t.encodeRegistrationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:n.arrayBufferToBase64(t.rawId),response:{attestationObject:n.arrayBufferToBase64(i.attestationObject),clientDataJSON:n.arrayBufferToBase64(i.clientDataJSON)},authenticatorAttachment:e,type:t.type}}}(I||(I={}));class P{async modal(t){try{const e=await this.performAuthentication(r(r({},t),{},{mediationType:S.Modal}));return n.jsonToBase64(e)}catch(t){throw k.toAuthenticationError(t)}}activateAutofill(t){const{handlers:e,username:i}=t,{onSuccess:a,onError:r,onReady:s}=e;this.performAuthentication({username:i,mediationType:S.InputAutofill,onReady:s}).then((t=>{a(n.jsonToBase64(t))})).catch((t=>{const e=k.toAuthenticationError(t);if(!r)throw e;r(e)}))}abortAutofill(){this.abortController&&this.abortController.abort(o.AutofillAuthenticationAborted)}abortAuthentication(){this.abortController&&this.abortController.abort(o.AuthenticationAbortedTimeout)}async performAuthentication(t){var e,i;const a="crossDeviceTicketId"in t?await _.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await _.startAuthentication({username:t.username,identifier:t.identifier,identifierType:t.identifierType,timeout:null===(e=t.options)||void 0===e?void 0:e.timeout}),r=a.credential_request_options,n=I.processCredentialRequestOptions(r),s=this.getMediatedCredentialRequest(n,t.mediationType);t.mediationType===S.InputAutofill&&(null===(i=t.onReady)||void 0===i||i.call(t));const o=await navigator.credentials.get(s).catch((t=>{throw k.toAuthenticationError(t)}));return{webauthnSessionId:a.webauthn_session_id,publicKeyCredential:I.encodeAuthenticationResult(o),userAgent:navigator.userAgent}}getMediatedCredentialRequest(t,e){const i={publicKey:t};return this.abortController=new AbortController,i.signal=this.abortController&&this.abortController.signal,e===S.InputAutofill?i.mediation="conditional":t.timeout&&setTimeout((()=>{this.abortAuthentication()}),t.timeout),i}}class O{constructor(t,e){this.handler=t,this.intervalInMs=e}begin(){var t;this.intervalId=window.setInterval((t=this.handler,async function(){t.isRunning||(t.isRunning=!0,await t(...arguments),t.isRunning=!1)}),this.intervalInMs)}stop(){clearInterval(this.intervalId)}}const R=/^[A-Za-z0-9\-_.: ]*$/;function j(t){if(t&&(!function(t){return Object.keys(t).length<=10}(t)||!function(t){const e=t=>"string"==typeof t,i=t=>R.test(t);return Object.keys(t).every((a=>e(a)&&e(t[a])&&i(a)&&i(t[a])))}(t)))throw s.error("Failed validating approval data"),new y("Provided approval data should have 10 properties max. Also, it should contain only \n alphanumeric characters, numbers, and the special characters: '-', '_', '.'")}class x{constructor(t,e,i){this.authenticationHandler=t,this.registrationHandler=e,this.approvalHandler=i,this.init={registration:async t=>(this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(t.crossDeviceTicketId,t.handlers)),authentication:async t=>{const{username:e}=t,i=(await _.initCrossDeviceAuthentication(r({},e&&{username:e}))).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(i,t.handlers)},approval:async t=>{const{username:e,approvalData:i}=t;j(i);const a=(await _.initCrossDeviceAuthentication({username:e,approvalData:i})).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(a,t.handlers)}},this.authenticate={modal:async t=>this.authenticationHandler.modal({crossDeviceTicketId:t})},this.approve={modal:async t=>this.approvalHandler.modal({crossDeviceTicketId:t})}}async register(t){return this.registrationHandler.register(t)}async attachDevice(t){const e=await _.attachDeviceToCrossDeviceSession({ticketId:t});return r({status:e.status,startedAt:e.started_at},e.approval_data&&{approvalData:e.approval_data})}async pollCrossDeviceSession(t,e){return this.poller=new O((async()=>{var i,a;const r=await _.getCrossDeviceTicketStatus({ticketId:t}),n=r.status;if(n!==this.ticketStatus)switch(this.ticketStatus=n,n){case exports.WebauthnCrossDeviceStatus.Scanned:await e.onDeviceAttach();break;case exports.WebauthnCrossDeviceStatus.Error:case exports.WebauthnCrossDeviceStatus.Timeout:case exports.WebauthnCrossDeviceStatus.Aborted:await e.onFailure(r),null===(i=this.poller)||void 0===i||i.stop();break;case exports.WebauthnCrossDeviceStatus.Success:if("onCredentialRegister"in e)await e.onCredentialRegister();else{if(!r.session_id)throw new C("Cross device session is complete without returning session_id",r);await e.onCredentialAuthenticate(r.session_id)}null===(a=this.poller)||void 0===a||a.stop()}}),1e3),this.poller.begin(),setTimeout((()=>{var t;null===(t=this.poller)||void 0===t||t.stop(),e.onFailure({status:exports.WebauthnCrossDeviceStatus.Timeout})}),3e5),{crossDeviceTicketId:t,stop:()=>{var t;null===(t=this.poller)||void 0===t||t.stop()}}}}class K{async register(t){var e,i,a;this.abortController=new AbortController;const s=r({allowCrossPlatformAuthenticators:!("crossDeviceTicketId"in t),registerAsDiscoverable:!0},t.options);try{const r="crossDeviceTicketId"in t?await _.startCrossDeviceRegistration({ticketId:t.crossDeviceTicketId}):await _.startRegistration({username:t.username,displayName:(null===(e=t.options)||void 0===e?void 0:e.displayName)||t.username,timeout:null===(i=t.options)||void 0===i?void 0:i.timeout,limitSingleCredentialToDevice:null===(a=t.options)||void 0===a?void 0:a.limitSingleCredentialToDevice}),o=I.processCredentialCreationOptions(r.credential_creation_options,s);setTimeout((()=>{this.abortRegistration()}),o.timeout);const c=await this.registerCredential(o),l={webauthnSessionId:r.webauthn_session_id,publicKeyCredential:c,userAgent:navigator.userAgent};return n.jsonToBase64(l)}catch(t){throw k.toRegistrationError(t)}}abortRegistration(){this.abortController&&this.abortController.abort(o.RegistrationAbortedTimeout)}async registerCredential(t){const e=await navigator.credentials.create({publicKey:t,signal:this.abortController&&this.abortController.signal}).catch((t=>{throw k.toRegistrationError(t)}));return I.encodeRegistrationResult(e)}}class B{async modal(t){try{const e=await this.performApproval(t);return n.jsonToBase64(e)}catch(t){throw k.toAuthenticationError(t)}}async performApproval(t){"approvalData"in t&&j(t.approvalData);const e="crossDeviceTicketId"in t?await _.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await _.startAuthentication({username:t.username,approvalData:t.approvalData}),i=e.credential_request_options,a=I.processCredentialRequestOptions(i),r=await navigator.credentials.get({publicKey:a}).catch((t=>{throw k.toAuthenticationError(t)}));return{webauthnSessionId:e.webauthn_session_id,publicKeyCredential:I.encodeAuthenticationResult(r),userAgent:navigator.userAgent}}}class E{constructor(){this._initialized=!1,this._authenticationHandler=new P,this._registrationHandler=new K,this._approvalHandler=new B,this._crossDeviceHandler=new x(this._authenticationHandler,this._registrationHandler,this._approvalHandler),this.authenticate={modal:async t=>(this.initCheck(),this._authenticationHandler.modal(t)),autofill:{activate:t=>(this.initCheck(),this._authenticationHandler.activateAutofill(t)),abort:()=>this._authenticationHandler.abortAutofill()}},this.approve={modal:async t=>(this.initCheck(),this._approvalHandler.modal(t))},this.register=async t=>(this.initCheck(),this._registrationHandler.register(t)),this.crossDevice={init:{registration:async t=>(this.initCheck(),this._crossDeviceHandler.init.registration(t)),authentication:async t=>(this.initCheck(),this._crossDeviceHandler.init.authentication(t)),approval:async t=>(this.initCheck(),this._crossDeviceHandler.init.approval(t))},authenticate:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.authenticate.modal(t))},approve:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.approve.modal(t))},register:async t=>(this.initCheck(),this._crossDeviceHandler.register(t)),attachDevice:async t=>(this.initCheck(),this._crossDeviceHandler.attachDevice(t))},this.isPlatformAuthenticatorSupported=async()=>{var t;try{return await(null===(t=E.StaticPublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable())}catch(t){return!1}},this.isAutofillSupported=async()=>{var t,e;return!(!(null===(t=E.StaticPublicKeyCredential)||void 0===t?void 0:t.isConditionalMediationAvailable)||!await(null===(e=E.StaticPublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable()))}}async init(t){const{clientId:e,options:i}=t;try{if(!e)throw new u("Invalid clientId",{clientId:e});if(i.webauthnApiPaths){const t=_.getDefaultPaths();if(function(t,e){const i=new Set(t),a=new Set(e);return[...t.filter((t=>!a.has(t))),...e.filter((t=>!i.has(t)))]}(Object.keys(i.webauthnApiPaths),Object.keys(t)).length)throw new u("Invalid custom paths",{customApiPaths:i.webauthnApiPaths})}_.init(e,i),this._initialized=!0}catch(t){throw A(t)?t:new u("Failed to initialize SDK")}}getDefaultPaths(){return this.initCheck(),_.getDefaultPaths()}getApiPaths(){return this.initCheck(),_.getApiPaths()}initCheck(){if(!this._initialized)throw new u}}E.StaticPublicKeyCredential=window.PublicKeyCredential;const N=new t("webauthn"),H=new E;N.events.on(N.events.MODULE_INITIALIZED,(()=>{var t;const e=N.moduleMetadata.getInitConfig();if(!(null===(t=null==e?void 0:e.webauthn)||void 0===t?void 0:t.serverPath))return;const{clientId:i,webauthn:a}=e;H.init({clientId:i,options:r({},a)})}));const W={modal:async t=>(H.initCheck(),H.authenticate.modal(t)),autofill:{activate:t=>{H.initCheck(),H.authenticate.autofill.activate(t)},abort:()=>{H.initCheck(),H.authenticate.autofill.abort()}}},q={modal:async t=>(H.initCheck(),H.approve.modal(t))};async function F(t){return H.initCheck(),H.register(t)}const{crossDevice:M}=H,{isPlatformAuthenticatorSupported:z}=H,{isAutofillSupported:J}=H,{getDefaultPaths:$}=H;window.localWebAuthnSDK=H;var U=Object.freeze({__proto__:null,get WebauthnCrossDeviceStatus(){return exports.WebauthnCrossDeviceStatus},approve:q,authenticate:W,crossDevice:M,getDefaultPaths:$,isAutofillSupported:J,isPlatformAuthenticatorSupported:z,register:F});const V={initialize:e.initialize,...U};Object.defineProperty(exports,"initialize",{enumerable:!0,get:function(){return e.initialize}}),exports.PACKAGE_VERSION="2.2.0",exports.approve=q,exports.authenticate=W,exports.crossDevice=M,exports.getDefaultPaths=$,exports.isAutofillSupported=J,exports.isPlatformAuthenticatorSupported=z,exports.register=F,exports.webauthn=V;
1
+ "undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));var t=require("./common.cjs"),e=require("./common.cjs");function i(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var a=i.call(t,e||"default");if("object"!=typeof a)return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function a(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,a)}return i}function r(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?a(Object(r),!0).forEach((function(e){i(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):a(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}class n{static arrayBufferToBase64(t){return btoa(String.fromCharCode(...new Uint8Array(t)))}static base64ToArrayBuffer(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}static stringToBase64(t){return btoa(t)}static jsonToBase64(t){const e=JSON.stringify(t);return btoa(e)}static base64ToJson(t){const e=atob(t);return JSON.parse(e)}}const s={log:console.log,error:console.error};var o,c;!function(t){t.NotInitialized="not_initialized",t.AuthenticationFailed="authentication_failed",t.AuthenticationAbortedTimeout="authentication_aborted_timeout",t.AuthenticationCanceled="webauthn_authentication_canceled",t.RegistrationFailed="registration_failed",t.AlreadyRegistered="username_already_registered",t.RegistrationAbortedTimeout="registration_aborted_timeout",t.RegistrationCanceled="webauthn_registration_canceled",t.AutofillAuthenticationAborted="autofill_authentication_aborted",t.AuthenticationProcessAlreadyActive="authentication_process_already_active",t.InvalidApprovalData="invalid_approval_data",t.FailedToInitCrossDeviceSession="cross_device_init_failed",t.FailedToGetCrossDeviceStatus="cross_device_status_failed",t.Unknown="unknown"}(o||(o={}));class l extends Error{constructor(t,e){super(t),this.errorCode=o.NotInitialized,this.data=e}}class u extends l{constructor(t,e){super(null!=t?t:"WebAuthnSdk is not initialized",e),this.errorCode=o.NotInitialized}}class d extends l{constructor(t,e){super(null!=t?t:"Authentication failed with an error",e),this.errorCode=o.AuthenticationFailed}}class h extends l{constructor(t,e){super(null!=t?t:"Authentication was canceled by the user or got timeout",e),this.errorCode=o.AuthenticationCanceled}}class p extends l{constructor(t,e){super(null!=t?t:"Registration failed with an error",e),this.errorCode=o.RegistrationFailed}}class v extends l{constructor(t,e){super(null!=t?t:"Registration was canceled by the user or got timeout",e),this.errorCode=o.RegistrationCanceled}}class g extends l{constructor(t){super(null!=t?t:"Autofill flow was aborted"),this.errorCode=o.AutofillAuthenticationAborted}}class f extends l{constructor(t){super(null!=t?t:"Operation was aborted by timeout"),this.errorCode=o.AutofillAuthenticationAborted}}class m extends l{constructor(t){super(null!=t?t:"Passkey with this username is already registered with the relying party."),this.errorCode=o.AlreadyRegistered}}class w extends l{constructor(t,e){super(null!=t?t:"Authentication process is already active",e),this.errorCode=o.AuthenticationProcessAlreadyActive}}class y extends l{constructor(t,e){super(null!=t?t:"Invalid approval data",e),this.errorCode=o.InvalidApprovalData}}class b extends l{constructor(t,e){super(null!=t?t:"Failed to init cross device authentication",e),this.errorCode=o.FailedToInitCrossDeviceSession}}class C extends l{constructor(t,e){super(null!=t?t:"Failed to get cross device status",e),this.errorCode=o.FailedToGetCrossDeviceStatus}}function A(t){return t.errorCode&&Object.values(o).includes(t.errorCode)}!function(t){t[t.persistent=0]="persistent",t[t.session=1]="session"}(c||(c={}));class D{static get(t){return D.getStorageMedium(D.allowedKeys[t]).getItem(D.getStorageKey(t))||void 0}static set(t,e){return D.getStorageMedium(D.allowedKeys[t]).setItem(D.getStorageKey(t),e)}static remove(t){D.getStorageMedium(D.allowedKeys[t]).removeItem(D.getStorageKey(t))}static clear(t){for(const[e,i]of Object.entries(D.allowedKeys)){const a=e;t&&this.configurationKeys.includes(a)||D.getStorageMedium(i).removeItem(D.getStorageKey(a))}}static getStorageKey(t){return`WebAuthnSdk:${t}`}static getStorageMedium(t){return t===c.session?sessionStorage:localStorage}}D.allowedKeys={clientId:c.session},D.configurationKeys=["clientId"];class _{static isNewApiDomain(t){return t&&(this.newApiDomains.includes(t)||t.startsWith("api.")&&t.endsWith(".transmitsecurity.io")||t.startsWith("api.")&&t.endsWith(".idsec-dev.com"))}static dnsPrefetch(t){const e=document.createElement("link");e.rel="dns-prefetch",e.href=t,document.head.appendChild(e)}static preconnect(t,e){const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}static warmupConnection(t){this.dnsPrefetch(t),this.preconnect(t,!1),this.preconnect(t,!0)}static init(t,e){var i,a;try{this._serverPath=new URL(e.serverPath),this.isNewApiDomain(null===(i=this._serverPath)||void 0===i?void 0:i.hostname)&&this.warmupConnection(this._serverPath.origin),this._apiPaths=null!==(a=e.webauthnApiPaths)&&void 0!==a?a:this.getDefaultPaths(),this._clientId=t,D.set("clientId",t)}catch(t){throw new u("Invalid options.serverPath",{error:t})}}static getDefaultPaths(){var t;const e=this.isNewApiDomain(null===(t=this._serverPath)||void 0===t?void 0:t.hostname)?"/cis":"";return{startAuthentication:`${e}/v1/auth/webauthn/authenticate/start`,startRegistration:`${e}/v1/auth/webauthn/register/start`,initCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/init`,startCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/start`,startCrossDeviceRegistration:`${e}/v1/auth/webauthn/cross-device/register/start`,getCrossDeviceTicketStatus:`${e}/v1/auth/webauthn/cross-device/status`,attachDeviceToCrossDeviceSession:`${e}/v1/auth/webauthn/cross-device/attach-device`}}static getApiPaths(){return this._apiPaths}static async sendRequest(t,e,i){s.log(`[WebAuthn SDK] Calling ${e.method} ${t}...`);const a=new URL(this._serverPath);return a.pathname=t,i&&(a.search=i),fetch(a.toString(),e)}static async startRegistration(t){const e=await this.sendRequest(this._apiPaths.startRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r(r({client_id:this.getValidatedClientId(),username:t.username,display_name:t.displayName},t.timeout&&{timeout:t.timeout}),t.limitSingleCredentialToDevice&&{limit_single_credential_to_device:t.limitSingleCredentialToDevice}))});if(!(null==e?void 0:e.ok))throw new d("Failed to start registration",null==e?void 0:e.body);return await e.json()}static async startAuthentication(t){const e=await this.sendRequest(this._apiPaths.startAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r(r(r(r(r({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.identifier&&{identifier:t.identifier}),t.identifierType&&{identifier_type:t.identifierType}),t.approvalData&&{approval_data:t.approvalData}),t.timeout&&{timeout:t.timeout}))});if(!(null==e?void 0:e.ok))throw new d("Failed to start authentication",null==e?void 0:e.body);return await e.json()}static async initCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.initCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r(r({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}))});if(!(null==e?void 0:e.ok))throw new b(void 0,null==e?void 0:e.body);return await e.json()}static async getCrossDeviceTicketStatus(t){const e=await this.sendRequest(this._apiPaths.getCrossDeviceTicketStatus,{method:"GET"},`cross_device_ticket_id=${t.ticketId}`);if(!(null==e?void 0:e.ok))throw new C(void 0,null==e?void 0:e.body);return await e.json()}static async startCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new d("Failed to start cross device authentication",null==e?void 0:e.body);return await e.json()}static async startCrossDeviceRegistration(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new p("Failed to start cross device registration",null==e?void 0:e.body);return await e.json()}static async attachDeviceToCrossDeviceSession(t){const e=await this.sendRequest(this._apiPaths.attachDeviceToCrossDeviceSession,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new p("Failed to attach device to cross device session",null==e?void 0:e.body);return await e.json()}static getValidatedClientId(){var t;const e=null!==(t=this._clientId)&&void 0!==t?t:D.get("clientId");if(!e)throw new u("Missing clientId");return e}}var S,T,k,I;_.newApiDomains=["api.idsec-dev.com","api.idsec-stg.com"],function(t){t.InputAutofill="input-autofill",t.Modal="modal"}(S||(S={})),exports.WebauthnCrossDeviceStatus=void 0,(T=exports.WebauthnCrossDeviceStatus||(exports.WebauthnCrossDeviceStatus={})).Pending="pending",T.Scanned="scanned",T.Success="success",T.Error="error",T.Timeout="timeout",T.Aborted="aborted",function(t){t.toAuthenticationError=t=>A(t)?t:"NotAllowedError"===t.name?new h:"OperationError"===t.name?new w(t.message):"SecurityError"===t.name?new d(t.message):t===o.AuthenticationAbortedTimeout?new f:"AbortError"===t.name||t===o.AutofillAuthenticationAborted?new g:new d("Something went wrong during authentication",{error:t}),t.toRegistrationError=t=>A(t)?t:"NotAllowedError"===t.name?new v:"SecurityError"===t.name?new p(t.message):"InvalidStateError"===t.name?new m:t===o.RegistrationAbortedTimeout?new f:new p("Something went wrong during registration",{error:t})}(k||(k={})),function(t){t.processCredentialRequestOptions=t=>r(r({},t),{},{challenge:n.base64ToArrayBuffer(t.challenge),allowCredentials:t.allowCredentials.map((t=>r(r({},t),{},{id:n.base64ToArrayBuffer(t.id)})))}),t.processCredentialCreationOptions=(t,e)=>{var i;const a=JSON.parse(JSON.stringify(t));return a.challenge=n.base64ToArrayBuffer(t.challenge),a.user.id=n.base64ToArrayBuffer(t.user.id),(null==e?void 0:e.limitSingleCredentialToDevice)&&(a.excludeCredentials=null===(i=t.excludeCredentials)||void 0===i?void 0:i.map((t=>r(r({},t),{},{id:n.base64ToArrayBuffer(t.id)})))),(null==e?void 0:e.registerAsDiscoverable)?(a.authenticatorSelection.residentKey="preferred",a.authenticatorSelection.requireResidentKey=!0):(a.authenticatorSelection.residentKey="discouraged",a.authenticatorSelection.requireResidentKey=!1),a.authenticatorSelection.authenticatorAttachment=(null==e?void 0:e.allowCrossPlatformAuthenticators)?void 0:"platform",a},t.encodeAuthenticationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:n.arrayBufferToBase64(t.rawId),response:{authenticatorData:n.arrayBufferToBase64(i.authenticatorData),clientDataJSON:n.arrayBufferToBase64(i.clientDataJSON),signature:n.arrayBufferToBase64(i.signature),userHandle:n.arrayBufferToBase64(i.userHandle)},authenticatorAttachment:e,type:t.type}},t.encodeRegistrationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:n.arrayBufferToBase64(t.rawId),response:{attestationObject:n.arrayBufferToBase64(i.attestationObject),clientDataJSON:n.arrayBufferToBase64(i.clientDataJSON)},authenticatorAttachment:e,type:t.type}}}(I||(I={}));class P{async modal(t){try{const e=await this.performAuthentication(r(r({},t),{},{mediationType:S.Modal}));return n.jsonToBase64(e)}catch(t){throw k.toAuthenticationError(t)}}activateAutofill(t){const{handlers:e,username:i}=t,{onSuccess:a,onError:r,onReady:s}=e;this.performAuthentication({username:i,mediationType:S.InputAutofill,onReady:s}).then((t=>{a(n.jsonToBase64(t))})).catch((t=>{const e=k.toAuthenticationError(t);if(!r)throw e;r(e)}))}abortAutofill(){this.abortController&&this.abortController.abort(o.AutofillAuthenticationAborted)}abortAuthentication(){this.abortController&&this.abortController.abort(o.AuthenticationAbortedTimeout)}async performAuthentication(t){var e,i;const a="crossDeviceTicketId"in t?await _.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await _.startAuthentication({username:t.username,identifier:t.identifier,identifierType:t.identifierType,timeout:null===(e=t.options)||void 0===e?void 0:e.timeout}),r=a.credential_request_options,n=I.processCredentialRequestOptions(r),s=this.getMediatedCredentialRequest(n,t.mediationType);t.mediationType===S.InputAutofill&&(null===(i=t.onReady)||void 0===i||i.call(t));const o=await navigator.credentials.get(s).catch((t=>{throw k.toAuthenticationError(t)}));return{webauthnSessionId:a.webauthn_session_id,publicKeyCredential:I.encodeAuthenticationResult(o),userAgent:navigator.userAgent}}getMediatedCredentialRequest(t,e){const i={publicKey:t};return this.abortController=new AbortController,i.signal=this.abortController&&this.abortController.signal,e===S.InputAutofill?i.mediation="conditional":t.timeout&&setTimeout((()=>{this.abortAuthentication()}),t.timeout),i}}class O{constructor(t,e){this.handler=t,this.intervalInMs=e}begin(){var t;this.intervalId=window.setInterval((t=this.handler,async function(){t.isRunning||(t.isRunning=!0,await t(...arguments),t.isRunning=!1)}),this.intervalInMs)}stop(){clearInterval(this.intervalId)}}const R=/^[A-Za-z0-9\-_.: ]*$/;function j(t){if(t&&(!function(t){return Object.keys(t).length<=10}(t)||!function(t){const e=t=>"string"==typeof t,i=t=>R.test(t);return Object.keys(t).every((a=>e(a)&&e(t[a])&&i(a)&&i(t[a])))}(t)))throw s.error("Failed validating approval data"),new y("Provided approval data should have 10 properties max. Also, it should contain only \n alphanumeric characters, numbers, and the special characters: '-', '_', '.'")}class x{constructor(t,e,i){this.authenticationHandler=t,this.registrationHandler=e,this.approvalHandler=i,this.init={registration:async t=>(this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(t.crossDeviceTicketId,t.handlers)),authentication:async t=>{const{username:e}=t,i=(await _.initCrossDeviceAuthentication(r({},e&&{username:e}))).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(i,t.handlers)},approval:async t=>{const{username:e,approvalData:i}=t;j(i);const a=(await _.initCrossDeviceAuthentication({username:e,approvalData:i})).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(a,t.handlers)}},this.authenticate={modal:async t=>this.authenticationHandler.modal({crossDeviceTicketId:t})},this.approve={modal:async t=>this.approvalHandler.modal({crossDeviceTicketId:t})}}async register(t){return this.registrationHandler.register(t)}async attachDevice(t){const e=await _.attachDeviceToCrossDeviceSession({ticketId:t});return r({status:e.status,startedAt:e.started_at},e.approval_data&&{approvalData:e.approval_data})}async pollCrossDeviceSession(t,e){return this.poller=new O((async()=>{var i,a;const r=await _.getCrossDeviceTicketStatus({ticketId:t}),n=r.status;if(n!==this.ticketStatus)switch(this.ticketStatus=n,n){case exports.WebauthnCrossDeviceStatus.Scanned:await e.onDeviceAttach();break;case exports.WebauthnCrossDeviceStatus.Error:case exports.WebauthnCrossDeviceStatus.Timeout:case exports.WebauthnCrossDeviceStatus.Aborted:await e.onFailure(r),null===(i=this.poller)||void 0===i||i.stop();break;case exports.WebauthnCrossDeviceStatus.Success:if("onCredentialRegister"in e)await e.onCredentialRegister();else{if(!r.session_id)throw new C("Cross device session is complete without returning session_id",r);await e.onCredentialAuthenticate(r.session_id)}null===(a=this.poller)||void 0===a||a.stop()}}),1e3),this.poller.begin(),setTimeout((()=>{var t;null===(t=this.poller)||void 0===t||t.stop(),e.onFailure({status:exports.WebauthnCrossDeviceStatus.Timeout})}),3e5),{crossDeviceTicketId:t,stop:()=>{var t;null===(t=this.poller)||void 0===t||t.stop()}}}}class K{async register(t){var e,i,a;this.abortController=new AbortController;const s=r({allowCrossPlatformAuthenticators:!("crossDeviceTicketId"in t),registerAsDiscoverable:!0},t.options);try{const r="crossDeviceTicketId"in t?await _.startCrossDeviceRegistration({ticketId:t.crossDeviceTicketId}):await _.startRegistration({username:t.username,displayName:(null===(e=t.options)||void 0===e?void 0:e.displayName)||t.username,timeout:null===(i=t.options)||void 0===i?void 0:i.timeout,limitSingleCredentialToDevice:null===(a=t.options)||void 0===a?void 0:a.limitSingleCredentialToDevice}),o=I.processCredentialCreationOptions(r.credential_creation_options,s);setTimeout((()=>{this.abortRegistration()}),o.timeout);const c=await this.registerCredential(o),l={webauthnSessionId:r.webauthn_session_id,publicKeyCredential:c,userAgent:navigator.userAgent};return n.jsonToBase64(l)}catch(t){throw k.toRegistrationError(t)}}abortRegistration(){this.abortController&&this.abortController.abort(o.RegistrationAbortedTimeout)}async registerCredential(t){const e=await navigator.credentials.create({publicKey:t,signal:this.abortController&&this.abortController.signal}).catch((t=>{throw k.toRegistrationError(t)}));return I.encodeRegistrationResult(e)}}class B{async modal(t){try{const e=await this.performApproval(t);return n.jsonToBase64(e)}catch(t){throw k.toAuthenticationError(t)}}async performApproval(t){"approvalData"in t&&j(t.approvalData);const e="crossDeviceTicketId"in t?await _.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await _.startAuthentication({username:t.username,approvalData:t.approvalData}),i=e.credential_request_options,a=I.processCredentialRequestOptions(i),r=await navigator.credentials.get({publicKey:a}).catch((t=>{throw k.toAuthenticationError(t)}));return{webauthnSessionId:e.webauthn_session_id,publicKeyCredential:I.encodeAuthenticationResult(r),userAgent:navigator.userAgent}}}class E{constructor(){this._initialized=!1,this._authenticationHandler=new P,this._registrationHandler=new K,this._approvalHandler=new B,this._crossDeviceHandler=new x(this._authenticationHandler,this._registrationHandler,this._approvalHandler),this.authenticate={modal:async t=>(this.initCheck(),this._authenticationHandler.modal(t)),autofill:{activate:t=>(this.initCheck(),this._authenticationHandler.activateAutofill(t)),abort:()=>this._authenticationHandler.abortAutofill()}},this.approve={modal:async t=>(this.initCheck(),this._approvalHandler.modal(t))},this.register=async t=>(this.initCheck(),this._registrationHandler.register(t)),this.crossDevice={init:{registration:async t=>(this.initCheck(),this._crossDeviceHandler.init.registration(t)),authentication:async t=>(this.initCheck(),this._crossDeviceHandler.init.authentication(t)),approval:async t=>(this.initCheck(),this._crossDeviceHandler.init.approval(t))},authenticate:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.authenticate.modal(t))},approve:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.approve.modal(t))},register:async t=>(this.initCheck(),this._crossDeviceHandler.register(t)),attachDevice:async t=>(this.initCheck(),this._crossDeviceHandler.attachDevice(t))},this.isPlatformAuthenticatorSupported=async()=>{var t;try{return await(null===(t=E.StaticPublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable())}catch(t){return!1}},this.isAutofillSupported=async()=>{var t,e;return!(!(null===(t=E.StaticPublicKeyCredential)||void 0===t?void 0:t.isConditionalMediationAvailable)||!await(null===(e=E.StaticPublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable()))}}async init(t){const{clientId:e,options:i}=t;try{if(!e)throw new u("Invalid clientId",{clientId:e});if(i.webauthnApiPaths){const t=_.getDefaultPaths();if(function(t,e){const i=new Set(t),a=new Set(e);return[...t.filter((t=>!a.has(t))),...e.filter((t=>!i.has(t)))]}(Object.keys(i.webauthnApiPaths),Object.keys(t)).length)throw new u("Invalid custom paths",{customApiPaths:i.webauthnApiPaths})}_.init(e,i),this._initialized=!0}catch(t){throw A(t)?t:new u("Failed to initialize SDK")}}getDefaultPaths(){return this.initCheck(),_.getDefaultPaths()}getApiPaths(){return this.initCheck(),_.getApiPaths()}initCheck(){if(!this._initialized)throw new u}}E.StaticPublicKeyCredential=window.PublicKeyCredential;const N=new t("webauthn"),H=new E;N.events.on(N.events.MODULE_INITIALIZED,(()=>{var t;const e=N.moduleMetadata.getInitConfig();if(!(null===(t=null==e?void 0:e.webauthn)||void 0===t?void 0:t.serverPath))return;const{clientId:i,webauthn:a}=e;H.init({clientId:i,options:r({},a)})}));const W={modal:async t=>(H.initCheck(),H.authenticate.modal(t)),autofill:{activate:t=>{H.initCheck(),H.authenticate.autofill.activate(t)},abort:()=>{H.initCheck(),H.authenticate.autofill.abort()}}},q={modal:async t=>(H.initCheck(),H.approve.modal(t))};async function F(t){return H.initCheck(),H.register(t)}const{crossDevice:M}=H,{isPlatformAuthenticatorSupported:z}=H,{isAutofillSupported:J}=H,{getDefaultPaths:$}=H;window.localWebAuthnSDK=H;var U=Object.freeze({__proto__:null,get WebauthnCrossDeviceStatus(){return exports.WebauthnCrossDeviceStatus},approve:q,authenticate:W,crossDevice:M,getDefaultPaths:$,isAutofillSupported:J,isPlatformAuthenticatorSupported:z,register:F});const V={initialize:e.initialize,...U};Object.defineProperty(exports,"initialize",{enumerable:!0,get:function(){return e.initialize}}),exports.PACKAGE_VERSION="2.3.1",exports.approve=q,exports.authenticate=W,exports.crossDevice=M,exports.getDefaultPaths=$,exports.isAutofillSupported=J,exports.isPlatformAuthenticatorSupported=z,exports.register=F,exports.webauthn=V;