@transmitsecurity/platform-web-sdk 2.3.2-beta-25104222190.0 → 2.3.2-beta-26093939905.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,9 +1,19 @@
1
1
  # Changelog
2
2
 
3
- ## 2.3.0 - May. 10, 2026
3
+ ## 2.3.1 - May. 24, 2026
4
+ **Identity Verification**
5
+ * fix: harden SVG icon rendering against potential XSS
6
+ * fix: separate texts for recapture of autocapture and manual
7
+
8
+ **Webauthn**
9
+ * fix support .idsec-dev.com hostnames as new API domain
4
10
 
5
- **Ido**
6
- startJourney / startSsoJourney Added optional adminDebugToken to StartJourneyOptions and StartSsoJourneyOptions. Pass a token generated from the Mosaic console to attach a specific journey invocation to an active debug session.
11
+ **Orchestration**
12
+ * feat: Add support for new IDV actions, `Selfie Acquisition`, `Document Acquisition` and `Wait For Idv Recommendations`
13
+
14
+ ## 2.3.0 - May. 10, 2026
15
+ **Orchestration**
16
+ * startJourney / startSsoJourney — Added optional adminDebugToken to StartJourneyOptions and StartSsoJourneyOptions. Pass a token generated from the Mosaic console to attach a specific journey invocation to an active debug session.
7
17
 
8
18
  ## 2.2.0 - Apr. 26, 2026
9
19
  **Identity Verification**
@@ -36,7 +46,14 @@ startJourney / startSsoJourney — Added optional adminDebugToken to StartJourne
36
46
  **Fraud Prevention**
37
47
  * feat: Introducing CIAM Secure through IDO journeys
38
48
 
39
- ## 2.0.0 - Feb. 01, 2026
49
+ ## 2.0.1 - Feb. 04, 2026
50
+ **General**
51
+ * fix: Hotfix release addressing issues found in 2.0.0
52
+
53
+ > **Note:** Version 2.0.0 has been deprecated. Please use 2.0.1 or later.
54
+
55
+ ## 2.0.0 - Feb. 01, 2026 ⚠️ DEPRECATED
56
+ > **⚠️ This version is deprecated.** Please upgrade to 2.0.1 or later.
40
57
  **Fraud Prevention**
41
58
  * 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.
42
59
  * 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.
