@transmitsecurity/platform-web-sdk 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/common.cjs +1 -1
- package/dist/common.js +1 -1
- package/dist/drs.cjs +1 -1
- package/dist/drs.d.ts +27 -1
- package/dist/drs.js +1 -1
- package/dist/ido.cjs +1 -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 +33 -1
- package/dist/webauthn.cjs +1 -1
- package/dist/webauthn.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
# Changelog
|
|
2
|
+
## 2.1.0 - Feb. 08, 2026
|
|
3
|
+
**Fraud Prevention**
|
|
4
|
+
* feat: Introducing CIAM Secure through IDO journeys
|
|
5
|
+
|
|
2
6
|
## 2.0.0 - Feb. 01, 2026
|
|
3
7
|
**Fraud Prevention**
|
|
4
8
|
* BREAKING CHANGE: The `serverPath` parameter is now required. In previous versions, it defaulted to the US region. To ensure correct routing to your region, you must update your configuration to include the `serverPath` property as specified in the documentation.
|
package/dist/common.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){e(n,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(i,e))}))}return n}function r(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function i(e,t){return Object.entries(t).reduce(((t,r)=>{let[s,o]=r;return n(n({},t),{},{[s]:a.isPrototypeOf(o)?new o(e.slug):"function"==typeof o?o.bind(e):"object"==typeof o&&!Array.isArray(o)&&o?i(e,o):o})}),{})}"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self)),Object.defineProperty(exports,"__esModule",{value:!0});class a{constructor(e){this.slug=e}static create(e){return class extends a{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var s=Object.freeze({__proto__:null,Agent:a});const o=new Map;function c(e,t){var n,r;null===(n=o.get(e))||void 0===n||n.forEach((r=e=>e(t),function(){try{return r(...arguments)}catch(e){console.log(e)}}))}const l=Symbol("MODULE_INITIALIZED");var d=Object.freeze({__proto__:null,MODULE_INITIALIZED:l,emit:c,off:function(e,t){const n=o.get(e);if(!n)return;const r=n.indexOf(t);-1!==r&&n.splice(r,1)},on:function(e,t){var n;o.has(e)?null===(n=o.get(e))||void 0===n||n.push(t):o.set(e,[t])}});let y=null;function u(e){y=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return y},get initConfig(){return y},setInitConfig:u});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,a=null==t||t;return n(n({serverPath:i},r(e,f)),{},{enabled:a})}function w(e){const{drs:t}=e;u(n(n({},r(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function K(e,t){const n=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const n=e[t];if(null!==n&&"object"==typeof n&&!Array.isArray(n))return n}const n={};return e[t]=n,n}),n),n]}const v="tsec",m="general";function D(e){return e?m:y.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(v))}function S(e,t){const n=e?sessionStorage:localStorage,r=t(O(e));n.setItem(v,JSON.stringify(r))}var R=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:v,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral),r=O(!!t.sessionOnly),[i]=K(r,[this.slug.toString(),n]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);return function(e,t){let n=e;return t.every((e=>!(!n||"object"!=typeof n||Array.isArray(n)||!(e in n)||(n=n[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),n,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[r,i]=K(t,[this.slug.toString(),n]);return delete r[e],i}))},setValue:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=D(!!n.isGeneral);S(!!n.sessionOnly,(n=>{const[i,a]=K(n,[this.slug.toString(),r]);return i[e]=t,a}))}});const P="RSA-PSS",k=async(e,t)=>await window.crypto.subtle.generateKey({name:e,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,t),x=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),_=async()=>await k(P,["sign"]),j=async(e,t)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:P,saltLength:32},e,n)};class I{constructor(e,t,n){this.slug=e,this.dbName=t,this.dbVersion=n}queryObjectStore(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=r,a=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,s=`${this.slug}:${this.dbName}`,o=a.open(s,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const n=o.result;(null===(t=null==n?void 0:n.objectStoreNames)||void 0===t?void 0:t.contains)&&!n.objectStoreNames.contains(e)&&n.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==r?void 0:r.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(a.deleteDatabase(s).onsuccess=()=>{this.queryObjectStore(e,t,n(n({},r),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.put({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.add({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{const t=e.target.error;i(t)}}))}))}get(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?n(null===(e=i.result)||void 0===e?void 0:e.value):n(void 0)},i.onerror=e=>{r("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.getAll(null,t);i.onsuccess=()=>{if(i.result){const e=i.result;(null==e?void 0:e.length)?n(e.map((e=>null==e?void 0:e.value))):n(e)}else n([])},i.onerror=e=>{r("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{n()},i.onerror=e=>{r(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,n)=>{this.queryObjectStore(e,(e=>{const r=e.clear();r.onsuccess=()=>{t()},r.onerror=e=>{n("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,((e,i)=>{const a=e.transaction;a.onerror=()=>{r(`Transaction failed: ${a.error}`)},a.onabort=()=>{r("Transaction aborted")},a.oncomplete=()=>{i.close(),n()};for(const n of t){let t;if("delete"===n.type)t=e.delete(n.key);else{if("put"!==n.type)return a.abort(),void r("Unknown operation type");t=e.put({key:n.key,value:n.value})}t.onerror=()=>{a.abort(),r(`Operation failed: ${t.error}`)}}}))}))}}const B="init",T="completed",E="RSA2048",N=[B,T];class A{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",n=arguments.length>2?arguments[2]:void 0;var r,i,a,s,o;this.agent=e,this.keysType=t,this.options=n,this._extractingKeysPromise=null;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(a=this.options)||void 0===a?void 0:a.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(s=this.options)||void 0===s?void 0:s.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName;const d=c?"platform":e.slug,y=this.getClientConfiguration(l,d);this.indexedDBClient=new I(y.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new I(y.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${y.clientId}`}}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(e){return window.btoa(String.fromCharCode(...new Uint8Array(e)))}async getPKRepresentations(e){const t=await crypto.subtle.exportKey("spki",e);return{arrayBufferKey:t,base64Key:this.arrayBufferToBase64(t)}}async generateKeyPair(){return"sign"==this.keysType?await _():await x()}async calcKeyIdentifier(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var e,t;const n=(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(n.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=n.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r),n})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:r}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(r);return n(n({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const n=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==n?void 0:n.isEnabled)||!n.expiryDays||void 0===n.startedAt)return!1;const r=24*n.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=n.startedAt?e.createdDate:n.startedAt;return Date.now()-i>r-2592e6}async extractMainKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getKeysRecordKey())}async extractFallbackMainKeysData(){return await this.indexedDBClientFallback.get(this.keysStoreName,this.getKeysRecordKey())}async extractRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKey())}async extractPendingRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKeyPending())}async saveKeyData(e,t){try{return await this.indexedDBClient.add(this.keysStoreName,e,t),t}catch(t){if(t instanceof DOMException&&"ConstraintError"===t.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}throw t}}async getKeysData(){const e=this.getKeysRecordKey();let t=await this.extractMainKeysData();if(t)return t;if(t=await this.extractFallbackMainKeysData(),t)return this.saveKeyData(e,t);const n=await this.generateKeyPairData();return this.saveKeyData(e,n)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),r=await this.getKeysData(),i=n(n({},r),{},{createdDate:r.createdDate||Date.now()});e=await this.saveKeyData(t,i)}return e}async getRotatedKeysData(){const e=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(e)){if(!await this.extractPendingRotatedKeysData()){const t=this.getRotatedKeysRecordKeyPending(),n=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,n)}}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId}}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),n=await j(t,e);return this.arrayBufferToBase64(n)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const e=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,e)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:E,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var e,t;if(!(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const r=await this.extractPendingRotatedKeysData();if(r){const{base64Key:e}=await this.getPKRepresentations(r.publicKey),{privateKey:t}=await this.extractKeysData(),i=n(n({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:r.createdDate,newPublicKeyType:E}),a=JSON.stringify(i);return{data:a,signature:await this.signPayload(a,t)}}const i=await this.extractRotatedKeysData();if(i&&!1===i.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,i.privateKey)}}}async signPayload(e,t){const n=await j(t,e);return this.arrayBufferToBase64(n)}async handleRotateResponse(e){if(N.includes(e))if(e===B){const e=await this.extractPendingRotatedKeysData();if(e){const t=n(n({},e),{},{confirmed:!1});await this.indexedDBClient.executeTransaction(this.keysStoreName,[{type:"delete",key:this.getRotatedKeysRecordKey()},{type:"put",key:this.getRotatedKeysRecordKey(),value:t},{type:"delete",key:this.getRotatedKeysRecordKeyPending()}]);const{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r)}}else if(e===T){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),n(n({},e),{},{confirmed:!0}))}}}var C=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:T,INIT_ROTATION_RESPONSE:B,createCryptoBinding:function(){return new A(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:x,generateRSASignKeyPair:_,signAssymetric:j,verifyAssymetric:async(e,t,n)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,n,r)}}),$=Object.freeze({__proto__:null});const L=a.create((e=>{class t extends Error{constructor(t,n){super(`${e.slug}-${t} ${n}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var M=a.create((()=>n({exceptions:L},s)));class z{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=e,this.middlewares=t,this.logs=[]}info(e,t){this.pushLog(3,e,t)}warn(e,t){this.pushLog(4,e,t)}error(e,t){this.pushLog(5,e,t)}pushLog(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:n,message:t});const r=this.middlewares.map((e=>e(this)));Promise.all(r).catch((()=>{}))}}var U=Object.freeze({__proto__:null,consoleMiddleware:function(e){const t=e.logs[e.logs.length-1];console.log(`${t.severity} ${t.message}`,t.fields)},createSdkLogger:function(){return new z(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])}});function V(e,t){if(!(null==e?void 0:e.trim()))return"";if(function(e){try{return new URL(e),!0}catch(e){return!1}}(e))return e;const n="http://mock.com",r=new URL(n);r.search=(null==t?void 0:t.toString())||"",r.pathname=e;return r.href.replace(n,"")}const q={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function F(e,t,r){var i;const a=(s=t||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:e,headers:n(n(n({},{"X-TS-body-size":String(a)}),q),r||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,n,r,i){const a=V(e,r),s=F(t,n,i);return fetch(a,s)}async function J(e,t,n,r,i){let a;if(a=await G(e,t,n,r,i),!a.ok)throw new Error("Request failed");return a}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const r=await J(e,"DELETE",void 0,void 0,t);return n(n({data:await r.json()},r),{},{headers:r.headers})},httpGet:async function(e,t,r){const i=await J(e,"GET",void 0,t,r);return n(n({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,r,i){const a=await J(e,"POST",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},httpPut:async function(e,t,r,i){const a=await J(e,"PUT",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},init:F}),H=a.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:M,storage:R,crypto:C,indexedDB:$,logger:U,http:X})));exports.PACKAGE_VERSION="2.0.1",exports.default=H,exports.initialize=w;
|
|
1
|
+
function e(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){e(n,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(i,e))}))}return n}function r(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function i(e,t){return Object.entries(t).reduce(((t,r)=>{let[s,o]=r;return n(n({},t),{},{[s]:a.isPrototypeOf(o)?new o(e.slug):"function"==typeof o?o.bind(e):"object"==typeof o&&!Array.isArray(o)&&o?i(e,o):o})}),{})}"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self)),Object.defineProperty(exports,"__esModule",{value:!0});class a{constructor(e){this.slug=e}static create(e){return class extends a{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var s=Object.freeze({__proto__:null,Agent:a});const o=new Map;function c(e,t){var n,r;null===(n=o.get(e))||void 0===n||n.forEach((r=e=>e(t),function(){try{return r(...arguments)}catch(e){console.log(e)}}))}const l=Symbol("MODULE_INITIALIZED");var d=Object.freeze({__proto__:null,MODULE_INITIALIZED:l,emit:c,off:function(e,t){const n=o.get(e);if(!n)return;const r=n.indexOf(t);-1!==r&&n.splice(r,1)},on:function(e,t){var n;o.has(e)?null===(n=o.get(e))||void 0===n||n.push(t):o.set(e,[t])}});let y=null;function u(e){y=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return y},get initConfig(){return y},setInitConfig:u});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,a=null==t||t;return n(n({serverPath:i},r(e,f)),{},{enabled:a})}function w(e){const{drs:t}=e;u(n(n({},r(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function K(e,t){const n=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const n=e[t];if(null!==n&&"object"==typeof n&&!Array.isArray(n))return n}const n={};return e[t]=n,n}),n),n]}const v="tsec",m="general";function D(e){return e?m:y.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(v))}function S(e,t){const n=e?sessionStorage:localStorage,r=t(O(e));n.setItem(v,JSON.stringify(r))}var R=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:v,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral),r=O(!!t.sessionOnly),[i]=K(r,[this.slug.toString(),n]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);return function(e,t){let n=e;return t.every((e=>!(!n||"object"!=typeof n||Array.isArray(n)||!(e in n)||(n=n[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),n,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[r,i]=K(t,[this.slug.toString(),n]);return delete r[e],i}))},setValue:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=D(!!n.isGeneral);S(!!n.sessionOnly,(n=>{const[i,a]=K(n,[this.slug.toString(),r]);return i[e]=t,a}))}});const P="RSA-PSS",k=async(e,t)=>await window.crypto.subtle.generateKey({name:e,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,t),x=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),_=async()=>await k(P,["sign"]),j=async(e,t)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:P,saltLength:32},e,n)};class I{constructor(e,t,n){this.slug=e,this.dbName=t,this.dbVersion=n}queryObjectStore(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=r,a=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,s=`${this.slug}:${this.dbName}`,o=a.open(s,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const n=o.result;(null===(t=null==n?void 0:n.objectStoreNames)||void 0===t?void 0:t.contains)&&!n.objectStoreNames.contains(e)&&n.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==r?void 0:r.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(a.deleteDatabase(s).onsuccess=()=>{this.queryObjectStore(e,t,n(n({},r),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.put({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.add({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{const t=e.target.error;i(t)}}))}))}get(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?n(null===(e=i.result)||void 0===e?void 0:e.value):n(void 0)},i.onerror=e=>{r("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.getAll(null,t);i.onsuccess=()=>{if(i.result){const e=i.result;(null==e?void 0:e.length)?n(e.map((e=>null==e?void 0:e.value))):n(e)}else n([])},i.onerror=e=>{r("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{n()},i.onerror=e=>{r(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,n)=>{this.queryObjectStore(e,(e=>{const r=e.clear();r.onsuccess=()=>{t()},r.onerror=e=>{n("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,((e,i)=>{const a=e.transaction;a.onerror=()=>{r(`Transaction failed: ${a.error}`)},a.onabort=()=>{r("Transaction aborted")},a.oncomplete=()=>{i.close(),n()};for(const n of t){let t;if("delete"===n.type)t=e.delete(n.key);else{if("put"!==n.type)return a.abort(),void r("Unknown operation type");t=e.put({key:n.key,value:n.value})}t.onerror=()=>{a.abort(),r(`Operation failed: ${t.error}`)}}}))}))}}const B="init",T="completed",E="RSA2048",N=[B,T];class A{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",n=arguments.length>2?arguments[2]:void 0;var r,i,a,s,o;this.agent=e,this.keysType=t,this.options=n,this._extractingKeysPromise=null;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(a=this.options)||void 0===a?void 0:a.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(s=this.options)||void 0===s?void 0:s.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName;const d=c?"platform":e.slug,y=this.getClientConfiguration(l,d);this.indexedDBClient=new I(y.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new I(y.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${y.clientId}`}}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(e){return window.btoa(String.fromCharCode(...new Uint8Array(e)))}async getPKRepresentations(e){const t=await crypto.subtle.exportKey("spki",e);return{arrayBufferKey:t,base64Key:this.arrayBufferToBase64(t)}}async generateKeyPair(){return"sign"==this.keysType?await _():await x()}async calcKeyIdentifier(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var e,t;const n=(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(n.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=n.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r),n})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:r}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(r);return n(n({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const n=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==n?void 0:n.isEnabled)||!n.expiryDays||void 0===n.startedAt)return!1;const r=24*n.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=n.startedAt?e.createdDate:n.startedAt;return Date.now()-i>r-2592e6}async extractMainKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getKeysRecordKey())}async extractFallbackMainKeysData(){return await this.indexedDBClientFallback.get(this.keysStoreName,this.getKeysRecordKey())}async extractRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKey())}async extractPendingRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKeyPending())}async saveKeyData(e,t){try{return await this.indexedDBClient.add(this.keysStoreName,e,t),t}catch(t){if(t instanceof DOMException&&"ConstraintError"===t.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}throw t}}async getKeysData(){const e=this.getKeysRecordKey();let t=await this.extractMainKeysData();if(t)return t;if(t=await this.extractFallbackMainKeysData(),t)return this.saveKeyData(e,t);const n=await this.generateKeyPairData();return this.saveKeyData(e,n)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),r=await this.getKeysData(),i=n(n({},r),{},{createdDate:r.createdDate||Date.now()});e=await this.saveKeyData(t,i)}return e}async getRotatedKeysData(){const e=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(e)){if(!await this.extractPendingRotatedKeysData()){const t=this.getRotatedKeysRecordKeyPending(),n=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,n)}}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId}}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),n=await j(t,e);return this.arrayBufferToBase64(n)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const e=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,e)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:E,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var e,t;if(!(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const r=await this.extractPendingRotatedKeysData();if(r){const{base64Key:e}=await this.getPKRepresentations(r.publicKey),{privateKey:t}=await this.extractKeysData(),i=n(n({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:r.createdDate,newPublicKeyType:E}),a=JSON.stringify(i);return{data:a,signature:await this.signPayload(a,t)}}const i=await this.extractRotatedKeysData();if(i&&!1===i.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,i.privateKey)}}}async signPayload(e,t){const n=await j(t,e);return this.arrayBufferToBase64(n)}async handleRotateResponse(e){if(N.includes(e))if(e===B){const e=await this.extractPendingRotatedKeysData();if(e){const t=n(n({},e),{},{confirmed:!1});await this.indexedDBClient.executeTransaction(this.keysStoreName,[{type:"delete",key:this.getRotatedKeysRecordKey()},{type:"put",key:this.getRotatedKeysRecordKey(),value:t},{type:"delete",key:this.getRotatedKeysRecordKeyPending()}]);const{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r)}}else if(e===T){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),n(n({},e),{},{confirmed:!0}))}}}var C=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:T,INIT_ROTATION_RESPONSE:B,createCryptoBinding:function(){return new A(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:x,generateRSASignKeyPair:_,signAssymetric:j,verifyAssymetric:async(e,t,n)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,n,r)}}),$=Object.freeze({__proto__:null});const L=a.create((e=>{class t extends Error{constructor(t,n){super(`${e.slug}-${t} ${n}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var M=a.create((()=>n({exceptions:L},s)));class z{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=e,this.middlewares=t,this.logs=[]}info(e,t){this.pushLog(3,e,t)}warn(e,t){this.pushLog(4,e,t)}error(e,t){this.pushLog(5,e,t)}pushLog(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:n,message:t});const r=this.middlewares.map((e=>e(this)));Promise.all(r).catch((()=>{}))}}var U=Object.freeze({__proto__:null,consoleMiddleware:function(e){const t=e.logs[e.logs.length-1];console.log(`${t.severity} ${t.message}`,t.fields)},createSdkLogger:function(){return new z(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])}});function V(e,t){if(!(null==e?void 0:e.trim()))return"";if(function(e){try{return new URL(e),!0}catch(e){return!1}}(e))return e;const n="http://mock.com",r=new URL(n);r.search=(null==t?void 0:t.toString())||"",r.pathname=e;return r.href.replace(n,"")}const q={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function F(e,t,r){var i;const a=(s=t||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:e,headers:n(n(n({},{"X-TS-body-size":String(a)}),q),r||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,n,r,i){const a=V(e,r),s=F(t,n,i);return fetch(a,s)}async function J(e,t,n,r,i){let a;if(a=await G(e,t,n,r,i),!a.ok)throw new Error("Request failed");return a}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const r=await J(e,"DELETE",void 0,void 0,t);return n(n({data:await r.json()},r),{},{headers:r.headers})},httpGet:async function(e,t,r){const i=await J(e,"GET",void 0,t,r);return n(n({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,r,i){const a=await J(e,"POST",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},httpPut:async function(e,t,r,i){const a=await J(e,"PUT",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},init:F}),H=a.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:M,storage:R,crypto:C,indexedDB:$,logger:U,http:X})));exports.PACKAGE_VERSION="2.1.0",exports.default=H,exports.initialize=w;
|
package/dist/common.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){e(n,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(i,e))}))}return n}function r(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function i(e,t){return Object.entries(t).reduce(((t,r)=>{let[s,o]=r;return n(n({},t),{},{[s]:a.isPrototypeOf(o)?new o(e.slug):"function"==typeof o?o.bind(e):"object"==typeof o&&!Array.isArray(o)&&o?i(e,o):o})}),{})}"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));class a{constructor(e){this.slug=e}static create(e){return class extends a{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var s=Object.freeze({__proto__:null,Agent:a});const o=new Map;function c(e,t){var n,r;null===(n=o.get(e))||void 0===n||n.forEach((r=e=>e(t),function(){try{return r(...arguments)}catch(e){console.log(e)}}))}const l=Symbol("MODULE_INITIALIZED");var d=Object.freeze({__proto__:null,MODULE_INITIALIZED:l,emit:c,off:function(e,t){const n=o.get(e);if(!n)return;const r=n.indexOf(t);-1!==r&&n.splice(r,1)},on:function(e,t){var n;o.has(e)?null===(n=o.get(e))||void 0===n||n.push(t):o.set(e,[t])}});let y=null;function u(e){y=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return y},get initConfig(){return y},setInitConfig:u});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,a=null==t||t;return n(n({serverPath:i},r(e,f)),{},{enabled:a})}function w(e){const{drs:t}=e;u(n(n({},r(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function K(e,t){const n=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const n=e[t];if(null!==n&&"object"==typeof n&&!Array.isArray(n))return n}const n={};return e[t]=n,n}),n),n]}const v="tsec",m="general";function D(e){return e?m:y.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(v))}function S(e,t){const n=e?sessionStorage:localStorage,r=t(O(e));n.setItem(v,JSON.stringify(r))}var R=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:v,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral),r=O(!!t.sessionOnly),[i]=K(r,[this.slug.toString(),n]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);return function(e,t){let n=e;return t.every((e=>!(!n||"object"!=typeof n||Array.isArray(n)||!(e in n)||(n=n[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),n,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[r,i]=K(t,[this.slug.toString(),n]);return delete r[e],i}))},setValue:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=D(!!n.isGeneral);S(!!n.sessionOnly,(n=>{const[i,a]=K(n,[this.slug.toString(),r]);return i[e]=t,a}))}});const P="RSA-PSS",k=async(e,t)=>await window.crypto.subtle.generateKey({name:e,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,t),x=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),_=async()=>await k(P,["sign"]),j=async(e,t)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:P,saltLength:32},e,n)};class I{constructor(e,t,n){this.slug=e,this.dbName=t,this.dbVersion=n}queryObjectStore(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=r,a=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,s=`${this.slug}:${this.dbName}`,o=a.open(s,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const n=o.result;(null===(t=null==n?void 0:n.objectStoreNames)||void 0===t?void 0:t.contains)&&!n.objectStoreNames.contains(e)&&n.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==r?void 0:r.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(a.deleteDatabase(s).onsuccess=()=>{this.queryObjectStore(e,t,n(n({},r),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.put({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.add({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{const t=e.target.error;i(t)}}))}))}get(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?n(null===(e=i.result)||void 0===e?void 0:e.value):n(void 0)},i.onerror=e=>{r("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.getAll(null,t);i.onsuccess=()=>{if(i.result){const e=i.result;(null==e?void 0:e.length)?n(e.map((e=>null==e?void 0:e.value))):n(e)}else n([])},i.onerror=e=>{r("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{n()},i.onerror=e=>{r(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,n)=>{this.queryObjectStore(e,(e=>{const r=e.clear();r.onsuccess=()=>{t()},r.onerror=e=>{n("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,((e,i)=>{const a=e.transaction;a.onerror=()=>{r(`Transaction failed: ${a.error}`)},a.onabort=()=>{r("Transaction aborted")},a.oncomplete=()=>{i.close(),n()};for(const n of t){let t;if("delete"===n.type)t=e.delete(n.key);else{if("put"!==n.type)return a.abort(),void r("Unknown operation type");t=e.put({key:n.key,value:n.value})}t.onerror=()=>{a.abort(),r(`Operation failed: ${t.error}`)}}}))}))}}const B="init",T="completed",E="RSA2048",N=[B,T];class A{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",n=arguments.length>2?arguments[2]:void 0;var r,i,a,s,o;this.agent=e,this.keysType=t,this.options=n,this._extractingKeysPromise=null;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(a=this.options)||void 0===a?void 0:a.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(s=this.options)||void 0===s?void 0:s.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName;const d=c?"platform":e.slug,y=this.getClientConfiguration(l,d);this.indexedDBClient=new I(y.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new I(y.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${y.clientId}`}}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(e){return window.btoa(String.fromCharCode(...new Uint8Array(e)))}async getPKRepresentations(e){const t=await crypto.subtle.exportKey("spki",e);return{arrayBufferKey:t,base64Key:this.arrayBufferToBase64(t)}}async generateKeyPair(){return"sign"==this.keysType?await _():await x()}async calcKeyIdentifier(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var e,t;const n=(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(n.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=n.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r),n})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:r}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(r);return n(n({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const n=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==n?void 0:n.isEnabled)||!n.expiryDays||void 0===n.startedAt)return!1;const r=24*n.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=n.startedAt?e.createdDate:n.startedAt;return Date.now()-i>r-2592e6}async extractMainKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getKeysRecordKey())}async extractFallbackMainKeysData(){return await this.indexedDBClientFallback.get(this.keysStoreName,this.getKeysRecordKey())}async extractRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKey())}async extractPendingRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKeyPending())}async saveKeyData(e,t){try{return await this.indexedDBClient.add(this.keysStoreName,e,t),t}catch(t){if(t instanceof DOMException&&"ConstraintError"===t.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}throw t}}async getKeysData(){const e=this.getKeysRecordKey();let t=await this.extractMainKeysData();if(t)return t;if(t=await this.extractFallbackMainKeysData(),t)return this.saveKeyData(e,t);const n=await this.generateKeyPairData();return this.saveKeyData(e,n)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),r=await this.getKeysData(),i=n(n({},r),{},{createdDate:r.createdDate||Date.now()});e=await this.saveKeyData(t,i)}return e}async getRotatedKeysData(){const e=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(e)){if(!await this.extractPendingRotatedKeysData()){const t=this.getRotatedKeysRecordKeyPending(),n=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,n)}}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId}}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),n=await j(t,e);return this.arrayBufferToBase64(n)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const e=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,e)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:E,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var e,t;if(!(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const r=await this.extractPendingRotatedKeysData();if(r){const{base64Key:e}=await this.getPKRepresentations(r.publicKey),{privateKey:t}=await this.extractKeysData(),i=n(n({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:r.createdDate,newPublicKeyType:E}),a=JSON.stringify(i);return{data:a,signature:await this.signPayload(a,t)}}const i=await this.extractRotatedKeysData();if(i&&!1===i.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,i.privateKey)}}}async signPayload(e,t){const n=await j(t,e);return this.arrayBufferToBase64(n)}async handleRotateResponse(e){if(N.includes(e))if(e===B){const e=await this.extractPendingRotatedKeysData();if(e){const t=n(n({},e),{},{confirmed:!1});await this.indexedDBClient.executeTransaction(this.keysStoreName,[{type:"delete",key:this.getRotatedKeysRecordKey()},{type:"put",key:this.getRotatedKeysRecordKey(),value:t},{type:"delete",key:this.getRotatedKeysRecordKeyPending()}]);const{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r)}}else if(e===T){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),n(n({},e),{},{confirmed:!0}))}}}var C=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:T,INIT_ROTATION_RESPONSE:B,createCryptoBinding:function(){return new A(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:x,generateRSASignKeyPair:_,signAssymetric:j,verifyAssymetric:async(e,t,n)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,n,r)}}),$=Object.freeze({__proto__:null});const L=a.create((e=>{class t extends Error{constructor(t,n){super(`${e.slug}-${t} ${n}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var M=a.create((()=>n({exceptions:L},s)));class z{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=e,this.middlewares=t,this.logs=[]}info(e,t){this.pushLog(3,e,t)}warn(e,t){this.pushLog(4,e,t)}error(e,t){this.pushLog(5,e,t)}pushLog(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:n,message:t});const r=this.middlewares.map((e=>e(this)));Promise.all(r).catch((()=>{}))}}var U=Object.freeze({__proto__:null,consoleMiddleware:function(e){const t=e.logs[e.logs.length-1];console.log(`${t.severity} ${t.message}`,t.fields)},createSdkLogger:function(){return new z(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])}});function q(e,t){if(!(null==e?void 0:e.trim()))return"";if(function(e){try{return new URL(e),!0}catch(e){return!1}}(e))return e;const n="http://mock.com",r=new URL(n);r.search=(null==t?void 0:t.toString())||"",r.pathname=e;return r.href.replace(n,"")}const F={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function V(e,t,r){var i;const a=(s=t||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:e,headers:n(n(n({},{"X-TS-body-size":String(a)}),F),r||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,n,r,i){const a=q(e,r),s=V(t,n,i);return fetch(a,s)}async function J(e,t,n,r,i){let a;if(a=await G(e,t,n,r,i),!a.ok)throw new Error("Request failed");return a}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const r=await J(e,"DELETE",void 0,void 0,t);return n(n({data:await r.json()},r),{},{headers:r.headers})},httpGet:async function(e,t,r){const i=await J(e,"GET",void 0,t,r);return n(n({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,r,i){const a=await J(e,"POST",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},httpPut:async function(e,t,r,i){const a=await J(e,"PUT",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},init:V}),H=a.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:M,storage:R,crypto:C,indexedDB:$,logger:U,http:X})));const Y="2.0.1";export{Y as PACKAGE_VERSION,H as default,w as initialize};
|
|
1
|
+
function e(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(n){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){e(n,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(e){Object.defineProperty(n,e,Object.getOwnPropertyDescriptor(i,e))}))}return n}function r(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],-1===t.indexOf(n)&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function i(e,t){return Object.entries(t).reduce(((t,r)=>{let[s,o]=r;return n(n({},t),{},{[s]:a.isPrototypeOf(o)?new o(e.slug):"function"==typeof o?o.bind(e):"object"==typeof o&&!Array.isArray(o)&&o?i(e,o):o})}),{})}"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));class a{constructor(e){this.slug=e}static create(e){return class extends a{constructor(t){super(t),Object.assign(this,i(this,e(this)))}}}}var s=Object.freeze({__proto__:null,Agent:a});const o=new Map;function c(e,t){var n,r;null===(n=o.get(e))||void 0===n||n.forEach((r=e=>e(t),function(){try{return r(...arguments)}catch(e){console.log(e)}}))}const l=Symbol("MODULE_INITIALIZED");var d=Object.freeze({__proto__:null,MODULE_INITIALIZED:l,emit:c,off:function(e,t){const n=o.get(e);if(!n)return;const r=n.indexOf(t);-1!==r&&n.splice(r,1)},on:function(e,t){var n;o.has(e)?null===(n=o.get(e))||void 0===n||n.push(t):o.set(e,[t])}});let y=null;function u(e){y=e}var h=Object.freeze({__proto__:null,getInitConfig:function(){return y},get initConfig(){return y},setInitConfig:u});const f=["enabled","serverPath"],g=["drs"];function p(e){if(!e)return{enabled:!1};const{enabled:t,serverPath:i}=e,a=null==t||t;return n(n({serverPath:i},r(e,f)),{},{enabled:a})}function w(e){const{drs:t}=e;u(n(n({},r(e,g)),{},{drs:p(t)})),c(l,void 0)}var b=Object.freeze({__proto__:null,initialize:w});function K(e,t){const n=!e||"object"!=typeof e||Array.isArray(e)?{}:e;return[t.reduce(((e,t)=>{if(t in e){const n=e[t];if(null!==n&&"object"==typeof n&&!Array.isArray(n))return n}const n={};return e[t]=n,n}),n),n]}const v="tsec",m="general";function D(e){return e?m:y.clientId}function O(e){return function(e){if(!e)return{};try{return JSON.parse(e)}catch(e){return{}}}((e?sessionStorage:localStorage).getItem(v))}function S(e,t){const n=e?sessionStorage:localStorage,r=t(O(e));n.setItem(v,JSON.stringify(r))}var R=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:v,GENERAL_ID_KEY:m,getValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral),r=O(!!t.sessionOnly),[i]=K(r,[this.slug.toString(),n]);return i[e]},hasValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);return function(e,t){let n=e;return t.every((e=>!(!n||"object"!=typeof n||Array.isArray(n)||!(e in n)||(n=n[e],0))),e)}(O(!!t.sessionOnly),[this.slug.toString(),n,e])},removeValue:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=D(!!t.isGeneral);S(!!t.sessionOnly,(t=>{const[r,i]=K(t,[this.slug.toString(),n]);return delete r[e],i}))},setValue:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=D(!!n.isGeneral);S(!!n.sessionOnly,(n=>{const[i,a]=K(n,[this.slug.toString(),r]);return i[e]=t,a}))}});const P="RSA-PSS",k=async(e,t)=>await window.crypto.subtle.generateKey({name:e,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,t),x=async()=>await k("RSA-OAEP",["encrypt","decrypt"]),_=async()=>await k(P,["sign"]),j=async(e,t)=>{const n=(new TextEncoder).encode(t);return await window.crypto.subtle.sign({name:P,saltLength:32},e,n)};class I{constructor(e,t,n){this.slug=e,this.dbName=t,this.dbVersion=n}queryObjectStore(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{attemptToRecoverDB:i=!0}=r,a=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB,s=`${this.slug}:${this.dbName}`,o=a.open(s,this.dbVersion||1);o.onupgradeneeded=()=>{var t;const n=o.result;(null===(t=null==n?void 0:n.objectStoreNames)||void 0===t?void 0:t.contains)&&!n.objectStoreNames.contains(e)&&n.createObjectStore(e,{keyPath:"key"})},o.onsuccess=()=>{const c=o.result;let l;try{l=c.transaction(e,(null==r?void 0:r.operation)||"readwrite")}catch(o){if(i&&o instanceof DOMException&&"NotFoundError"===o.name){c.close();return void(a.deleteDatabase(s).onsuccess=()=>{this.queryObjectStore(e,t,n(n({},r),{},{attemptToRecoverDB:!1}))})}throw o}const d=l.objectStore(e);t(d,c),l.oncomplete||(l.oncomplete=()=>{c.close()})}}put(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.put({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{i("Failed adding item to objectStore, err: "+e)}}))}))}add(e,t,n){return new Promise(((r,i)=>{this.queryObjectStore(e,(e=>{const a=e.add({key:t,value:n});a.onsuccess=()=>{r(a.result)},a.onerror=e=>{const t=e.target.error;i(t)}}))}))}get(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.get(t);i.onsuccess=()=>{var e;i.result?n(null===(e=i.result)||void 0===e?void 0:e.value):n(void 0)},i.onerror=e=>{r("Failed adding item to objectStore, err: "+e)}}))}))}getAll(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.getAll(null,t);i.onsuccess=()=>{if(i.result){const e=i.result;(null==e?void 0:e.length)?n(e.map((e=>null==e?void 0:e.value))):n(e)}else n([])},i.onerror=e=>{r("Failed getting items, err: "+e)}}))}))}delete(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,(e=>{const i=e.delete(t);i.onsuccess=()=>{n()},i.onerror=e=>{r(`Failed deleting key: '${t}' from objectStore, err: `+e)}}))}))}clear(e){return new Promise(((t,n)=>{this.queryObjectStore(e,(e=>{const r=e.clear();r.onsuccess=()=>{t()},r.onerror=e=>{n("Failed clearing objectStore, err: "+e)}}))}))}executeTransaction(e,t){return new Promise(((n,r)=>{this.queryObjectStore(e,((e,i)=>{const a=e.transaction;a.onerror=()=>{r(`Transaction failed: ${a.error}`)},a.onabort=()=>{r("Transaction aborted")},a.oncomplete=()=>{i.close(),n()};for(const n of t){let t;if("delete"===n.type)t=e.delete(n.key);else{if("put"!==n.type)return a.abort(),void r("Unknown operation type");t=e.put({key:n.key,value:n.value})}t.onerror=()=>{a.abort(),r(`Operation failed: ${t.error}`)}}}))}))}}const B="init",T="completed",E="RSA2048",N=[B,T];class A{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",n=arguments.length>2?arguments[2]:void 0;var r,i,a,s,o;this.agent=e,this.keysType=t,this.options=n,this._extractingKeysPromise=null;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope),l=null===(i=this.options)||void 0===i?void 0:i.fallbackClientId;this.keysDatabaseName=c||!(null===(a=this.options)||void 0===a?void 0:a.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(s=this.options)||void 0===s?void 0:s.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName;const d=c?"platform":e.slug,y=this.getClientConfiguration(l,d);this.indexedDBClient=new I(y.main,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new I(y.fallback,this.keysDatabaseName,this.dbVersion)}getClientConfiguration(e,t){return e?{main:t,fallback:`${t}:${e}`}:{main:t,fallback:`${t}:${y.clientId}`}}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(e){return window.btoa(String.fromCharCode(...new Uint8Array(e)))}async getPKRepresentations(e){const t=await crypto.subtle.exportKey("spki",e);return{arrayBufferKey:t,base64Key:this.arrayBufferToBase64(t)}}async generateKeyPair(){return"sign"==this.keysType?await _():await x()}async calcKeyIdentifier(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var e,t;const n=(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(n.publicKey);return this.publicKeyBase64=i,this.keyIdentifier=n.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r),n})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(e){const t=await this.generateKeyPair(),{arrayBufferKey:r}=await this.getPKRepresentations(t.publicKey),i=e||await this.calcKeyIdentifier(r);return n(n({},t),{},{keyIdentifier:i,createdDate:Date.now()})}shouldKeyBeRotated(e){var t;const n=null===(t=this.options)||void 0===t?void 0:t.keyRotation;if(!(null==n?void 0:n.isEnabled)||!n.expiryDays||void 0===n.startedAt)return!1;const r=24*n.expiryDays*60*60*1e3,i=e.createdDate&&e.createdDate>=n.startedAt?e.createdDate:n.startedAt;return Date.now()-i>r-2592e6}async extractMainKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getKeysRecordKey())}async extractFallbackMainKeysData(){return await this.indexedDBClientFallback.get(this.keysStoreName,this.getKeysRecordKey())}async extractRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKey())}async extractPendingRotatedKeysData(){return await this.indexedDBClient.get(this.keysStoreName,this.getRotatedKeysRecordKeyPending())}async saveKeyData(e,t){try{return await this.indexedDBClient.add(this.keysStoreName,e,t),t}catch(t){if(t instanceof DOMException&&"ConstraintError"===t.name){const t=await this.indexedDBClient.get(this.keysStoreName,e);if(t)return t}throw t}}async getKeysData(){const e=this.getKeysRecordKey();let t=await this.extractMainKeysData();if(t)return t;if(t=await this.extractFallbackMainKeysData(),t)return this.saveKeyData(e,t);const n=await this.generateKeyPairData();return this.saveKeyData(e,n)}async getOrCreateRotatedKeys(){let e=await this.extractRotatedKeysData();if(!e){const t=this.getRotatedKeysRecordKey(),r=await this.getKeysData(),i=n(n({},r),{},{createdDate:r.createdDate||Date.now()});e=await this.saveKeyData(t,i)}return e}async getRotatedKeysData(){const e=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(e)){if(!await this.extractPendingRotatedKeysData()){const t=this.getRotatedKeysRecordKeyPending(),n=await this.generateKeyPairData(e.keyIdentifier);await this.saveKeyData(t,n)}}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier,publicKeyId:this.publicKeyId}}async sign(e){if("sign"==this.keysType){const{privateKey:t}=await this.extractKeysData(),n=await j(t,e);return this.arrayBufferToBase64(n)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const e=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,e)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:E,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var e,t;if(!(null===(t=null===(e=this.options)||void 0===e?void 0:e.keyRotation)||void 0===t?void 0:t.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier&&this.publicKeyId||await this.extractKeysData();const r=await this.extractPendingRotatedKeysData();if(r){const{base64Key:e}=await this.getPKRepresentations(r.publicKey),{privateKey:t}=await this.extractKeysData(),i=n(n({},this.getBaseRotationPayload()),{},{newPublicKey:e,createdDate:r.createdDate,newPublicKeyType:E}),a=JSON.stringify(i);return{data:a,signature:await this.signPayload(a,t)}}const i=await this.extractRotatedKeysData();if(i&&!1===i.confirmed){await this.extractKeysData();const e=JSON.stringify(this.getBaseRotationPayload());return{data:e,signature:await this.signPayload(e,i.privateKey)}}}async signPayload(e,t){const n=await j(t,e);return this.arrayBufferToBase64(n)}async handleRotateResponse(e){if(N.includes(e))if(e===B){const e=await this.extractPendingRotatedKeysData();if(e){const t=n(n({},e),{},{confirmed:!1});await this.indexedDBClient.executeTransaction(this.keysStoreName,[{type:"delete",key:this.getRotatedKeysRecordKey()},{type:"put",key:this.getRotatedKeysRecordKey(),value:t},{type:"delete",key:this.getRotatedKeysRecordKeyPending()}]);const{arrayBufferKey:r,base64Key:i}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=i,this.keyIdentifier=e.keyIdentifier,this.publicKeyId=await this.calcKeyIdentifier(r)}}else if(e===T){const e=await this.extractRotatedKeysData();e&&!1===e.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),n(n({},e),{},{confirmed:!0}))}}}var C=Object.freeze({__proto__:null,COMPLETED_ROTATION_RESPONSE:T,INIT_ROTATION_RESPONSE:B,createCryptoBinding:function(){return new A(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",arguments.length>1?arguments[1]:void 0)},generateRSAKeyPair:x,generateRSASignKeyPair:_,signAssymetric:j,verifyAssymetric:async(e,t,n)=>{const r=(new TextEncoder).encode(t);return await window.crypto.subtle.verify(P,e,n,r)}}),$=Object.freeze({__proto__:null});const L=a.create((e=>{class t extends Error{constructor(t,n){super(`${e.slug}-${t} ${n}`)}}return{TsError:t,TsInternalError:class extends t{constructor(e){super(e,"Internal error")}}}}));var M=a.create((()=>n({exceptions:L},s)));class z{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=e,this.middlewares=t,this.logs=[]}info(e,t){this.pushLog(3,e,t)}warn(e,t){this.pushLog(4,e,t)}error(e,t){this.pushLog(5,e,t)}pushLog(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:e,fields:n,message:t});const r=this.middlewares.map((e=>e(this)));Promise.all(r).catch((()=>{}))}}var U=Object.freeze({__proto__:null,consoleMiddleware:function(e){const t=e.logs[e.logs.length-1];console.log(`${t.severity} ${t.message}`,t.fields)},createSdkLogger:function(){return new z(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:[])}});function q(e,t){if(!(null==e?void 0:e.trim()))return"";if(function(e){try{return new URL(e),!0}catch(e){return!1}}(e))return e;const n="http://mock.com",r=new URL(n);r.search=(null==t?void 0:t.toString())||"",r.pathname=e;return r.href.replace(n,"")}const F={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function V(e,t,r){var i;const a=(s=t||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:e,headers:n(n(n({},{"X-TS-body-size":String(a)}),F),r||{}),body:null!==(i=t&&JSON.stringify(t||{}))&&void 0!==i?i:void 0}}function G(e,t,n,r,i){const a=q(e,r),s=V(t,n,i);return fetch(a,s)}async function J(e,t,n,r,i){let a;if(a=await G(e,t,n,r,i),!a.ok)throw new Error("Request failed");return a}var X=Object.freeze({__proto__:null,httpDelete:async function(e,t){const r=await J(e,"DELETE",void 0,void 0,t);return n(n({data:await r.json()},r),{},{headers:r.headers})},httpGet:async function(e,t,r){const i=await J(e,"GET",void 0,t,r);return n(n({data:await i.json()},i),{},{headers:i.headers})},httpPost:async function(e,t,r,i){const a=await J(e,"POST",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},httpPut:async function(e,t,r,i){const a=await J(e,"PUT",t,r,i);return n(n({data:await a.json()},a),{},{headers:a.headers})},init:V}),H=a.create((()=>({events:d,moduleMetadata:h,mainEntry:b,utils:M,storage:R,crypto:C,indexedDB:$,logger:U,http:X})));const Y="2.1.0";export{Y as PACKAGE_VERSION,H as default,w as initialize};
|