@transmitsecurity/platform-web-sdk 2.6.1 → 2.6.2

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,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.6.2 - Aug. 30, 2026
4
+ **Identity Verification**
5
+ * feat: redesign the auto-capture manual-fallback UX — remove the Auto/Manual toggle; after the per-step timeout, the capture button becomes tappable directly while autocapture keeps running in the background
6
+ * feat: report a manual capture as fallback usage when it's triggered while autocapture is on and the fallback button is showing
7
+ * fix: hold the auto-capture manual-fallback threshold to its original deadline instead of resetting it on every retry, so repeated rejected attempts can no longer push the fallback button's appearance out indefinitely
8
+ * fix: restore the fallback hint after a submission error instead of leaving a generic error message stuck for the rest of the step, and stop treating an error during post-success cleanup as a capture failure
9
+ * fix: give the auto-capture fallback button a screen-reader label
10
+ * fix: restyle the auto-capture fallback spinner as three evenly-spaced rotating arcs, at a calmer rotation speed, and keep its shape fixed while it rotates (could visibly distort on some devices)
11
+ * fix: revert the 2.6.1 behaviour that stopped auto-capture after persistent detection failures — detection again treats a failure as a transient bad frame and keeps retrying
12
+
13
+ **Fraud Prevention**
14
+ * feat: Extended the set of supported challenge types (document_verification, security_question, knowledge_based_authentication, device_approval, out_of_band, otp, device_biometrics, face_id, fingerprint, mobile_approve, pin, cap_rep_token, symantec_token, duo, secure_id, csm, biometric, devicetag_rep_token, email_verification, magic_link, symantec_pin, web_to_mobile).
15
+ * feat: Enriched action and interaction events with further behavioral signs for agentic AI recognition.
16
+
17
+
3
18
  ## 2.6.1 - Aug. 16, 2026
4
19
  **Identity Verification**
5
20
  * fix: prevent the Authorization header from being dropped on session-status requests due to a race condition in header assignment
@@ -10,6 +25,7 @@
10
25
  **Fraud Prevention**
11
26
  * feat: added an `authContext` parameter to `triggerActionEvent`, so callers can pass authentication context for non-authentication actions that occur after a successful login.
12
27
  * chore: the Platform SDK version is now reported on all events, not only action events.
28
+ * fix: resolved an "SDK already initialized" error on re-initialization and when standard and agentic collection run side by side.
13
29
 
14
30
  **Orchestration**
15
31
  * Device registration now captures more accurate device context, such as browser, operating system, and hardware model.
