@transmitsecurity/platform-web-sdk 1.18.2 → 2.0.0-beta.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/CHANGELOG.md CHANGED
@@ -1,4 +1,49 @@
1
1
  # Changelog
2
+ ## 2.0.0 - Feb. 01, 2026
3
+ **Fraud Prevention**
4
+ * BREAKING CHANGE: The `serverPath` parameter is now required. In previous versions, it defaulted to the US region. To ensure correct routing to your region, you must update your configuration to include the `serverPath` property as specified in the documentation.
5
+ * BREAKING CHANGE: The DRS module is no longer initialized by default. If your application uses DRS, you must explicitly include the `drs` configuration object in your initialization.
6
+ * BREAKING CHANGE: DRS user identification APIs have been changed:
7
+ - `unidentifiedUser()` → `clearUser()`
8
+ - `identifyUser()` → `setAuthenticatedUser()`
9
+ - `setUser()` → `setAuthenticatedUser()`
10
+
11
+ **Identity Verification**
12
+ * BREAKING CHANGE: The `serverPath` parameter is now required. In previous versions, it defaulted to the US region. To ensure correct routing to your region, you must update your configuration to include the `serverPath` property as specified in the documentation.
13
+
14
+ **Orchestration**
15
+ * feat: Introducing CIAM Secure through IDO journeys
16
+ * feat: IDO module now uses separate typing files. You may need to update imports if your application consumes IDO types.
17
+
18
+ **Webauthn**
19
+ * BREAKING CHANGE: All major SDK methods have been refactored to use a single parameter object pattern instead of multiple positional parameters.
20
+
21
+
22
+ ## 1.20.0 - Jan. 18, 2026
23
+ **Fraud Prevention**
24
+ * Add getSecureSessionToken public method for generating cryptographically signed session tokens
25
+ * Support optional actionType and expirationMinutes parameters in secure session token generation
26
+
27
+ **Orchestration**
28
+ * fix: Update ido-web-sdk to version 0.0.78 - Fix correlationId serialization to persist across external redirects
29
+ * Fixes issue where correlationId was lost during external redirects (e.g., IDV, external IDP)
30
+ * Ensures single correlation_id per invocation_id for consistent tracking
31
+ * Maintains backward compatibility with existing serialized states
32
+
33
+ **Identity Verification**
34
+ * feat: Add document silhouette on front image capture to help users do auto-capture
35
+
36
+ ## 1.19.0 - Dec. 21, 2025
37
+ **Fraud Prevention**
38
+ * feat: Improved mouse movement sampling rate by using Pointer Events API.
39
+ * feat: Improved device identification speed by sending device data immediately.
40
+ * feat: Add current `publicKeyID` tracking for session token injection protection.
41
+
42
+ ## 1.18.3 - Dec. 7, 2025
43
+ **Identity Verification**
44
+ * feat: Use ZXing lib for extraction of barcode data
45
+ * feat: Improve camera selection for capturing documents
46
+ * fix: Stability manager counter issue
2
47
 
3
48
  ## 1.18.2 - Nov. 9, 2025
4
49
  **Identity Verification**
package/README.md CHANGED
@@ -1,100 +1,111 @@
1
1
  # Transmit Security Platform Web SDK
2
2
 
3
- A comprehensive browser-based identity and security solution with fraud prevention, WebAuthn authentication, identity verification, and orchestration capabilities.
3
+
4
+ A JavaScript client SDK offering comprehensive identity and security solution with Fraud prevention, WebAuthn authentication, Identity Verification, and Orchestration capabilities.
4
5
 
5
6
  ## Installation
6
7
 
7
- ### NPM Package (Recommended)
8
+ Installs the latest v2 version:
9
+
8
10
  ```bash
9
- npm install @transmitsecurity/platform-web-sdk
11
+ npm install @transmitsecurity/platform-web-sdk@^2
10
12
  ```
11
- ## Usage Patterns
12
13
 
13
- #### Individual Module Imports (Recommended)
14
- For optimal bundle sizes and performance, import only the modules you need:
14
+ ## Initialization
15
15
 