package/dist/common.cjs CHANGED
@@ -1 +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.3.2-beta-25104222190.0",exports.default=H,exports.initialize=w;
1
+ function e(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;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:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?t(Object(i),!0).forEach((function(t){e(r,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(i,e))}))}return r}function n(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n<s.length;n++)r=s[n],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function i(e,t){return Object.entries(t).reduce(((t,n)=>{let[a,o]=n;return r(r({},t),{},{[a]:s.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 s{constructor(e){this.slug=e}static create(e){return class extends s{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var a=Object.freeze({__proto__:null,Agent:s});const o=new Map;function c(e,t){var r,n;null===(r=o.get(e))||void 0===r||r.forEach((n=e=>e(t),function(){try{return n(...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 r=o.get(e);if(!r)return;const n=r.indexOf(t);-1!==n&&r.splice(n,1)},on:function(e,t){var r;o.has(e)?null===(r=o.get(e))||void 0===r||r.push(t):o.set(e,[t])}});let u=null;function y(e){u=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return u},get initConfig(){return u},setInitConfig:y});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,s=null==t||t;return r(r({serverPath:i},n(e,f)),{},{enabled:s})}function w(e){const{drs:t}=e;y(r(r({},n(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function v(e,t){const r=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const r=e[t];if(null!==r&&"object"==typeof r&&!Array.isArray(r))return r}const r={};return e[t]=r,r}),r),r]}const K="tsec",m="general";function D(e){return e?m:u.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(K))}function S(e,t){const r=e?sessionStorage:localStorage,n=t(O(e));r.setItem(K,JSON.stringify(n))}var P=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:K,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=D(!!t.isGeneral),n=O(!!t.sessionOnly),[i]=v(n,[this.slug.toString(),r]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=D(!!t.isGeneral);return function(e,t){let r=e;return t.every((e=>!(!r||"object"!=typeof r||Array.isArray(r)||!(e in r)||(r=r[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),r,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[n,i]=v(t,[this.slug.toString(),r]);return delete n[e],i}))},setValue:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=D(!!r.isGeneral);S(!!r.sessionOnly,(r=>{const[i,s]=v(r,[this.slug.toString(),n]);return i[e]=t,s}))}});const R="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),_=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),x=async()=>await k(R,["sign"]),I=async(e,t)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:R,saltLength:32},e,r)};class j extends Error{constructor(){super("IDB transaction timed out"),this.name="IDBWriteTimeoutError"}}class B{constructor(e,t,r){this.slug=e,this.dbName=t,this.dbVersion=r}queryObjectStore(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=n,s=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,a=`${this.slug}:${this.dbName}`,o=s.open(a,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const r=o.result;(null===(t=null==r?void 0:r.objectStoreNames)||void 0===t?void 0:t.contains)&&!r.objectStoreNames.contains(e)&&r.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==n?void 0:n.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(s.deleteDatabase(a).onsuccess=()=>{this.queryObjectStore(e,t,r(r({},n),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,r){return new Promise(((n,i)=>{this.queryObjectStore(e,(e=>{const s=e.put({key:t,value:r});s.onsuccess=()=>{n(s.result)},s.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,r,n){const i=new Promise(((n,i)=>{this.queryObjectStore(e,(e=>{const s=e.add({key:t,value:r});s.onsuccess=()=>{n(s.result)},s.onerror=e=>{const t=e.target.error;i(t)}}))}));if(void 0===n||isNaN(n))return i;const s=new Promise(((e,t)=>setTimeout((()=>t(new j)),n)));return Promise.race([i,s])}get(e,t){return new Promise(((r,n)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?r(null===(e=i.result)||void 0===e?void 0:e.value):r(void 0)},i.onerror=e=>{n("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((r,n)=>{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)?r(e.map((e=>null==e?void 0:e.value))):r(e)}else r([])},i.onerror=e=>{n("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((r,n)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{r()},i.onerror=e=>{n(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,r)=>{this.queryObjectStore(e,(e=>{const n=e.clear();n.onsuccess=()=>{t()},n.onerror=e=>{r("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((r,n)=>{this.queryObjectStore(e,((e,i)=>{const s=e.transaction;s.onerror=()=>{n(`Transaction failed: ${s.error}`)},s.onabort=()=>{n("Transaction aborted")},s.oncomplete=()=>{i.close(),r()};for(const r of t){let t;if("delete"===r.type)t=e.delete(r.key);else{if("put"!==r.type)return s.abort(),void n("Unknown operation type");t=e.put({key:r.key,value:r.value})}t.onerror=()=>{s.abort(),n(`Operation failed: ${t.error}`)}}}))}))}}const E="init",T="completed",N="RSA2048",A=[E,T];class C{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",r=arguments.length>2?arguments[2]:void 0;var n,i,s,a,o;this.agent=e,this.keysType=t,this.options=r,this._extractingKeysPromise=null,this.cryptoBindingErrors=[];const c=!(null===(n=this.options)||void 0===n?void 0:n.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(a=this.options)||void 0===a?void 0:a.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,u=this.getClientConfiguration(l,d);this.indexedDBClient=new B(u.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(u.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${u.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 x():await _()}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 r=(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:n,base64Key:i}=await this.getPKRepresentations(r.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=r.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(n),r})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:n}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(n);return r(r({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const r=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==r?void 0:r.isEnabled)||!r.expiryDays||void 0===r.startedAt)return!1;const n=24*r.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=r.startedAt?e.createdDate:r.startedAt;return Date.now()-i>n-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){var r;try{return await this.indexedDBClient.add(this.keysStoreName,e,t,null===(r=this.options)||void 0===r?void 0:r.idbWriteTimeoutMs),t}catch(r){if(r instanceof DOMException&&"ConstraintError"===r.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}if(r instanceof j)return this.cryptoBindingErrors.push("IDB_WRITE_TIMEOUT"),t;throw r}}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 r=await this.generateKeyPairData();return this.saveKeyData(e,r)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),n=await this.getKeysData(),i=r(r({},n),{},{createdDate:n.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(),r=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,r)}}return e}async getPublicData(){this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const e={publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId};return this.cryptoBindingErrors.length>0&&(e.errors=this.cryptoBindingErrors),e}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),r=await I(t,e);return this.arrayBufferToBase64(r)}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:N,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 n=await this.extractPendingRotatedKeysData();if(n){const{base64Key:e}=await this.getPKRepresentations(n.publicKey),{privateKey:t}=await this.extractKeysData(),i=r(r({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:n.createdDate,newPublicKeyType:N}),s=JSON.stringify(i);return{data:s,signature:await this.signPayload(s,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 r=await I(t,e);return this.arrayBufferToBase64(r)}async handleRotateResponse(e){if(A.includes(e))if(e===E){const e=await this.extractPendingRotatedKeysData();if(e){const t=r(r({},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:n,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(n)}}else if(e===T){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),r(r({},e),{},{confirmed:!0}))}}}var M=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:T,INIT_ROTATION_RESPONSE:E,createCryptoBinding:function(){return new C(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:_,generateRSASignKeyPair:x,signAssymetric:I,verifyAssymetric:async(e,t,r)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(R,e,r,n)}}),$=Object.freeze({__proto__:null,IDBWriteTimeoutError:j});const L=s.create((e=>{class t extends Error{constructor(t,r){super(`${e.slug}-${t} ${r}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var z=s.create((()=>r({exceptions:L},a)));class U{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 r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:r,message:t});const n=this.middlewares.map((e=>e(this)));Promise.all(n).catch((()=>{}))}}var V=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 U(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 r="http://mock.com",n=new URL(r);n.search=(null==t?void 0:t.toString())||"",n.pathname=e;return n.href.replace(r,"")}function F(e,t,n){var i;const s=(a=t||{},encodeURI(JSON.stringify(a)).split(/%..|./).length-1);var a;return{method:e,headers:r({"X-TS-body-size":String(s),"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":"undefined"!=typeof navigator?navigator.userAgent:""},n||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,r,n,i){const s=q(e,n),a=F(t,r,i);return fetch(s,a)}async function J(e,t,r,n,i){let s;if(s=await G(e,t,r,n,i),!s.ok)throw new Error("Request failed");return s}var W=Object.freeze({__proto__:null,httpDelete:async function(e,t){const n=await J(e,"DELETE",void 0,void 0,t);return r(r({data:await n.json()},n),{},{headers:n.headers})},httpGet:async function(e,t,n){const i=await J(e,"GET",void 0,t,n);return r(r({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,n,i){const s=await J(e,"POST",t,n,i);return r(r({data:await s.json()},s),{},{headers:s.headers})},httpPut:async function(e,t,n,i){const s=await J(e,"PUT",t,n,i);return r(r({data:await s.json()},s),{},{headers:s.headers})},init:F}),X=s.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:z,storage:P,crypto:M,indexedDB:$,logger:V,http:W})));exports.PACKAGE_VERSION="2.3.2-beta-26093939905.0",exports.default=X,exports.initialize=w;
package/dist/common.js CHANGED
@@ -1 +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.3.2-beta-25104222190.0";export{Y as PACKAGE_VERSION,H as default,w as initialize};
1
+ function e(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;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:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function r(r){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?t(Object(i),!0).forEach((function(t){e(r,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(i,e))}))}return r}function n(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(-1!==t.indexOf(n))continue;r[n]=e[n]}return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n<s.length;n++)r=s[n],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function i(e,t){return Object.entries(t).reduce(((t,n)=>{let[a,o]=n;return r(r({},t),{},{[a]:s.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 s{constructor(e){this.slug=e}static create(e){return class extends s{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var a=Object.freeze({__proto__:null,Agent:s});const o=new Map;function c(e,t){var r,n;null===(r=o.get(e))||void 0===r||r.forEach((n=e=>e(t),function(){try{return n(...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 r=o.get(e);if(!r)return;const n=r.indexOf(t);-1!==n&&r.splice(n,1)},on:function(e,t){var r;o.has(e)?null===(r=o.get(e))||void 0===r||r.push(t):o.set(e,[t])}});let u=null;function y(e){u=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return u},get initConfig(){return u},setInitConfig:y});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,s=null==t||t;return r(r({serverPath:i},n(e,f)),{},{enabled:s})}function w(e){const{drs:t}=e;y(r(r({},n(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function v(e,t){const r=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const r=e[t];if(null!==r&&"object"==typeof r&&!Array.isArray(r))return r}const r={};return e[t]=r,r}),r),r]}const K="tsec",m="general";function D(e){return e?m:u.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(K))}function S(e,t){const r=e?sessionStorage:localStorage,n=t(O(e));r.setItem(K,JSON.stringify(n))}var R=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:K,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=D(!!t.isGeneral),n=O(!!t.sessionOnly),[i]=v(n,[this.slug.toString(),r]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=D(!!t.isGeneral);return function(e,t){let r=e;return t.every((e=>!(!r||"object"!=typeof r||Array.isArray(r)||!(e in r)||(r=r[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),r,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[n,i]=v(t,[this.slug.toString(),r]);return delete n[e],i}))},setValue:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=D(!!r.isGeneral);S(!!r.sessionOnly,(r=>{const[i,s]=v(r,[this.slug.toString(),n]);return i[e]=t,s}))}});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),_=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),x=async()=>await k(P,["sign"]),I=async(e,t)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:P,saltLength:32},e,r)};class j extends Error{constructor(){super("IDB transaction timed out"),this.name="IDBWriteTimeoutError"}}class B{constructor(e,t,r){this.slug=e,this.dbName=t,this.dbVersion=r}queryObjectStore(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=n,s=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,a=`${this.slug}:${this.dbName}`,o=s.open(a,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const r=o.result;(null===(t=null==r?void 0:r.objectStoreNames)||void 0===t?void 0:t.contains)&&!r.objectStoreNames.contains(e)&&r.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==n?void 0:n.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(s.deleteDatabase(a).onsuccess=()=>{this.queryObjectStore(e,t,r(r({},n),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,r){return new Promise(((n,i)=>{this.queryObjectStore(e,(e=>{const s=e.put({key:t,value:r});s.onsuccess=()=>{n(s.result)},s.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,r,n){const i=new Promise(((n,i)=>{this.queryObjectStore(e,(e=>{const s=e.add({key:t,value:r});s.onsuccess=()=>{n(s.result)},s.onerror=e=>{const t=e.target.error;i(t)}}))}));if(void 0===n||isNaN(n))return i;const s=new Promise(((e,t)=>setTimeout((()=>t(new j)),n)));return Promise.race([i,s])}get(e,t){return new Promise(((r,n)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?r(null===(e=i.result)||void 0===e?void 0:e.value):r(void 0)},i.onerror=e=>{n("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((r,n)=>{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)?r(e.map((e=>null==e?void 0:e.value))):r(e)}else r([])},i.onerror=e=>{n("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((r,n)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{r()},i.onerror=e=>{n(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,r)=>{this.queryObjectStore(e,(e=>{const n=e.clear();n.onsuccess=()=>{t()},n.onerror=e=>{r("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((r,n)=>{this.queryObjectStore(e,((e,i)=>{const s=e.transaction;s.onerror=()=>{n(`Transaction failed: ${s.error}`)},s.onabort=()=>{n("Transaction aborted")},s.oncomplete=()=>{i.close(),r()};for(const r of t){let t;if("delete"===r.type)t=e.delete(r.key);else{if("put"!==r.type)return s.abort(),void n("Unknown operation type");t=e.put({key:r.key,value:r.value})}t.onerror=()=>{s.abort(),n(`Operation failed: ${t.error}`)}}}))}))}}const T="init",E="completed",N="RSA2048",A=[T,E];class C{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",r=arguments.length>2?arguments[2]:void 0;var n,i,s,a,o;this.agent=e,this.keysType=t,this.options=r,this._extractingKeysPromise=null,this.cryptoBindingErrors=[];const c=!(null===(n=this.options)||void 0===n?void 0:n.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(a=this.options)||void 0===a?void 0:a.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,u=this.getClientConfiguration(l,d);this.indexedDBClient=new B(u.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(u.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${u.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 x():await _()}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 r=(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:n,base64Key:i}=await this.getPKRepresentations(r.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=r.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(n),r})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:n}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(n);return r(r({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const r=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==r?void 0:r.isEnabled)||!r.expiryDays||void 0===r.startedAt)return!1;const n=24*r.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=r.startedAt?e.createdDate:r.startedAt;return Date.now()-i>n-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){var r;try{return await this.indexedDBClient.add(this.keysStoreName,e,t,null===(r=this.options)||void 0===r?void 0:r.idbWriteTimeoutMs),t}catch(r){if(r instanceof DOMException&&"ConstraintError"===r.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}if(r instanceof j)return this.cryptoBindingErrors.push("IDB_WRITE_TIMEOUT"),t;throw r}}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 r=await this.generateKeyPairData();return this.saveKeyData(e,r)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),n=await this.getKeysData(),i=r(r({},n),{},{createdDate:n.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(),r=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,r)}}return e}async getPublicData(){this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const e={publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId};return this.cryptoBindingErrors.length>0&&(e.errors=this.cryptoBindingErrors),e}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),r=await I(t,e);return this.arrayBufferToBase64(r)}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:N,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 n=await this.extractPendingRotatedKeysData();if(n){const{base64Key:e}=await this.getPKRepresentations(n.publicKey),{privateKey:t}=await this.extractKeysData(),i=r(r({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:n.createdDate,newPublicKeyType:N}),s=JSON.stringify(i);return{data:s,signature:await this.signPayload(s,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 r=await I(t,e);return this.arrayBufferToBase64(r)}async handleRotateResponse(e){if(A.includes(e))if(e===T){const e=await this.extractPendingRotatedKeysData();if(e){const t=r(r({},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:n,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(n)}}else if(e===E){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),r(r({},e),{},{confirmed:!0}))}}}var $=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:E,INIT_ROTATION_RESPONSE:T,createCryptoBinding:function(){return new C(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:_,generateRSASignKeyPair:x,signAssymetric:I,verifyAssymetric:async(e,t,r)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,r,n)}}),L=Object.freeze({__proto__:null,IDBWriteTimeoutError:j});const M=s.create((e=>{class t extends Error{constructor(t,r){super(`${e.slug}-${t} ${r}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var z=s.create((()=>r({exceptions:M},a)));class U{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 r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:r,message:t});const n=this.middlewares.map((e=>e(this)));Promise.all(n).catch((()=>{}))}}var q=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 U(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])}});function F(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 r="http://mock.com",n=new URL(r);n.search=(null==t?void 0:t.toString())||"",n.pathname=e;return n.href.replace(r,"")}function V(e,t,n){var i;const s=(a=t||{},encodeURI(JSON.stringify(a)).split(/%..|./).length-1);var a;return{method:e,headers:r({"X-TS-body-size":String(s),"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":"undefined"!=typeof navigator?navigator.userAgent:""},n||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,r,n,i){const s=F(e,n),a=V(t,r,i);return fetch(s,a)}async function J(e,t,r,n,i){let s;if(s=await G(e,t,r,n,i),!s.ok)throw new Error("Request failed");return s}var W=Object.freeze({__proto__:null,httpDelete:async function(e,t){const n=await J(e,"DELETE",void 0,void 0,t);return r(r({data:await n.json()},n),{},{headers:n.headers})},httpGet:async function(e,t,n){const i=await J(e,"GET",void 0,t,n);return r(r({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,n,i){const s=await J(e,"POST",t,n,i);return r(r({data:await s.json()},s),{},{headers:s.headers})},httpPut:async function(e,t,n,i){const s=await J(e,"PUT",t,n,i);return r(r({data:await s.json()},s),{},{headers:s.headers})},init:V}),X=s.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:z,storage:R,crypto:$,indexedDB:L,logger:q,http:W})));const H="2.3.2-beta-26093939905.0";export{H as PACKAGE_VERSION,X as default,w as initialize};