@transmitsecurity/platform-web-sdk 2.1.4-beta-24499833561.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web-sdk.d.ts CHANGED
@@ -130,10 +130,12 @@ declare namespace storage {
130
130
 
131
131
  declare const INIT_ROTATION_RESPONSE = "init";
132
132
  declare const COMPLETED_ROTATION_RESPONSE = "completed";
133
+ type CryptoKeyInvalidReason = 'IDB_WRITE_TIMEOUT';
133
134
  type CryptoBindingPublicData = {
134
135
  publicKey: string;
135
136
  keyIdentifier: string;
136
137
  publicKeyId: string;
138
+ errors?: CryptoKeyInvalidReason[];
137
139
  };
138
140
  type CryptoBindingRotationPayload = {
139
141
  data: string;
@@ -157,6 +159,9 @@ type CryptoBindingOptions = {
157
159
  startedAt: number;
158
160
  tenantId: string;
159
161
  };
162
+ /** Timeout in milliseconds for IDB write transactions. If not set, no timeout is applied.
163
+ * Use to guard against browsers that silently freeze IDB (e.g. iOS 18.7 WKWebView ephemeral sessions). */
164
+ idbWriteTimeoutMs?: number;
160
165
  /** @internal
161
166
  * Warning! This flag shouldn't be used, it was added temporarily for multi-tenant support.
162
167
  *
@@ -180,6 +185,7 @@ declare class CryptoBinding {
180
185
  private keyIdentifier;
181
186
  private publicKeyId;
182
187
  private _extractingKeysPromise;
188
+ private cryptoBindingErrors;
183
189
  constructor(agent: Agent, keysType?: 'encrypt' | 'sign', options?: CryptoBindingOptions);
184
190
  private getClientConfiguration;
185
191
  private getKeysRecordKey;
@@ -250,11 +256,17 @@ type TransactionOperation = {
250
256
  type: 'delete';
251
257
  key: string;
252
258
  };
259
+ declare class IDBWriteTimeoutError extends Error {
260
+ constructor();
261
+ }
253
262
 
263
+ type indexedDB_IDBWriteTimeoutError = IDBWriteTimeoutError;
264
+ declare const indexedDB_IDBWriteTimeoutError: typeof IDBWriteTimeoutError;
254
265
  type indexedDB_QueryObjectStoreOptions = QueryObjectStoreOptions;
255
266
  type indexedDB_TransactionOperation = TransactionOperation;
256
267
  declare namespace indexedDB {
257
268
  export {
269
+ indexedDB_IDBWriteTimeoutError as IDBWriteTimeoutError,
258
270
  indexedDB_QueryObjectStoreOptions as QueryObjectStoreOptions,
259
271
  indexedDB_TransactionOperation as TransactionOperation,
260
272
  };
@@ -425,6 +437,9 @@ type LightweightPayload = {
425
437
  events: Array<Record<string, unknown>>;
426
438
  };
427
439
 
440
+ type TransactionType = 'purchase' | 'bill_payment' | 'mobile_recharge' | 'money_transfer' | 'credit_transfer' | 'credit_redemption' | 'top_up' | 'withdrawal' | 'investment' | 'loan' | 'refund' | 'other';
441
+ type TransactionMethod = 'bank_account' | 'wire' | 'card' | 'p2p' | 'wallet';
442
+ type AvsMatchLevel = 'none' | 'postal' | 'street' | 'full' | 'unknown';
428
443
  interface ActionResponse {
429
444
  /** The token return by the SDK when the action was reported */
430
445
  actionToken?: string;
@@ -459,19 +474,73 @@ interface ConstructorOptions {
459
474
  interface TransactionData {
460
475
  amount: number;
461
476
  currency: string;
477
+ type?: TransactionType;
478
+ method?: TransactionMethod;
479
+ channelId?: string;
462
480
  reason?: string;
463
481
  transactionDate?: number;
464
482
  payer?: {
465
- name?: string;
483
+ accountId?: string;
484
+ accountNumber?: string;
485
+ accountCountryCode?: string;
466
486
  bankIdentifier?: string;
467
487
  branchIdentifier?: string;
468
- accountNumber?: string;
488
+ name?: string;
489
+ customerTier?: string;
490
+ card?: {
491
+ holderName?: string;
492
+ bin?: string;
493
+ last4?: string;
494
+ };
495
+ billingInfo?: {
496
+ name?: string;
497
+ addressLine1?: string;
498
+ addressLine2?: string;
499
+ city?: string;
500
+ state?: string;
501
+ zipPostalCode?: string;
502
+ country?: string;
503
+ email?: string;
504
+ phone?: string;
505
+ };
469
506
  };
470
507
  payee?: {
471
- name?: string;
508
+ accountId?: string;
509
+ accountNumber?: string;
510
+ accountCountryCode?: string;
472
511
  bankIdentifier?: string;
473
512
  branchIdentifier?: string;
474
- accountNumber?: string;
513
+ name?: string;
514
+ card?: {
515
+ holderName?: string;
516
+ bin?: string;
517
+ last4?: string;
518
+ };
519
+ };
520
+ purchase?: {
521
+ totalItems?: number;
522
+ products: {
523
+ id?: string;
524
+ name?: string;
525
+ amount?: number;
526
+ price?: number;
527
+ }[];
528
+ shippingInfo?: {
529
+ name?: string;
530
+ addressLine1?: string;
531
+ addressLine2?: string;
532
+ city?: string;
533
+ state?: string;
534
+ zipPostalCode?: string;
535
+ country?: string;
536
+ email?: string;
537
+ phone?: string;
538
+ };
539
+ };
540
+ avs?: {
541
+ code?: string;
542
+ provider?: string;
543
+ matchLevel?: AvsMatchLevel;
475
544
  };
476
545
  }
477
546
  interface ActionEventOptions {
@@ -608,15 +677,6 @@ declare class TSAccountProtection {
608
677
  getSecureSessionToken(actionType?: string | null, expirationSeconds?: number): Promise<string>;
609
678
  }
610
679
 
611
- declare module '@transmit-security/web-sdk-common/dist/module-metadata/module-metadata' {
612
- interface initConfigParams {
613
- drs?: InitOptions & ConstructorOptions & {
614
- enabled: boolean;
615
- } & {
616
- clientId?: string;
617
- };
618
- }
619
- }
620
680
  /**
621
681
  * Reports a user action event to the SDK
622
682
  * @param actionType Type of user action event that was predefined in the Transmit Security server
@@ -1342,6 +1402,10 @@ interface StartJourneyOptions {
1342
1402
  * Should client-server communication be double encrypted? Defaults to false.
1343
1403
  */
1344
1404
  encrypted?: boolean;
1405
+ /**
1406
+ * An optional admin debug token to be passed to the Journey.
1407
+ */
1408
+ adminDebugToken?: string;
1345
1409
  }
1346
1410
  /**
1347
1411
  * @interface
@@ -1352,6 +1416,10 @@ interface StartSsoJourneyOptions {
1352
1416
  * Should client-server communication be double encrypted? Defaults to false.
1353
1417
  */
1354
1418
  encrypted?: boolean;
1419
+ /**
1420
+ * An optional admin debug token to be passed to the Journey.
1421
+ */
1422
+ adminDebugToken?: string;
1355
1423
  }
1356
1424
  /**
1357
1425
  * @enum
@@ -1508,7 +1576,7 @@ declare enum IdoServiceResponseType {
1508
1576
  /**
1509
1577
  * @enum
1510
1578
  * @description The enum for the Journey step ID, used when the journey step is a predefined typed action.
1511
- * 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.
1579
+ * The actions that do not use this are "Collect information" and "Login Form" which allow the journey author to define a custom ID.
1512
1580
  * See also {@link IdoServiceResponse.journeyStepId}.
1513
1581
  */
1514
1582
  declare enum IdoJourneyActionType {
@@ -1535,7 +1603,7 @@ declare enum IdoJourneyActionType {
1535
1603
  * }
1536
1604
  * }
1537
1605
  * ```
1538
- * The client response does not need to include any data: `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1606
+ * The client response does not need to include any data: `ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1539
1607
  */
1540
1608
  Information = "action:information",
1541
1609
  /**
@@ -1545,7 +1613,7 @@ declare enum IdoJourneyActionType {
1545
1613
  *
1546
1614
  * The {@link IdoServiceResponse} object does not include any data.
1547
1615
  *
1548
- * The client response does not need to include any data: `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1616
+ * The client response does not need to include any data: `ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1549
1617
  */
1550
1618
  DebugBreak = "action:debug_break",
1551
1619
  /**
@@ -1554,7 +1622,7 @@ declare enum IdoJourneyActionType {
1554
1622
  * The {@link IdoServiceResponse} object includes information that can be presented as a QR to scan by another device.
1555
1623
  * The response will remain the same while the cross session message was not consumed by the journey executed by the other device.
1556
1624
  *
1557
- * The client response does not need to include any data: `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1625
+ * The client response does not need to include any data: `ido.submitClientResponse(ClientResponseOptionType.ClientInput);`
1558
1626
  */
1559
1627
  WaitForAnotherDevice = "action:wait_for_another_device",
1560
1628
  /**
@@ -1582,7 +1650,7 @@ declare enum IdoJourneyActionType {
1582
1650
  /**
1583
1651
  * @description `journeyStepId` for WebAuthn Registration action.
1584
1652
  *
1585
- * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `tsPlatform.webauthn.register()`
1653
+ * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `webauthn.register()`
1586
1654
  * ```json
1587
1655
  * {
1588
1656
  * "data": {
@@ -1594,10 +1662,10 @@ declare enum IdoJourneyActionType {
1594
1662
  * }
1595
1663
  * ```
1596
1664
  *
1597
- * Before responding, activate `tsPlatform.webauthn.register()` to obtain the `webauthn_encoded_result` value.
1665
+ * Before responding, activate `webauthn.register()` to obtain the `webauthn_encoded_result` value.
1598
1666
  * This will present the user with the WebAuthn registration UI. Use the result to send the client response:
1599
1667
  * ```json
1600
- * tsPlatform.ido.submitClientResponse(
1668
+ * ido.submitClientResponse(
1601
1669
  * ClientResponseOptionType.ClientInput,
1602
1670
  * {
1603
1671
  * "webauthn_encoded_result": "<WEBAUTHN_ENCODED_RESULT_FROM_SDK>"
@@ -1606,9 +1674,9 @@ declare enum IdoJourneyActionType {
1606
1674
  */
1607
1675
  WebAuthnRegistration = "action:webauthn_registration",
1608
1676
  /**
1609
- * @description `journeyStepId` for instructing the use of DRS trigger action, as part of the Risk Recommendation journey step.
1677
+ * @description `journeyStepId` for instructing the use of Fraud Prevention trigger action, as part of the Risk Recommendation journey step.
1610
1678
  *
1611
- * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `tsPlatform.drs.triggerActionEvent()`
1679
+ * Data received in the {@link IdoServiceResponse} object: the input parameters that you need to send to `drs.triggerActionEvent()`
1612
1680
  * ```json
1613
1681
  * {
1614
1682
  * "data": {
@@ -1618,13 +1686,13 @@ declare enum IdoJourneyActionType {
1618
1686
  * },
1619
1687
  * }
1620
1688
  * ```
1621
- * Before responding, activate `tsPlatform.drs.triggerActionEvent()` to obtain the `action_token` value. This is a silent action, and does not require user interaction.
1689
+ * Before responding, activate `drs.triggerActionEvent()` to obtain the `action_token` value. This is a silent action, and does not require user interaction.
1622
1690
  * Use the result to send the client response:
1623
1691
  * ```json
1624
- * tsPlatform.ido.submitClientResponse(
1692
+ * ido.submitClientResponse(
1625
1693
  * ClientResponseOptionType.ClientInput,
1626
1694
  * {
1627
- * "action_token": "<DRS action token>"
1695
+ * "action_token": "<Fraud Prevention action token>"
1628
1696
  * })
1629
1697
  * ```
1630
1698
  */
@@ -1647,12 +1715,12 @@ declare enum IdoJourneyActionType {
1647
1715
  * }
1648
1716
  * ```
1649
1717
  * Use this data to redirect the user to the identity verification endpoint.
1650
- * 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.
1651
- * 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.
1718
+ * 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.
1719
+ * 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.
1652
1720
  *
1653
1721
  * Once done, send the following client response:
1654
1722
  * ```json
1655
- * tsPlatform.ido.submitClientResponse(
1723
+ * ido.submitClientResponse(
1656
1724
  * ClientResponseOptionType.ClientInput,
1657
1725
  * {
1658
1726
  * "payload": {
@@ -1685,7 +1753,7 @@ declare enum IdoJourneyActionType {
1685
1753
  *
1686
1754
  * - For simple submit of OTP passcode:
1687
1755
  * ```json
1688
- * tsPlatform.ido.submitClientResponse(
1756
+ * ido.submitClientResponse(
1689
1757
  * ClientResponseOptionType.ClientInput,
1690
1758
  * {
1691
1759
  * "passcode": "<passcode>"
@@ -1693,7 +1761,7 @@ declare enum IdoJourneyActionType {
1693
1761
  * ```
1694
1762
  *
1695
1763
  * - In Order to request resend of OTP (restart the action):
1696
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1764
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1697
1765
  *
1698
1766
  */
1699
1767
  EmailOTPAuthentication = "transmit_platform_email_otp_authentication",
@@ -1719,7 +1787,7 @@ declare enum IdoJourneyActionType {
1719
1787
  *
1720
1788
  * - For simple submit of OTP passcode:
1721
1789
  * ```json
1722
- * tsPlatform.ido.submitClientResponse(
1790
+ * ido.submitClientResponse(
1723
1791
  * ClientResponseOptionType.ClientInput,
1724
1792
  * {
1725
1793
  * "passcode": "<passcode>"
@@ -1727,7 +1795,7 @@ declare enum IdoJourneyActionType {
1727
1795
  * ```
1728
1796
  *
1729
1797
  * - In Order to request resend of OTP (restart the action):
1730
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1798
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1731
1799
  *
1732
1800
  */
1733
1801
  SmsOTPAuthentication = "transmit_platform_sms_otp_authentication",
@@ -1753,7 +1821,7 @@ declare enum IdoJourneyActionType {
1753
1821
  *
1754
1822
  * - For simple submit of OTP passcode:
1755
1823
  * ```json
1756
- * tsPlatform.ido.submitClientResponse(
1824
+ * ido.submitClientResponse(
1757
1825
  * ClientResponseOptionType.ClientInput,
1758
1826
  * {
1759
1827
  * "passcode": "<passcode>"
@@ -1761,7 +1829,7 @@ declare enum IdoJourneyActionType {
1761
1829
  * ```
1762
1830
  *
1763
1831
  * - In Order to request resend of OTP (restart the action):
1764
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1832
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1765
1833
  *
1766
1834
  */
1767
1835
  GenericOTPAuthentication = "transmit_platform_generic_otp_authentication",
@@ -1783,7 +1851,7 @@ declare enum IdoJourneyActionType {
1783
1851
  * The user should use this to register the TOTP secret in their authenticator app.
1784
1852
  * Once the user has completed the registration, send the following empty client response:
1785
1853
  * ```json
1786
- * tsPlatform.ido.submitClientResponse(
1854
+ * ido.submitClientResponse(
1787
1855
  * ClientResponseOptionType.ClientInput
1788
1856
  * )
1789
1857
  * ```
@@ -1812,7 +1880,7 @@ declare enum IdoJourneyActionType {
1812
1880
  *
1813
1881
  * - For simple submit of validation passcode:
1814
1882
  * ```json
1815
- * tsPlatform.ido.submitClientResponse(
1883
+ * ido.submitClientResponse(
1816
1884
  * ClientResponseOptionType.ClientInput,
1817
1885
  * {
1818
1886
  * "passcode": "<passcode>"
@@ -1820,7 +1888,7 @@ declare enum IdoJourneyActionType {
1820
1888
  * ```
1821
1889
  *
1822
1890
  * - In Order to request resend of OTP (restart the action):
1823
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1891
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1824
1892
  *
1825
1893
  */
1826
1894
  EmailValidation = "transmit_platform_email_validation",
@@ -1845,7 +1913,7 @@ declare enum IdoJourneyActionType {
1845
1913
  *
1846
1914
  * - For simple submit of validation passcode:
1847
1915
  * ```json
1848
- * tsPlatform.ido.submitClientResponse(
1916
+ * ido.submitClientResponse(
1849
1917
  * ClientResponseOptionType.ClientInput,
1850
1918
  * {
1851
1919
  * "passcode": "<passcode>"
@@ -1853,7 +1921,7 @@ declare enum IdoJourneyActionType {
1853
1921
  * ```
1854
1922
  *
1855
1923
  * - In Order to request resend of OTP (restart the action):
1856
- * `tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)`
1924
+ * `ido.submitClientResponse(ClientResponseOptionType.Resend)`
1857
1925
  *
1858
1926
  */
1859
1927
  SmsValidation = "transmit_platform_sms_validation",
@@ -1882,7 +1950,7 @@ declare enum IdoJourneyActionType {
1882
1950
  *
1883
1951
  * - For submitting the TOTP code:
1884
1952
  * ```json
1885
- * tsPlatform.ido.submitClientResponse(
1953
+ * ido.submitClientResponse(
1886
1954
  * ClientResponseOptionType.ClientInput,
1887
1955
  * {
1888
1956
  * "totp_code": "<6_DIGIT_TOTP_CODE>"
@@ -1915,7 +1983,7 @@ declare enum IdoJourneyActionType {
1915
1983
  *
1916
1984
  * Once done, send the following client response:
1917
1985
  * ```json
1918
- * tsPlatform.ido.submitClientResponse(
1986
+ * ido.submitClientResponse(
1919
1987
  * ClientResponseOptionType.ClientInput,
1920
1988
  * {
1921
1989
  * "idp_response" : {
@@ -1946,16 +2014,16 @@ declare enum IdoJourneyActionType {
1946
2014
  * }
1947
2015
  * }
1948
2016
  * ```
1949
- * Before responding, call `tsPlatform.webauthn.approve.modal()` to obtain the `webauthn_encoded_result` value.
2017
+ * Before responding, call `webauthn.approve.modal()` to obtain the `webauthn_encoded_result` value.
1950
2018
  * ```javascript
1951
- * const result = await tsPlatform.webauthn.approve.modal(
2019
+ * const result = await webauthn.approve.modal(
1952
2020
  * response.data.approval_data // Transaction details to be approved
1953
2021
  * );
1954
2022
  * ```
1955
2023
  *
1956
2024
  * Then submit the result:
1957
2025
  * ```javascript
1958
- * tsPlatform.ido.submitClientResponse(
2026
+ * ido.submitClientResponse(
1959
2027
  * ClientResponseOptionType.ClientInput,
1960
2028
  * {
1961
2029
  * "webauthn_encoded_result": result
@@ -1999,7 +2067,7 @@ declare enum IdoJourneyActionType {
1999
2067
  *
2000
2068
  * For organization selection, send the following client response:
2001
2069
  * ```javascript
2002
- * tsPlatform.ido.submitClientResponse(
2070
+ * ido.submitClientResponse(
2003
2071
  * ClientResponseOptionType.ClientInput,
2004
2072
  * {
2005
2073
  * "organization_id": "<ORGANIZATION_ID>"
@@ -2034,7 +2102,7 @@ declare enum IdoJourneyActionType {
2034
2102
  *
2035
2103
  * For device selection, send the following client response:
2036
2104
  * ```javascript
2037
- * tsPlatform.ido.submitClientResponse(
2105
+ * ido.submitClientResponse(
2038
2106
  * ClientResponseOptionType.ClientInput,
2039
2107
  * {
2040
2108
  * "selected_device_code": "<DEVICE_CODE>"
@@ -2066,17 +2134,17 @@ declare enum IdoJourneyActionType {
2066
2134
  * ```javascript
2067
2135
  * // The application should implement its own polling mechanism
2068
2136
  * // and call this method periodically to check the status
2069
- * tsPlatform.ido.submitClientResponse(ClientResponseOptionType.ClientInput)
2137
+ * ido.submitClientResponse(ClientResponseOptionType.ClientInput)
2070
2138
  * ```
2071
2139
  *
2072
2140
  * - To cancel the authentication:
2073
2141
  * ```javascript
2074
- * tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Cancel)
2142
+ * ido.submitClientResponse(ClientResponseOptionType.Cancel)
2075
2143
  * ```
2076
2144
  *
2077
2145
  * - To resend the push notification:
2078
2146
  * ```javascript
2079
- * tsPlatform.ido.submitClientResponse(ClientResponseOptionType.Resend)
2147
+ * ido.submitClientResponse(ClientResponseOptionType.Resend)
2080
2148
  * ```
2081
2149
  *
2082
2150
  * Note: The application is responsible for implementing the polling mechanism
@@ -2109,7 +2177,7 @@ interface IdoServiceResponse {
2109
2177
  readonly errorData?: IdoSdkError;
2110
2178
  /**
2111
2179
  * @description Contains the Journey step ID, allowing the client side to choose the correct handler and UI.
2112
- * This will be either a form ID for the "Get Information from Client" and "Login Form" journey steps,
2180
+ * This will be either a form ID for the "Collect information" and "Login Form" journey steps,
2113
2181
  * or one of {@link IdoJourneyActionType} for other actions.
2114
2182
  */
2115
2183
  readonly journeyStepId?: IdoJourneyActionType | string;
@@ -2143,7 +2211,8 @@ interface IdoSdk {
2143
2211
  * @throws {@link ErrorCode.InvalidInitOptions} in case of invalid init options.
2144
2212
  * @example
2145
2213
  * // Initialize an instance of the Identity Orchestration SDK using the unified SDK
2146
- * await window.tsPlatform.initialize({
2214
+ * import { initialize } from '@transmitsecurity/platform-web-sdk';
2215
+ * initialize({
2147
2216
  * clientId: 'my-client-id',
2148
2217
  * ido: { serverPath: 'https://api.transmitsecurity.io/ido'}
2149
2218
  * });
@@ -2160,7 +2229,7 @@ interface IdoSdk {
2160
2229
  * @example
2161
2230
  * // Start a Journey with the id 'my-journey-id'
2162
2231
  * try {
2163
- * const idoResponse = await window.tsPlatform.ido.startJourney('my-journey-id', { additionalParams: 'additionalParams' });
2232
+ * const idoResponse = await ido.startJourney('my-journey-id', { additionalParams: 'additionalParams' });
2164
2233
  * // Handle Journey response
2165
2234
  * } catch(error) {
2166
2235
  * switch(sdkError.errorCode) ...
@@ -2177,7 +2246,7 @@ interface IdoSdk {
2177
2246
  * @example
2178
2247
  * // Start a Journey with the Interaction ID '2456E855-05A0-4992-85C1-A2519CBB4AA7'
2179
2248
  * try {
2180
- * const idoResponse = await window.tsPlatform.ido.startSsoJourney('2456E855-05A0-4992-85C1-A2519CBB4AA7');
2249
+ * const idoResponse = await ido.startSsoJourney('2456E855-05A0-4992-85C1-A2519CBB4AA7');
2181
2250
  * // Handle Journey response
2182
2251
  * } catch(error) {
2183
2252
  * switch(sdkError.errorCode) ...
@@ -2206,7 +2275,7 @@ interface IdoSdk {
2206
2275
  *
2207
2276
  * // Submit the client input. The data inside the JSON correspond to the expected fields from the Journey step.
2208
2277
  * try {
2209
- * const idoResponse = await window.tsPlatform.ido.submitClientResponse(selectedInputOption, {
2278
+ * const idoResponse = await ido.submitClientResponse(selectedInputOption, {
2210
2279
  * 'userEmail': 'user@input.email',
2211
2280
  * 'userPhone': '111-222-3333',
2212
2281
  * });
@@ -2223,7 +2292,7 @@ interface IdoSdk {
2223
2292
  serializeState(): string;
2224
2293
  /**
2225
2294
  * @description Restores the SDK state from a serialized state, can be used to recover from page redirects or refresh.
2226
- * The application code also receives the latest communication from the orchestration server.
2295
+ * The application code also receives the latest communication from the Mosaic server.
2227
2296
  * @param state - The state to restore from.
2228
2297
  * @returns The last {@link IdoServiceResponse} that was received before the state was saved.
2229
2298
  * @throws {@link ErrorCode.InvalidState} - Throws error if the provided state string is invalid.
@@ -2231,15 +2300,18 @@ interface IdoSdk {
2231
2300
  restoreFromSerializedState(state: string): IdoServiceResponse;
2232
2301
  /**
2233
2302
  * @description This method will generate a debug PIN
2234
- * const debugPin = await sdk.generateDebugPin();
2235
- * console.log(`Debug PIN: ${debugPin}`); // Output: Debug PIN: 1234
2303
+ * const debugPin = await ido.generateDebugPin();
2304
+ * console.log(`Debug PIN: ${debugPin}`); // Output: Debug PIN: 1234
2236
2305
  */
2237
2306
  generateDebugPin(): Promise<string>;
2238
2307
  }
2239
2308
 
2240
2309
  declare module "@transmit-security/web-sdk-common/dist/module-metadata/module-metadata" {
2241
2310
  interface initConfigParams {
2242
- ido?: IdoInitOptions;
2311
+ ido?: {
2312
+ serverPath?: string;
2313
+ [key: string]: any;
2314
+ };
2243
2315
  }
2244
2316
  }
2245
2317
 
@@ -2316,6 +2388,6 @@ declare class TSWebSDK {
2316
2388
  }
2317
2389
  declare const _default: TSWebSDK;
2318
2390
 
2319
- declare const PACKAGE_VERSION = "2.1.4-beta-24499833561.0";
2391
+ declare const PACKAGE_VERSION = "2.3.0";
2320
2392
 
2321
2393
  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.1.4-beta-24499833561.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 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.3.0",exports.approve=q,exports.authenticate=W,exports.crossDevice=M,exports.getDefaultPaths=$,exports.isAutofillSupported=J,exports.isPlatformAuthenticatorSupported=z,exports.register=F,exports.webauthn=V;