16
- ```javascript
17
- // Option 1: Individual function imports (best for tree-shaking)
18
- import { triggerActionEvent, setUser, clearUser, initialize } from '@transmitsecurity/platform-web-sdk/drs';
19
- import { isPlatformAuthenticatorSupported, register } from '@transmitsecurity/platform-web-sdk/webauthn';
20
- import { start } from '@transmitsecurity/platform-web-sdk/idv';
16
+ To benefit from tree-shaking, initialize only the modules you need:
21
17
 
22
- // Use modules (syntax depends on import method)
23
- // Option 1: Direct function calls
24
- await triggerActionEvent('login', { correlationId: 'example' });
25
- await setUser({ userId: 'user123' });
26
- const isSupported = await isPlatformAuthenticatorSupported();
18
+ ```javascript
19
+ import { initialize } from '@transmitsecurity/platform-web-sdk';
27
20
 
28
- // Option 2: Namespace calls
29
- await drs.triggerActionEvent('login', { correlationId: 'example' });
30
- await drs.setUser({ userId: 'user123' });
31
- const isSupported = await webauthn.isPlatformAuthenticatorSupported();
21
+ initialize({
22
+ clientId: 'your-client-id',
23
+ drs: {
24
+ serverPath: 'https://api.transmitsecurity.io/risk-collect/', // Required: Set serverPath based on your region or custom domain
25
+ enableSessionToken: true
26
+ },
27
+ ido: {
28
+ serverPath: 'https://api.transmitsecurity.io/ido' // Required: Set serverPath based on your region or custom domain
29
+ },
30
+ idv: {
31
+ serverPath: 'https://api.transmitsecurity.io/verify' // Required: Set serverPath based on your region or custom domain
32
+ },
33
+ webauthn: {
34
+ serverPath: 'https://api.transmitsecurity.io' // Required: Set serverPath based on your region or custom domain
35
+ }
36
+ });
32
37
  ```
33
38
 
39
+ ## Usage Patterns
40
+
41
+ ### Import Functions from Individual Subpaths (Recommended)
42
+
43
+ For optimal bundle sizes and performance, import specific functions from individual subpaths:
44
+
45
+ > The functions shown below are examples only. For the full list of functions in each module, see [SDK reference](https://developer.transmitsecurity.com/sdk-ref/platform/introduction).
34
46
 
35
47
  ```javascript
36
- import { ido, ClientResponseOptionType } from '@transmitsecurity/platform-web-sdk/ido';
37
- import { initialize } from '@transmitsecurity/platform-web-sdk';
48
+ // Individual function imports
49
+ import { triggerActionEvent, setAuthenticatedUser, clearUser, getSessionToken } from '@transmitsecurity/platform-web-sdk/drs';
50
+ import { isPlatformAuthenticatorSupported, register } from '@transmitsecurity/platform-web-sdk/webauthn';
51
+ import { start } from '@transmitsecurity/platform-web-sdk/idv';
52
+ import { startJourney } from '@transmitsecurity/platform-web-sdk/ido';
38
53
 
39
- // Initialize
40
- await initialize({
41
- clientId: 'your-client-id',
42
- ido: { serverPath: 'https://api.transmitsecurity.io' }
43
- });
54
+ // Direct function calls
55
+ await triggerActionEvent('login', { correlationId: 'example' });
56
+ await setAuthenticatedUser('user123');
57
+ await getSessionToken();
58
+ const isSupported = await isPlatformAuthenticatorSupported();
59
+ await startJourney('JOURNEY_ID');
44
60
 
45
- // IDO usage
46
- await ido.startJourney('journey-id');
47
- await ido.submitClientResponse(
48
- ClientResponseOptionType.ClientInput,
49
- { userEmail: 'user@example.com' }
50
- );
51
61
  ```
52
62
 
53
63
  #### TypeScript Support
54
- Full TypeScript support with individual module imports:
64
+ Full TypeScript support with individual imports:
55
65
 
56
66
  ```typescript
