@transmitsecurity/platform-web-sdk 2.5.1 → 2.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/common.cjs +1 -1
- package/dist/common.js +1 -1
- package/dist/drs.cjs +1 -1
- package/dist/drs.d.ts +48 -1
- package/dist/drs.js +1 -1
- package/dist/ido.cjs +1 -1
- package/dist/ido.d.ts +3 -1
- package/dist/ido.js +1 -1
- package/dist/idv.cjs +1 -1
- package/dist/idv.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/ts-platform-websdk.js +1 -1
- package/dist/web-sdk-drs+idv+webauthn+ido.js +1 -1
- package/dist/web-sdk.d.ts +91 -9
- package/dist/webauthn.cjs +1 -1
- package/dist/webauthn.js +1 -1
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.6.1 - Aug. 16, 2026
|
|
4
|
+
**Identity Verification**
|
|
5
|
+
* fix: prevent the Authorization header from being dropped on session-status requests due to a race condition in header assignment
|
|
6
|
+
* fix: align selfie autocapture face angle checks with the server, and skip them when the face is cut off by the frame edge
|
|
7
|
+
* fix: reduce autocapture per-frame processing cost on slow devices
|
|
8
|
+
* fix: stop autocapture and fall back to manual capture after persistent detection failures
|
|
9
|
+
|
|
10
|
+
**Fraud Prevention**
|
|
11
|
+
* feat: added an `authContext` parameter to `triggerActionEvent`, so callers can pass authentication context for non-authentication actions that occur after a successful login.
|
|
12
|
+
* chore: the Platform SDK version is now reported on all events, not only action events.
|
|
13
|
+
|
|
14
|
+
**Orchestration**
|
|
15
|
+
* Device registration now captures more accurate device context, such as browser, operating system, and hardware model.
|
|
16
|
+
|
|
17
|
+
## 2.6.0 - Aug. 02, 2026
|
|
18
|
+
**General**
|
|
19
|
+
* fix: Improved `keyScope` isolation to prevent different browser contexts from inadvertently clearing each other's crypto-binding keys.
|
|
20
|
+
|
|
21
|
+
**Orchestration**
|
|
22
|
+
* chore: Bump `ido-web-sdk` to `1.2.1`, which includes `keyScope` support for journey crypto-binding keys.
|
|
23
|
+
|
|
24
|
+
**Fraud Prevention**
|
|
25
|
+
* Adds edge-injection support for agentic data collection, enabling the SDK to be deployed via WAF or CDN alongside existing page instrumentation.
|
|
26
|
+
|
|
27
|
+
* Extended agentic AI recognition with additional behavioral signals, enriching action and interaction events.
|
|
28
|
+
|
|
3
29
|
## 2.5.1 - Jul. 19, 2026
|
|
4
30
|
**Identity Verification**
|
|
5
31
|
* feat: accept language in sdk initialization
|
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="identifiers_store",T="init",N="completed",A="RSA2048",C=[T,N];class ${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;this.keysDatabaseName=l||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=l?1:(null===(a=this.options)||void 0===a?void 0:a.dbVersion)||1;const u=null===(o=this.options)||void 0===o?void 0:o.keyScope;this.keysStoreName=u?`${E}:${u}`:l||!(null===(c=this.options)||void 0===c?void 0:c.keysStoreName)?E:this.options.keysStoreName;const y=l?"platform":e.slug,h=this.getClientConfiguration(d,y);this.indexedDBClient=new B(h.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(h.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:A,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:A}),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(C.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===N){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:N,INIT_ROTATION_RESPONSE:T,createCryptoBinding:function(){return new $(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 z=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 U=s.create((()=>r({exceptions:z},a)));class V{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 V(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 G(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 J(e,t,r,i,n){const s=F(e,i),a=G(t,r,n);return fetch(s,a)}async function W(e,t,r,i,n){let s;if(s=await J(e,t,r,i,n),!s.ok)throw new Error("Request failed");return s}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const i=await W(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 W(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 W(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 W(e,"PUT",t,i,n);return r(r({data:await s.json()},s),{},{headers:s.headers})},init:G}),H=s.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:U,storage:R,crypto:M,indexedDB:L,logger:q,http:X})));exports.PACKAGE_VERSION="2.5.1",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 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;
|
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 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 g=["enabled","serverPath"],f=["drs","ido"];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,g)),{},{enabled:s})}function w(e){const{drs:t,ido:i}=e,s=n(e,f);let a=t;(null==i?void 0:i.collectRiskData)&&(a=r(r({},t),{},{tier:"lightweight"}));y(r(r({},s),{},{ido:i,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,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="identifiers_store",E="init",N="completed",A="RSA2048",C=[E,N];class ${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,c;this.agent=e,this.keysType=t,this.options=r,this._extractingKeysPromise=null,this.cryptoBindingErrors=[];const l=!(null===(n=this.options)||void 0===n?void 0:n.productScope),d=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=l||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=l?1:(null===(a=this.options)||void 0===a?void 0:a.dbVersion)||1;const u=null===(o=this.options)||void 0===o?void 0:o.keyScope;this.keysStoreName=u?`${T}:${u}`:l||!(null===(c=this.options)||void 0===c?void 0:c.keysStoreName)?T:this.options.keysStoreName;const y=l?"platform":e.slug,h=this.getClientConfiguration(d,y);this.indexedDBClient=new B(h.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new B(h.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:A,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:A}),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(C.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===N){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),r(r({},e),{},{confirmed:!0}))}}}var L=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:N,INIT_ROTATION_RESPONSE:E,createCryptoBinding:function(){return new $(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)}}),M=Object.freeze({__proto__:null,IDBWriteTimeoutError:j});const z=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 U=s.create((()=>r({exceptions:z},a)));class q{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 F=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 q(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 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 G(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 J(e,t,r,n,i){const s=V(e,n),a=G(t,r,i);return fetch(s,a)}async function W(e,t,r,n,i){let s;if(s=await J(e,t,r,n,i),!s.ok)throw new Error("Request failed");return s}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const n=await W(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 W(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 W(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 W(e,"PUT",t,n,i);return r(r({data:await s.json()},s),{},{headers:s.headers})},init:G}),H=s.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:U,storage:R,crypto:L,indexedDB:M,logger:F,http:X})));const Y="2.5.1";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 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};
|