package/dist/common.cjs CHANGED
@@ -1 +1 @@
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 i=r.call(e,t||"default");if("object"!=typeof i)return i;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 i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(r){for(var i=1;i<arguments.length;i++){var n=null!=arguments[i]?arguments[i]:{};i%2?t(Object(n),!0).forEach((function(t){e(r,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(n,e))}))}return r}function i(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)r=s[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function n(e,t){return Object.entries(t).reduce(((t,i)=>{let[a,o]=i;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?n(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,n(this,e(this)))}}}}var a=Object.freeze({__proto__:null,Agent:s});const o=new Map;function c(e,t){var r,i;null===(r=o.get(e))||void 0===r||r.forEach((i=e=>e(t),function(){try{return i(...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 i=r.indexOf(t);-1!==i&&r.splice(i,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 g=["enabled","serverPath"],f=["drs","ido"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:n}=e,s=null==t||t;return r(r({serverPath:n},i(e,g)),{},{enabled:s})}function w(e){const{drs:t,ido:n}=e,s=i(e,f);let a=t;(null==n?void 0:n.collectRiskData)&&(a=r(r({},t),{},{tier:"lightweight"}));y(r(r({},s),{},{ido:n,drs:p(a)})),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,i=t(O(e));r.setItem(K,JSON.stringify(i))}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),i=O(!!t.sessionOnly),[n]=v(i,[this.slug.toString(),r]);return n[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[i,n]=v(t,[this.slug.toString(),r]);return delete i[e],n}))},setValue:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=D(!!r.isGeneral);S(!!r.sessionOnly,(r=>{const[n,s]=v(r,[this.slug.toString(),i]);return n[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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:n=!0}=i,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==i?void 0:i.operation)||"readwrite")}catch(o){if(n&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(s.deleteDatabase(a).onsuccess=()=>{this.queryObjectStore(e,t,r(r({},i),{},{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(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.put({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{n("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,r,i){const n=new Promise(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.add({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{const t=e.target.error;n(t)}}))}));if(void 0===i||isNaN(i))return n;const s=new Promise(((e,t)=>setTimeout((()=>t(new j)),i)));return Promise.race([n,s])}get(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.get(t);n.onsuccess=()=>{var e;n.result?r(null===(e=n.result)||void 0===e?void 0:e.value):r(void 0)},n.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.getAll(null,t);n.onsuccess=()=>{if(n.result){const e=n.result;(null==e?void 0:e.length)?r(e.map((e=>null==e?void 0:e.value))):r(e)}else r([])},n.onerror=e=>{i("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.delete(t);n.onsuccess=()=>{r()},n.onerror=e=>{i(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,r)=>{this.queryObjectStore(e,(e=>{const i=e.clear();i.onsuccess=()=>{t()},i.onerror=e=>{r("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,((e,n)=>{const s=e.transaction;s.onerror=()=>{i(`Transaction failed: ${s.error}`)},s.onabort=()=>{i("Transaction aborted")},s.oncomplete=()=>{n.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 i("Unknown operation type");t=e.put({key:r.key,value:r.value})}t.onerror=()=>{s.abort(),i(`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 i,n,s,a,o,c;this.agent=e,this.keysType=t,this.options=r,this._extractingKeysPromise=null,this.cryptoBindingErrors=[];const l=!(null===(i=this.options)||void 0===i?void 0:i.productScope),d=null===(n=this.options)||void 0===n?void 0:n.fallbackClientId,u=l||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,y=null===(a=this.options)||void 0===a?void 0:a.keyScope;this.keysDatabaseName=y?`${u}:${y}`:u,this.dbVersion=l?1:(null===(o=this.options)||void 0===o?void 0:o.dbVersion)||1,this.keysStoreName=l||!(null===(c=this.options)||void 0===c?void 0:c.keysStoreName)?"identifiers_store":this.options.keysStoreName;const h=l?"platform":e.slug,g=this.getClientConfiguration(d,h);this.indexedDBClient=new B(g.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(g.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:i,base64Key:n}=await this.getPKRepresentations(r.publicKey);return this.publicKeyBase64=n,this.keyIdentifier=r.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i),r})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:i}=await this.getPKRepresentations(t.publicKey),n=e||await this.calcKeyIdentifier(i);return r(r({},t),{},{keyIdentifier:n,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 i=24*r.expiryDays*60*60*1e3,n=e.createdDate&&e.createdDate>=r.startedAt?e.createdDate:r.startedAt;return Date.now()-n>i-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(),i=await this.getKeysData(),n=r(r({},i),{},{createdDate:i.createdDate||Date.now()});e=await this.saveKeyData(t,n)}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 i=await this.extractPendingRotatedKeysData();if(i){const{base64Key:e}=await this.getPKRepresentations(i.publicKey),{privateKey:t}=await this.extractKeysData(),n=r(r({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:i.createdDate,newPublicKeyType:N}),s=JSON.stringify(n);return{data:s,signature:await this.signPayload(s,t)}}const n=await this.extractRotatedKeysData();if(n&&!1===n.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,n.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:i,base64Key:n}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=n,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i)}}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 $=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 i=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,r,i)}}),M=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 i=this.middlewares.map((e=>e(this)));Promise.all(i).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",i=new URL(r);i.search=(null==t?void 0:t.toString())||"",i.pathname=e;return i.href.replace(r,"")}function F(e,t,i){var n;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:""},i||{}),body:null!==(n=t&&JSON.stringify(t||{}))&&void 0!==n?n:void 0}}function G(e,t,r,i,n){const s=q(e,i),a=F(t,r,n);return fetch(s,a)}async function J(e,t,r,i,n){let s;if(s=await G(e,t,r,i,n),!s.ok)throw new Error("Request failed");return s}var W=Object.freeze({__proto__:null,httpDelete:async function(e,t){const i=await J(e,"DELETE",void 0,void 0,t);return r(r({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(e,t,i){const n=await J(e,"GET",void 0,t,i);return r(r({data:await n.json()},n),{},{headers:n.headers})},httpPost:async function(e,t,i,n){const s=await J(e,"POST",t,i,n);return r(r({data:await s.json()},s),{},{headers:s.headers})},httpPut:async function(e,t,i,n){const s=await J(e,"PUT",t,i,n);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:R,crypto:$,indexedDB:M,logger:V,http:W})));exports.PACKAGE_VERSION="2.6.1",exports.default=X,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 i=r.call(e,t||"default");if("object"!=typeof i)return i;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 i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(r){for(var i=1;i<arguments.length;i++){var n=null!=arguments[i]?arguments[i]:{};i%2?t(Object(n),!0).forEach((function(t){e(r,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(n,e))}))}return r}function i(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)r=s[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function n(e,t){return Object.entries(t).reduce(((t,i)=>{let[a,o]=i;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?n(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,n(this,e(this)))}}}}var a=Object.freeze({__proto__:null,Agent:s});const o=new Map;function c(e,t){var r,i;null===(r=o.get(e))||void 0===r||r.forEach((i=e=>e(t),function(){try{return i(...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 i=r.indexOf(t);-1!==i&&r.splice(i,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 g=["enabled","serverPath"],f=["drs","ido"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:n}=e,s=null==t||t;return r(r({serverPath:n},i(e,g)),{},{enabled:s})}function w(e){const{drs:t,ido:n}=e,s=i(e,f);let a=t;(null==n?void 0:n.collectRiskData)&&(a=r(r({},t),{},{tier:"lightweight"}));y(r(r({},s),{},{ido:n,drs:p(a)})),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,i=t(O(e));r.setItem(K,JSON.stringify(i))}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),i=O(!!t.sessionOnly),[n]=v(i,[this.slug.toString(),r]);return n[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[i,n]=v(t,[this.slug.toString(),r]);return delete i[e],n}))},setValue:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=D(!!r.isGeneral);S(!!r.sessionOnly,(r=>{const[n,s]=v(r,[this.slug.toString(),i]);return n[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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:n=!0}=i,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==i?void 0:i.operation)||"readwrite")}catch(o){if(n&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(s.deleteDatabase(a).onsuccess=()=>{this.queryObjectStore(e,t,r(r({},i),{},{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(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.put({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{n("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,r,i){const n=new Promise(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.add({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{const t=e.target.error;n(t)}}))}));if(void 0===i||isNaN(i))return n;const s=new Promise(((e,t)=>setTimeout((()=>t(new j)),i)));return Promise.race([n,s])}get(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.get(t);n.onsuccess=()=>{var e;n.result?r(null===(e=n.result)||void 0===e?void 0:e.value):r(void 0)},n.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.getAll(null,t);n.onsuccess=()=>{if(n.result){const e=n.result;(null==e?void 0:e.length)?r(e.map((e=>null==e?void 0:e.value))):r(e)}else r([])},n.onerror=e=>{i("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.delete(t);n.onsuccess=()=>{r()},n.onerror=e=>{i(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,r)=>{this.queryObjectStore(e,(e=>{const i=e.clear();i.onsuccess=()=>{t()},i.onerror=e=>{r("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,((e,n)=>{const s=e.transaction;s.onerror=()=>{i(`Transaction failed: ${s.error}`)},s.onabort=()=>{i("Transaction aborted")},s.oncomplete=()=>{n.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 i("Unknown operation type");t=e.put({key:r.key,value:r.value})}t.onerror=()=>{s.abort(),i(`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 i,n,s,a,o,c;this.agent=e,this.keysType=t,this.options=r,this._extractingKeysPromise=null,this.cryptoBindingErrors=[];const l=!(null===(i=this.options)||void 0===i?void 0:i.productScope),d=null===(n=this.options)||void 0===n?void 0:n.fallbackClientId,u=l||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,y=null===(a=this.options)||void 0===a?void 0:a.keyScope;this.keysDatabaseName=y?`${u}:${y}`:u,this.dbVersion=l?1:(null===(o=this.options)||void 0===o?void 0:o.dbVersion)||1,this.keysStoreName=l||!(null===(c=this.options)||void 0===c?void 0:c.keysStoreName)?"identifiers_store":this.options.keysStoreName;const h=l?"platform":e.slug,g=this.getClientConfiguration(d,h);this.indexedDBClient=new B(g.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(g.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:i,base64Key:n}=await this.getPKRepresentations(r.publicKey);return this.publicKeyBase64=n,this.keyIdentifier=r.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i),r})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:i}=await this.getPKRepresentations(t.publicKey),n=e||await this.calcKeyIdentifier(i);return r(r({},t),{},{keyIdentifier:n,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 i=24*r.expiryDays*60*60*1e3,n=e.createdDate&&e.createdDate>=r.startedAt?e.createdDate:r.startedAt;return Date.now()-n>i-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(),i=await this.getKeysData(),n=r(r({},i),{},{createdDate:i.createdDate||Date.now()});e=await this.saveKeyData(t,n)}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 i=await this.extractPendingRotatedKeysData();if(i){const{base64Key:e}=await this.getPKRepresentations(i.publicKey),{privateKey:t}=await this.extractKeysData(),n=r(r({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:i.createdDate,newPublicKeyType:N}),s=JSON.stringify(n);return{data:s,signature:await this.signPayload(s,t)}}const n=await this.extractRotatedKeysData();if(n&&!1===n.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,n.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:i,base64Key:n}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=n,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i)}}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 $=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 i=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,r,i)}}),M=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 i=this.middlewares.map((e=>e(this)));Promise.all(i).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",i=new URL(r);i.search=(null==t?void 0:t.toString())||"",i.pathname=e;return i.href.replace(r,"")}function F(e,t,i){var n;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:""},i||{}),body:null!==(n=t&&JSON.stringify(t||{}))&&void 0!==n?n:void 0}}function G(e,t,r,i,n){const s=q(e,i),a=F(t,r,n);return fetch(s,a)}async function J(e,t,r,i,n){let s;if(s=await G(e,t,r,i,n),!s.ok)throw new Error("Request failed");return s}var W=Object.freeze({__proto__:null,httpDelete:async function(e,t){const i=await J(e,"DELETE",void 0,void 0,t);return r(r({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(e,t,i){const n=await J(e,"GET",void 0,t,i);return r(r({data:await n.json()},n),{},{headers:n.headers})},httpPost:async function(e,t,i,n){const s=await J(e,"POST",t,i,n);return r(r({data:await s.json()},s),{},{headers:s.headers})},httpPut:async function(e,t,i,n){const s=await J(e,"PUT",t,i,n);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:R,crypto:$,indexedDB:M,logger:V,http:W})));exports.PACKAGE_VERSION="2.6.2",exports.default=X,exports.initialize=w;
package/dist/common.js CHANGED
@@ -1 +1 @@
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 i=r.call(e,t||"default");if("object"!=typeof i)return i;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 i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(r){for(var i=1;i<arguments.length;i++){var n=null!=arguments[i]?arguments[i]:{};i%2?t(Object(n),!0).forEach((function(t){e(r,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(n,e))}))}return r}function i(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)r=s[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function n(e,t){return Object.entries(t).reduce(((t,i)=>{let[a,o]=i;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?n(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,n(this,e(this)))}}}}var a=Object.freeze({__proto__:null,Agent:s});const o=new Map;function c(e,t){var r,i;null===(r=o.get(e))||void 0===r||r.forEach((i=e=>e(t),function(){try{return i(...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 i=r.indexOf(t);-1!==i&&r.splice(i,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 g=["enabled","serverPath"],f=["drs","ido"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:n}=e,s=null==t||t;return r(r({serverPath:n},i(e,g)),{},{enabled:s})}function w(e){const{drs:t,ido:n}=e,s=i(e,f);let a=t;(null==n?void 0:n.collectRiskData)&&(a=r(r({},t),{},{tier:"lightweight"}));y(r(r({},s),{},{ido:n,drs:p(a)})),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,i=t(O(e));r.setItem(K,JSON.stringify(i))}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),i=O(!!t.sessionOnly),[n]=v(i,[this.slug.toString(),r]);return n[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[i,n]=v(t,[this.slug.toString(),r]);return delete i[e],n}))},setValue:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=D(!!r.isGeneral);S(!!r.sessionOnly,(r=>{const[n,s]=v(r,[this.slug.toString(),i]);return n[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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:n=!0}=i,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==i?void 0:i.operation)||"readwrite")}catch(o){if(n&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(s.deleteDatabase(a).onsuccess=()=>{this.queryObjectStore(e,t,r(r({},i),{},{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(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.put({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{n("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,r,i){const n=new Promise(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.add({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{const t=e.target.error;n(t)}}))}));if(void 0===i||isNaN(i))return n;const s=new Promise(((e,t)=>setTimeout((()=>t(new j)),i)));return Promise.race([n,s])}get(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.get(t);n.onsuccess=()=>{var e;n.result?r(null===(e=n.result)||void 0===e?void 0:e.value):r(void 0)},n.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.getAll(null,t);n.onsuccess=()=>{if(n.result){const e=n.result;(null==e?void 0:e.length)?r(e.map((e=>null==e?void 0:e.value))):r(e)}else r([])},n.onerror=e=>{i("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.delete(t);n.onsuccess=()=>{r()},n.onerror=e=>{i(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,r)=>{this.queryObjectStore(e,(e=>{const i=e.clear();i.onsuccess=()=>{t()},i.onerror=e=>{r("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,((e,n)=>{const s=e.transaction;s.onerror=()=>{i(`Transaction failed: ${s.error}`)},s.onabort=()=>{i("Transaction aborted")},s.oncomplete=()=>{n.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 i("Unknown operation type");t=e.put({key:r.key,value:r.value})}t.onerror=()=>{s.abort(),i(`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 i,n,s,a,o,c;this.agent=e,this.keysType=t,this.options=r,this._extractingKeysPromise=null,this.cryptoBindingErrors=[];const l=!(null===(i=this.options)||void 0===i?void 0:i.productScope),d=null===(n=this.options)||void 0===n?void 0:n.fallbackClientId,u=l||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,y=null===(a=this.options)||void 0===a?void 0:a.keyScope;this.keysDatabaseName=y?`${u}:${y}`:u,this.dbVersion=l?1:(null===(o=this.options)||void 0===o?void 0:o.dbVersion)||1,this.keysStoreName=l||!(null===(c=this.options)||void 0===c?void 0:c.keysStoreName)?"identifiers_store":this.options.keysStoreName;const h=l?"platform":e.slug,g=this.getClientConfiguration(d,h);this.indexedDBClient=new B(g.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(g.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:i,base64Key:n}=await this.getPKRepresentations(r.publicKey);return this.publicKeyBase64=n,this.keyIdentifier=r.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i),r})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:i}=await this.getPKRepresentations(t.publicKey),n=e||await this.calcKeyIdentifier(i);return r(r({},t),{},{keyIdentifier:n,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 i=24*r.expiryDays*60*60*1e3,n=e.createdDate&&e.createdDate>=r.startedAt?e.createdDate:r.startedAt;return Date.now()-n>i-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(),i=await this.getKeysData(),n=r(r({},i),{},{createdDate:i.createdDate||Date.now()});e=await this.saveKeyData(t,n)}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 i=await this.extractPendingRotatedKeysData();if(i){const{base64Key:e}=await this.getPKRepresentations(i.publicKey),{privateKey:t}=await this.extractKeysData(),n=r(r({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:i.createdDate,newPublicKeyType:N}),s=JSON.stringify(n);return{data:s,signature:await this.signPayload(s,t)}}const n=await this.extractRotatedKeysData();if(n&&!1===n.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,n.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:i,base64Key:n}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=n,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i)}}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 i=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,r,i)}}),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 i=this.middlewares.map((e=>e(this)));Promise.all(i).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",i=new URL(r);i.search=(null==t?void 0:t.toString())||"",i.pathname=e;return i.href.replace(r,"")}function V(e,t,i){var n;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:""},i||{}),body:null!==(n=t&&JSON.stringify(t||{}))&&void 0!==n?n:void 0}}function G(e,t,r,i,n){const s=F(e,i),a=V(t,r,n);return fetch(s,a)}async function J(e,t,r,i,n){let s;if(s=await G(e,t,r,i,n),!s.ok)throw new Error("Request failed");return s}var W=Object.freeze({__proto__:null,httpDelete:async function(e,t){const i=await J(e,"DELETE",void 0,void 0,t);return r(r({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(e,t,i){const n=await J(e,"GET",void 0,t,i);return r(r({data:await n.json()},n),{},{headers:n.headers})},httpPost:async function(e,t,i,n){const s=await J(e,"POST",t,i,n);return r(r({data:await s.json()},s),{},{headers:s.headers})},httpPut:async function(e,t,i,n){const s=await J(e,"PUT",t,i,n);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.6.1";export{H as PACKAGE_VERSION,X 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 i=r.call(e,t||"default");if("object"!=typeof i)return i;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 i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function r(r){for(var i=1;i<arguments.length;i++){var n=null!=arguments[i]?arguments[i]:{};i%2?t(Object(n),!0).forEach((function(t){e(r,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach((function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(n,e))}))}return r}function i(e,t){if(null==e)return{};var r,i,n=function(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)r=s[i],-1===t.indexOf(r)&&{}.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function n(e,t){return Object.entries(t).reduce(((t,i)=>{let[a,o]=i;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?n(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,n(this,e(this)))}}}}var a=Object.freeze({__proto__:null,Agent:s});const o=new Map;function c(e,t){var r,i;null===(r=o.get(e))||void 0===r||r.forEach((i=e=>e(t),function(){try{return i(...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 i=r.indexOf(t);-1!==i&&r.splice(i,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 g=["enabled","serverPath"],f=["drs","ido"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:n}=e,s=null==t||t;return r(r({serverPath:n},i(e,g)),{},{enabled:s})}function w(e){const{drs:t,ido:n}=e,s=i(e,f);let a=t;(null==n?void 0:n.collectRiskData)&&(a=r(r({},t),{},{tier:"lightweight"}));y(r(r({},s),{},{ido:n,drs:p(a)})),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,i=t(O(e));r.setItem(K,JSON.stringify(i))}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),i=O(!!t.sessionOnly),[n]=v(i,[this.slug.toString(),r]);return n[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[i,n]=v(t,[this.slug.toString(),r]);return delete i[e],n}))},setValue:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=D(!!r.isGeneral);S(!!r.sessionOnly,(r=>{const[n,s]=v(r,[this.slug.toString(),i]);return n[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 i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:n=!0}=i,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==i?void 0:i.operation)||"readwrite")}catch(o){if(n&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(s.deleteDatabase(a).onsuccess=()=>{this.queryObjectStore(e,t,r(r({},i),{},{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(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.put({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{n("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,r,i){const n=new Promise(((i,n)=>{this.queryObjectStore(e,(e=>{const s=e.add({key:t,value:r});s.onsuccess=()=>{i(s.result)},s.onerror=e=>{const t=e.target.error;n(t)}}))}));if(void 0===i||isNaN(i))return n;const s=new Promise(((e,t)=>setTimeout((()=>t(new j)),i)));return Promise.race([n,s])}get(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.get(t);n.onsuccess=()=>{var e;n.result?r(null===(e=n.result)||void 0===e?void 0:e.value):r(void 0)},n.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.getAll(null,t);n.onsuccess=()=>{if(n.result){const e=n.result;(null==e?void 0:e.length)?r(e.map((e=>null==e?void 0:e.value))):r(e)}else r([])},n.onerror=e=>{i("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const n=e.delete(t);n.onsuccess=()=>{r()},n.onerror=e=>{i(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,r)=>{this.queryObjectStore(e,(e=>{const i=e.clear();i.onsuccess=()=>{t()},i.onerror=e=>{r("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((r,i)=>{this.queryObjectStore(e,((e,n)=>{const s=e.transaction;s.onerror=()=>{i(`Transaction failed: ${s.error}`)},s.onabort=()=>{i("Transaction aborted")},s.oncomplete=()=>{n.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 i("Unknown operation type");t=e.put({key:r.key,value:r.value})}t.onerror=()=>{s.abort(),i(`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 i,n,s,a,o,c;this.agent=e,this.keysType=t,this.options=r,this._extractingKeysPromise=null,this.cryptoBindingErrors=[];const l=!(null===(i=this.options)||void 0===i?void 0:i.productScope),d=null===(n=this.options)||void 0===n?void 0:n.fallbackClientId,u=l||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,y=null===(a=this.options)||void 0===a?void 0:a.keyScope;this.keysDatabaseName=y?`${u}:${y}`:u,this.dbVersion=l?1:(null===(o=this.options)||void 0===o?void 0:o.dbVersion)||1,this.keysStoreName=l||!(null===(c=this.options)||void 0===c?void 0:c.keysStoreName)?"identifiers_store":this.options.keysStoreName;const h=l?"platform":e.slug,g=this.getClientConfiguration(d,h);this.indexedDBClient=new B(g.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(g.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:i,base64Key:n}=await this.getPKRepresentations(r.publicKey);return this.publicKeyBase64=n,this.keyIdentifier=r.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i),r})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:i}=await this.getPKRepresentations(t.publicKey),n=e||await this.calcKeyIdentifier(i);return r(r({},t),{},{keyIdentifier:n,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 i=24*r.expiryDays*60*60*1e3,n=e.createdDate&&e.createdDate>=r.startedAt?e.createdDate:r.startedAt;return Date.now()-n>i-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(),i=await this.getKeysData(),n=r(r({},i),{},{createdDate:i.createdDate||Date.now()});e=await this.saveKeyData(t,n)}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 i=await this.extractPendingRotatedKeysData();if(i){const{base64Key:e}=await this.getPKRepresentations(i.publicKey),{privateKey:t}=await this.extractKeysData(),n=r(r({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:i.createdDate,newPublicKeyType:N}),s=JSON.stringify(n);return{data:s,signature:await this.signPayload(s,t)}}const n=await this.extractRotatedKeysData();if(n&&!1===n.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,n.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:i,base64Key:n}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=n,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(i)}}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 i=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,r,i)}}),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 i=this.middlewares.map((e=>e(this)));Promise.all(i).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",i=new URL(r);i.search=(null==t?void 0:t.toString())||"",i.pathname=e;return i.href.replace(r,"")}function V(e,t,i){var n;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:""},i||{}),body:null!==(n=t&&JSON.stringify(t||{}))&&void 0!==n?n:void 0}}function G(e,t,r,i,n){const s=F(e,i),a=V(t,r,n);return fetch(s,a)}async function J(e,t,r,i,n){let s;if(s=await G(e,t,r,i,n),!s.ok)throw new Error("Request failed");return s}var W=Object.freeze({__proto__:null,httpDelete:async function(e,t){const i=await J(e,"DELETE",void 0,void 0,t);return r(r({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(e,t,i){const n=await J(e,"GET",void 0,t,i);return r(r({data:await n.json()},n),{},{headers:n.headers})},httpPost:async function(e,t,i,n){const s=await J(e,"POST",t,i,n);return r(r({data:await s.json()},s),{},{headers:s.headers})},httpPut:async function(e,t,i,n){const s=await J(e,"PUT",t,i,n);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.6.2";export{H as PACKAGE_VERSION,X as default,w as initialize};