57
- import { triggerActionEvent, setUser } from '@transmitsecurity/platform-web-sdk/drs';
67
+ import { triggerActionEvent, setAuthenticatedUser, getSessionToken } from '@transmitsecurity/platform-web-sdk/drs';
58
68
  import { isPlatformAuthenticatorSupported } from '@transmitsecurity/platform-web-sdk/webauthn';
59
69
  import { start } from '@transmitsecurity/platform-web-sdk/idv';
60
- import { ido } from '@transmitsecurity/platform-web-sdk/ido';
61
- import { initialize } from '@transmitsecurity/platform-web-sdk';
62
-
63
- // Initialize with TypeScript types
64
- await initialize({
65
- clientId: 'your-client-id',
66
- drs: { serverPath: 'https://api.transmitsecurity.io/risk-collect/' },
67
- webauthn: { serverPath: 'https://api.transmitsecurity.io' },
68
- idv: { serverPath: 'https://api.transmitsecurity.io' },
69
- ido: {
70
- serverPath: 'https://api.transmitsecurity.io',
71
- }
72
- });
70
+ import { submitClientResponse, ClientResponseOptionType } from '@transmitsecurity/platform-web-sdk/ido';
73
71
 
74
72
  // Use with proper TypeScript types
75
73
  await triggerActionEvent('login', { correlationId: 'example' });
74
+ await getSessionToken();
76
75
  const isSupported: boolean = await isPlatformAuthenticatorSupported();
77
- await ido.default.submitClientResponse(
76
+ await submitClientResponse(
78
77
  ClientResponseOptionType.ClientInput,
79
78
  { userEmail: 'user@example.com' }
80
79
  );
81
80
  ```
82
81
 
83
- #### Full SDK Import (Alternative)
82
+ ### Import Individual Modules
83
+
84
+ To leverage namespace calls, import modules from individual subpaths
85
+
86
+ ```javascript
87
+ // Individual module imports
88
+ import * as drs from '@transmitsecurity/platform-web-sdk/drs';
89
+ import * as ido from '@transmitsecurity/platform-web-sdk/ido';
90
+ import * as idv from '@transmitsecurity/platform-web-sdk/idv';
91
+ import * as webauthn from '@transmitsecurity/platform-web-sdk/webauthn';
92
+
93
+ // Namespace calls
94
+ await drs.triggerActionEvent('login', { correlationId: 'example' });
95
+ await drs.setAuthenticatedUser('user123');
96
+ await drs.getSessionToken();
97
+ const isSupported = await webauthn.isPlatformAuthenticatorSupported();
98
+ await ido.startJourney('journey-id');
99
+ ```
100
+
101
+ ### Import Full SDK (Alternative)
84
102
  If you need multiple modules, you can also import the full SDK:
85
103
 
86
104
  ```javascript
87
105
  import { drs, webauthn, idv, ido, initialize } from '@transmitsecurity/platform-web-sdk';
88
106
 
89
- // Single initialize call for all modules
90
- await initialize({
91
- clientId: 'your-client-id',
92
- drs: { serverPath: 'https://api.transmitsecurity.io/risk-collect/' },
93
- webauthn: { serverPath: 'https://api.transmitsecurity.io' },
94
- idv: { serverPath: 'https://api.transmitsecurity.io' },
95
- ido: { serverPath: 'https://api.transmitsecurity.io' }
96
- });
97
-
98
107
  // Use modules through the main object
99
108
  await drs.triggerActionEvent('login', { correlationId: 'example' });
109
+ await drs.getSessionToken();
110
+ await ido.startJourney('JOURNEY_ID');
100
111
  ```
@@ -0,0 +1 @@
1
+ function e(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){e(n,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(i,e))}))}return n}function r(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function i(e,t){return Object.entries(t).reduce(((t,r)=>{let[s,o]=r;return n(n({},t),{},{[s]:a.isPrototypeOf(o)?new o(e.slug):"function"==typeof o?o.bind(e):"object"==typeof o&&!Array.isArray(o)&&o?i(e,o):o})}),{})}"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self)),Object.defineProperty(exports,"__esModule",{value:!0});class a{constructor(e){this.slug=e}static create(e){return class extends a{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var s=Object.freeze({__proto__:null,Agent:a});const o=new Map;function c(e,t){var n,r;null===(n=o.get(e))||void 0===n||n.forEach((r=e=>e(t),function(){try{return r(...arguments)}catch(e){console.log(e)}}))}const l=Symbol("MODULE_INITIALIZED");var d=Object.freeze({__proto__:null,MODULE_INITIALIZED:l,emit:c,off:function(e,t){const n=o.get(e);if(!n)return;const r=n.indexOf(t);-1!==r&&n.splice(r,1)},on:function(e,t){var n;o.has(e)?null===(n=o.get(e))||void 0===n||n.push(t):o.set(e,[t])}});let y=null;function u(e){y=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return y},get initConfig(){return y},setInitConfig:u});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,a=null==t||t;return n(n({serverPath:i},r(e,f)),{},{enabled:a})}function w(e){const{drs:t}=e;u(n(n({},r(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function K(e,t){const n=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const n=e[t];if(null!==n&&"object"==typeof n&&!Array.isArray(n))return n}const n={};return e[t]=n,n}),n),n]}const v="tsec",m="general";function D(e){return e?m:y.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(v))}function S(e,t){const n=e?sessionStorage:localStorage,r=t(O(e));n.setItem(v,JSON.stringify(r))}var R=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:v,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral),r=O(!!t.sessionOnly),[i]=K(r,[this.slug.toString(),n]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);return function(e,t){let n=e;return t.every((e=>!(!n||"object"!=typeof n||Array.isArray(n)||!(e in n)||(n=n[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),n,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[r,i]=K(t,[this.slug.toString(),n]);return delete r[e],i}))},setValue:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=D(!!n.isGeneral);S(!!n.sessionOnly,(n=>{const[i,a]=K(n,[this.slug.toString(),r]);return i[e]=t,a}))}});const P="RSA-PSS",k=async(e,t)=>await window.crypto.subtle.generateKey({name:e,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,t),x=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),_=async()=>await k(P,["sign"]),j=async(e,t)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:P,saltLength:32},e,n)};class I{constructor(e,t,n){this.slug=e,this.dbName=t,this.dbVersion=n}queryObjectStore(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=r,a=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,s=`${this.slug}:${this.dbName}`,o=a.open(s,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const n=o.result;(null===(t=null==n?void 0:n.objectStoreNames)||void 0===t?void 0:t.contains)&&!n.objectStoreNames.contains(e)&&n.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==r?void 0:r.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(a.deleteDatabase(s).onsuccess=()=>{this.queryObjectStore(e,t,n(n({},r),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.put({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.add({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{const t=e.target.error;i(t)}}))}))}get(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?n(null===(e=i.result)||void 0===e?void 0:e.value):n(void 0)},i.onerror=e=>{r("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.getAll(null,t);i.onsuccess=()=>{if(i.result){const e=i.result;(null==e?void 0:e.length)?n(e.map((e=>null==e?void 0:e.value))):n(e)}else n([])},i.onerror=e=>{r("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{n()},i.onerror=e=>{r(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,n)=>{this.queryObjectStore(e,(e=>{const r=e.clear();r.onsuccess=()=>{t()},r.onerror=e=>{n("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,((e,i)=>{const a=e.transaction;a.onerror=()=>{r(`Transaction failed: ${a.error}`)},a.onabort=()=>{r("Transaction aborted")},a.oncomplete=()=>{i.close(),n()};for(const n of t){let t;if("delete"===n.type)t=e.delete(n.key);else{if("put"!==n.type)return a.abort(),void r("Unknown operation type");t=e.put({key:n.key,value:n.value})}t.onerror=()=>{a.abort(),r(`Operation failed: ${t.error}`)}}}))}))}}const B="init",T="completed",E="RSA2048",N=[B,T];class A{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",n=arguments.length>2?arguments[2]:void 0;var r,i,a,s,o;this.agent=e,this.keysType=t,this.options=n,this._extractingKeysPromise=null;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(a=this.options)||void 0===a?void 0:a.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(s=this.options)||void 0===s?void 0:s.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName;const d=c?"platform":e.slug,y=this.getClientConfiguration(l,d);this.indexedDBClient=new I(y.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new I(y.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${y.clientId}`}}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(e){return window.btoa(String.fromCharCode(...new Uint8Array(e)))}async getPKRepresentations(e){const t=await crypto.subtle.exportKey("spki",e);return{arrayBufferKey:t,base64Key:this.arrayBufferToBase64(t)}}async generateKeyPair(){return"sign"==this.keysType?await _():await x()}async calcKeyIdentifier(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var e,t;const n=(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(n.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=n.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r),n})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:r}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(r);return n(n({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const n=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==n?void 0:n.isEnabled)||!n.expiryDays||void 0===n.startedAt)return!1;const r=24*n.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=n.startedAt?e.createdDate:n.startedAt;return Date.now()-i>r-2592e6}async extractMainKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getKeysRecordKey())}async extractFallbackMainKeysData(){return await this.indexedDBClientFallback.get(this.keysStoreName,this.getKeysRecordKey())}async extractRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKey())}async extractPendingRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKeyPending())}async saveKeyData(e,t){try{return await this.indexedDBClient.add(this.keysStoreName,e,t),t}catch(t){if(t instanceof DOMException&&"ConstraintError"===t.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}throw t}}async getKeysData(){const e=this.getKeysRecordKey();let t=await this.extractMainKeysData();if(t)return t;if(t=await this.extractFallbackMainKeysData(),t)return this.saveKeyData(e,t);const n=await this.generateKeyPairData();return this.saveKeyData(e,n)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),r=await this.getKeysData(),i=n(n({},r),{},{createdDate:r.createdDate||Date.now()});e=await this.saveKeyData(t,i)}return e}async getRotatedKeysData(){const e=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(e)){if(!await this.extractPendingRotatedKeysData()){const t=this.getRotatedKeysRecordKeyPending(),n=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,n)}}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId}}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),n=await j(t,e);return this.arrayBufferToBase64(n)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const e=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,e)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:E,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var e,t;if(!(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const r=await this.extractPendingRotatedKeysData();if(r){const{base64Key:e}=await this.getPKRepresentations(r.publicKey),{privateKey:t}=await this.extractKeysData(),i=n(n({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:r.createdDate,newPublicKeyType:E}),a=JSON.stringify(i);return{data:a,signature:await this.signPayload(a,t)}}const i=await this.extractRotatedKeysData();if(i&&!1===i.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,i.privateKey)}}}async signPayload(e,t){const n=await j(t,e);return this.arrayBufferToBase64(n)}async handleRotateResponse(e){if(N.includes(e))if(e===B){const e=await this.extractPendingRotatedKeysData();if(e){const t=n(n({},e),{},{confirmed:!1});await this.indexedDBClient.executeTransaction(this.keysStoreName,[{type:"delete",key:this.getRotatedKeysRecordKey()},{type:"put",key:this.getRotatedKeysRecordKey(),value:t},{type:"delete",key:this.getRotatedKeysRecordKeyPending()}]);const{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r)}}else if(e===T){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),n(n({},e),{},{confirmed:!0}))}}}var C=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:T,INIT_ROTATION_RESPONSE:B,createCryptoBinding:function(){return new A(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:x,generateRSASignKeyPair:_,signAssymetric:j,verifyAssymetric:async(e,t,n)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,n,r)}}),$=Object.freeze({__proto__:null});const L=a.create((e=>{class t extends Error{constructor(t,n){super(`${e.slug}-${t} ${n}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var M=a.create((()=>n({exceptions:L},s)));class z{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=e,this.middlewares=t,this.logs=[]}info(e,t){this.pushLog(3,e,t)}warn(e,t){this.pushLog(4,e,t)}error(e,t){this.pushLog(5,e,t)}pushLog(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:n,message:t});const r=this.middlewares.map((e=>e(this)));Promise.all(r).catch((()=>{}))}}var U=Object.freeze({__proto__:null,consoleMiddleware:function(e){const t=e.logs[e.logs.length-1];console.log(`${t.severity} ${t.message}`,t.fields)},createSdkLogger:function(){return new z(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])}});function V(e,t){if(!(null==e?void 0:e.trim()))return"";if(function(e){try{return new URL(e),!0}catch(e){return!1}}(e))return e;const n="http://mock.com",r=new URL(n);r.search=(null==t?void 0:t.toString())||"",r.pathname=e;return r.href.replace(n,"")}const q={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function F(e,t,r){var i;const a=(s=t||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:e,headers:n(n(n({},{"X-TS-body-size":String(a)}),q),r||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,n,r,i){const a=V(e,r),s=F(t,n,i);return fetch(a,s)}async function J(e,t,n,r,i){let a;if(a=await G(e,t,n,r,i),!a.ok)throw new Error("Request failed");return a}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const r=await J(e,"DELETE",void 0,void 0,t);return n(n({data:await r.json()},r),{},{headers:r.headers})},httpGet:async function(e,t,r){const i=await J(e,"GET",void 0,t,r);return n(n({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,r,i){const a=await J(e,"POST",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},httpPut:async function(e,t,r,i){const a=await J(e,"PUT",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},init:F}),H=a.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:M,storage:R,crypto:C,indexedDB:$,logger:U,http:X})));exports.PACKAGE_VERSION="2.0.0-beta.0",exports.default=H,exports.initialize=w;
@@ -0,0 +1,11 @@
1
+ declare module './events' {
2
+ interface eventNameToDataParam {
3
+ [MODULE_INITIALIZED]: undefined;
4
+ }
5
+ }
6
+ declare const MODULE_INITIALIZED: unique symbol;
7
+
8
+ declare const PACKAGE_VERSION: string;
9
+ declare function initialize(config: any): void;
10
+
11
+ export { PACKAGE_VERSION, initialize };
package/dist/common.js ADDED
@@ -0,0 +1 @@
1
+ function e(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){e(n,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(i,e))}))}return n}function r(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function i(e,t){return Object.entries(t).reduce(((t,r)=>{let[s,o]=r;return n(n({},t),{},{[s]:a.isPrototypeOf(o)?new o(e.slug):"function"==typeof o?o.bind(e):"object"==typeof o&&!Array.isArray(o)&&o?i(e,o):o})}),{})}"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));class a{constructor(e){this.slug=e}static create(e){return class extends a{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var s=Object.freeze({__proto__:null,Agent:a});const o=new Map;function c(e,t){var n,r;null===(n=o.get(e))||void 0===n||n.forEach((r=e=>e(t),function(){try{return r(...arguments)}catch(e){console.log(e)}}))}const l=Symbol("MODULE_INITIALIZED");var d=Object.freeze({__proto__:null,MODULE_INITIALIZED:l,emit:c,off:function(e,t){const n=o.get(e);if(!n)return;const r=n.indexOf(t);-1!==r&&n.splice(r,1)},on:function(e,t){var n;o.has(e)?null===(n=o.get(e))||void 0===n||n.push(t):o.set(e,[t])}});let y=null;function u(e){y=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return y},get initConfig(){return y},setInitConfig:u});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,a=null==t||t;return n(n({serverPath:i},r(e,f)),{},{enabled:a})}function w(e){const{drs:t}=e;u(n(n({},r(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function K(e,t){const n=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const n=e[t];if(null!==n&&"object"==typeof n&&!Array.isArray(n))return n}const n={};return e[t]=n,n}),n),n]}const v="tsec",m="general";function D(e){return e?m:y.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(v))}function S(e,t){const n=e?sessionStorage:localStorage,r=t(O(e));n.setItem(v,JSON.stringify(r))}var R=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:v,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral),r=O(!!t.sessionOnly),[i]=K(r,[this.slug.toString(),n]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);return function(e,t){let n=e;return t.every((e=>!(!n||"object"!=typeof n||Array.isArray(n)||!(e in n)||(n=n[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),n,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[r,i]=K(t,[this.slug.toString(),n]);return delete r[e],i}))},setValue:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=D(!!n.isGeneral);S(!!n.sessionOnly,(n=>{const[i,a]=K(n,[this.slug.toString(),r]);return i[e]=t,a}))}});const P="RSA-PSS",k=async(e,t)=>await window.crypto.subtle.generateKey({name:e,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,t),x=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),_=async()=>await k(P,["sign"]),j=async(e,t)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:P,saltLength:32},e,n)};class I{constructor(e,t,n){this.slug=e,this.dbName=t,this.dbVersion=n}queryObjectStore(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=r,a=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,s=`${this.slug}:${this.dbName}`,o=a.open(s,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const n=o.result;(null===(t=null==n?void 0:n.objectStoreNames)||void 0===t?void 0:t.contains)&&!n.objectStoreNames.contains(e)&&n.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==r?void 0:r.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(a.deleteDatabase(s).onsuccess=()=>{this.queryObjectStore(e,t,n(n({},r),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.put({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.add({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{const t=e.target.error;i(t)}}))}))}get(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?n(null===(e=i.result)||void 0===e?void 0:e.value):n(void 0)},i.onerror=e=>{r("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.getAll(null,t);i.onsuccess=()=>{if(i.result){const e=i.result;(null==e?void 0:e.length)?n(e.map((e=>null==e?void 0:e.value))):n(e)}else n([])},i.onerror=e=>{r("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{n()},i.onerror=e=>{r(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,n)=>{this.queryObjectStore(e,(e=>{const r=e.clear();r.onsuccess=()=>{t()},r.onerror=e=>{n("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,((e,i)=>{const a=e.transaction;a.onerror=()=>{r(`Transaction failed: ${a.error}`)},a.onabort=()=>{r("Transaction aborted")},a.oncomplete=()=>{i.close(),n()};for(const n of t){let t;if("delete"===n.type)t=e.delete(n.key);else{if("put"!==n.type)return a.abort(),void r("Unknown operation type");t=e.put({key:n.key,value:n.value})}t.onerror=()=>{a.abort(),r(`Operation failed: ${t.error}`)}}}))}))}}const B="init",T="completed",E="RSA2048",N=[B,T];class A{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",n=arguments.length>2?arguments[2]:void 0;var r,i,a,s,o;this.agent=e,this.keysType=t,this.options=n,this._extractingKeysPromise=null;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(a=this.options)||void 0===a?void 0:a.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(s=this.options)||void 0===s?void 0:s.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName;const d=c?"platform":e.slug,y=this.getClientConfiguration(l,d);this.indexedDBClient=new I(y.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new I(y.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${y.clientId}`}}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(e){return window.btoa(String.fromCharCode(...new Uint8Array(e)))}async getPKRepresentations(e){const t=await crypto.subtle.exportKey("spki",e);return{arrayBufferKey:t,base64Key:this.arrayBufferToBase64(t)}}async generateKeyPair(){return"sign"==this.keysType?await _():await x()}async calcKeyIdentifier(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var e,t;const n=(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(n.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=n.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r),n})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:r}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(r);return n(n({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const n=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==n?void 0:n.isEnabled)||!n.expiryDays||void 0===n.startedAt)return!1;const r=24*n.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=n.startedAt?e.createdDate:n.startedAt;return Date.now()-i>r-2592e6}async extractMainKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getKeysRecordKey())}async extractFallbackMainKeysData(){return await this.indexedDBClientFallback.get(this.keysStoreName,this.getKeysRecordKey())}async extractRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKey())}async extractPendingRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKeyPending())}async saveKeyData(e,t){try{return await this.indexedDBClient.add(this.keysStoreName,e,t),t}catch(t){if(t instanceof DOMException&&"ConstraintError"===t.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}throw t}}async getKeysData(){const e=this.getKeysRecordKey();let t=await this.extractMainKeysData();if(t)return t;if(t=await this.extractFallbackMainKeysData(),t)return this.saveKeyData(e,t);const n=await this.generateKeyPairData();return this.saveKeyData(e,n)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),r=await this.getKeysData(),i=n(n({},r),{},{createdDate:r.createdDate||Date.now()});e=await this.saveKeyData(t,i)}return e}async getRotatedKeysData(){const e=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(e)){if(!await this.extractPendingRotatedKeysData()){const t=this.getRotatedKeysRecordKeyPending(),n=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,n)}}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId}}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),n=await j(t,e);return this.arrayBufferToBase64(n)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const e=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,e)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:E,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var e,t;if(!(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const r=await this.extractPendingRotatedKeysData();if(r){const{base64Key:e}=await this.getPKRepresentations(r.publicKey),{privateKey:t}=await this.extractKeysData(),i=n(n({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:r.createdDate,newPublicKeyType:E}),a=JSON.stringify(i);return{data:a,signature:await this.signPayload(a,t)}}const i=await this.extractRotatedKeysData();if(i&&!1===i.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,i.privateKey)}}}async signPayload(e,t){const n=await j(t,e);return this.arrayBufferToBase64(n)}async handleRotateResponse(e){if(N.includes(e))if(e===B){const e=await this.extractPendingRotatedKeysData();if(e){const t=n(n({},e),{},{confirmed:!1});await this.indexedDBClient.executeTransaction(this.keysStoreName,[{type:"delete",key:this.getRotatedKeysRecordKey()},{type:"put",key:this.getRotatedKeysRecordKey(),value:t},{type:"delete",key:this.getRotatedKeysRecordKeyPending()}]);const{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r)}}else if(e===T){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),n(n({},e),{},{confirmed:!0}))}}}var C=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:T,INIT_ROTATION_RESPONSE:B,createCryptoBinding:function(){return new A(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:x,generateRSASignKeyPair:_,signAssymetric:j,verifyAssymetric:async(e,t,n)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,n,r)}}),$=Object.freeze({__proto__:null});const L=a.create((e=>{class t extends Error{constructor(t,n){super(`${e.slug}-${t} ${n}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var M=a.create((()=>n({exceptions:L},s)));class z{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=e,this.middlewares=t,this.logs=[]}info(e,t){this.pushLog(3,e,t)}warn(e,t){this.pushLog(4,e,t)}error(e,t){this.pushLog(5,e,t)}pushLog(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:n,message:t});const r=this.middlewares.map((e=>e(this)));Promise.all(r).catch((()=>{}))}}var U=Object.freeze({__proto__:null,consoleMiddleware:function(e){const t=e.logs[e.logs.length-1];console.log(`${t.severity} ${t.message}`,t.fields)},createSdkLogger:function(){return new z(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])}});function q(e,t){if(!(null==e?void 0:e.trim()))return"";if(function(e){try{return new URL(e),!0}catch(e){return!1}}(e))return e;const n="http://mock.com",r=new URL(n);r.search=(null==t?void 0:t.toString())||"",r.pathname=e;return r.href.replace(n,"")}const F={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function V(e,t,r){var i;const a=(s=t||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:e,headers:n(n(n({},{"X-TS-body-size":String(a)}),F),r||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,n,r,i){const a=q(e,r),s=V(t,n,i);return fetch(a,s)}async function J(e,t,n,r,i){let a;if(a=await G(e,t,n,r,i),!a.ok)throw new Error("Request failed");return a}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const r=await J(e,"DELETE",void 0,void 0,t);return n(n({data:await r.json()},r),{},{headers:r.headers})},httpGet:async function(e,t,r){const i=await J(e,"GET",void 0,t,r);return n(n({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,r,i){const a=await J(e,"POST",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},httpPut:async function(e,t,r,i){const a=await J(e,"PUT",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},init:V}),H=a.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:M,storage:R,crypto:C,indexedDB:$,logger:U,http:X})));const Y="2.0.0-beta.0";export{Y as PACKAGE_VERSION,H as default,w as initialize};