@transmitsecurity/platform-web-sdk 1.15.0 → 1.16.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 -1
- package/README.md +6 -18
- package/build/ido/idoImpl.d.ts +2 -0
- package/build/ido/idoImpl.js +4 -0
- package/build/ido/index.d.ts +7 -0
- package/build/ido/index.js +9 -0
- package/bundler-config.json +2 -3
- package/dist/docs/modules.md +1 -1
- package/dist/drs.cjs +1 -1
- package/dist/drs.d.ts +9 -2
- package/dist/drs.js +1 -1
- package/dist/ido.cjs +3 -1
- package/dist/ido.d.ts +51 -2
- package/dist/ido.js +3 -1
- package/dist/idv.cjs +1 -1
- package/dist/idv.d.ts +1 -0
- package/dist/idv.js +1 -1
- package/dist/index.cjs +3 -1
- package/dist/index.esm.js +3 -1
- package/dist/index.umd.js +3 -1
- package/dist/ts-platform-websdk.js +3 -1
- package/dist/web-sdk-drs+idv+webauthn+ido.js +3 -1
- package/dist/web-sdk.d.ts +41 -7
- package/dist/webauthn.cjs +1 -1
- package/dist/webauthn.d.ts +4 -2
- package/dist/webauthn.js +1 -1
- package/package.json +8 -7
- package/scripts/upload-dist.sh +3 -0
- package/VITE_CONFIG.md +0 -107
package/dist/web-sdk.d.ts
CHANGED
|
@@ -241,8 +241,19 @@ declare const webSdkModule_d_setUser: typeof setUser;
|
|
|
241
241
|
declare const webSdkModule_d_triggerActionEvent: typeof triggerActionEvent;
|
|
242
242
|
declare const webSdkModule_d_unidentifiedUser: typeof unidentifiedUser;
|
|
243
243
|
declare namespace webSdkModule_d {
|
|
244
|
-
export {
|
|
245
|
-
|
|
244
|
+
export {
|
|
245
|
+
webSdkModule_d_ActionEventOptions as ActionEventOptions,
|
|
246
|
+
webSdkModule_d_ActionResponse as ActionResponse,
|
|
247
|
+
webSdkModule_d___internal as __internal,
|
|
248
|
+
webSdkModule_d_clearUser as clearUser,
|
|
249
|
+
webSdkModule_d_getActions as getActions,
|
|
250
|
+
webSdkModule_d_getSessionToken as getSessionToken,
|
|
251
|
+
webSdkModule_d_identifyUser as identifyUser,
|
|
252
|
+
webSdkModule_d_setAuthenticatedUser as setAuthenticatedUser,
|
|
253
|
+
webSdkModule_d_setUser as setUser,
|
|
254
|
+
webSdkModule_d_triggerActionEvent as triggerActionEvent,
|
|
255
|
+
webSdkModule_d_unidentifiedUser as unidentifiedUser,
|
|
256
|
+
};
|
|
246
257
|
}
|
|
247
258
|
|
|
248
259
|
/**
|
|
@@ -793,8 +804,32 @@ declare const index_d_isAutofillSupported: typeof isAutofillSupported;
|
|
|
793
804
|
declare const index_d_isPlatformAuthenticatorSupported: typeof isPlatformAuthenticatorSupported;
|
|
794
805
|
declare const index_d_register: typeof register;
|
|
795
806
|
declare namespace index_d {
|
|
796
|
-
export {
|
|
797
|
-
|
|
807
|
+
export {
|
|
808
|
+
index_d_ApiCrossDeviceStatusResponse as ApiCrossDeviceStatusResponse,
|
|
809
|
+
index_d_AttachDeviceResult as AttachDeviceResult,
|
|
810
|
+
index_d_AuthenticationAutofillActivateHandlers as AuthenticationAutofillActivateHandlers,
|
|
811
|
+
index_d_AutofillHandlers as AutofillHandlers,
|
|
812
|
+
index_d_CrossDeviceAuthenticationHandlers as CrossDeviceAuthenticationHandlers,
|
|
813
|
+
index_d_CrossDeviceController as CrossDeviceController,
|
|
814
|
+
index_d_CrossDeviceRegistrationHandlers as CrossDeviceRegistrationHandlers,
|
|
815
|
+
ErrorCode$1 as ErrorCode,
|
|
816
|
+
index_d_SdkError as SdkError,
|
|
817
|
+
index_d_WebauthnApis as WebauthnApis,
|
|
818
|
+
index_d_WebauthnApprovalFlows as WebauthnApprovalFlows,
|
|
819
|
+
index_d_WebauthnAuthenticationFlows as WebauthnAuthenticationFlows,
|
|
820
|
+
index_d_WebauthnAuthenticationOptions as WebauthnAuthenticationOptions,
|
|
821
|
+
index_d_WebauthnCrossDeviceFlows as WebauthnCrossDeviceFlows,
|
|
822
|
+
index_d_WebauthnCrossDeviceRegistrationOptions as WebauthnCrossDeviceRegistrationOptions,
|
|
823
|
+
index_d_WebauthnCrossDeviceStatus as WebauthnCrossDeviceStatus,
|
|
824
|
+
index_d_WebauthnRegistrationOptions as WebauthnRegistrationOptions,
|
|
825
|
+
index_d_approve as approve,
|
|
826
|
+
index_d_authenticate as authenticate,
|
|
827
|
+
index_d_crossDevice as crossDevice,
|
|
828
|
+
index_d_getDefaultPaths as getDefaultPaths,
|
|
829
|
+
index_d_isAutofillSupported as isAutofillSupported,
|
|
830
|
+
index_d_isPlatformAuthenticatorSupported as isPlatformAuthenticatorSupported,
|
|
831
|
+
index_d_register as register,
|
|
832
|
+
};
|
|
798
833
|
}
|
|
799
834
|
|
|
800
835
|
/**
|
|
@@ -1731,7 +1766,6 @@ declare class TSWebSDK {
|
|
|
1731
1766
|
}
|
|
1732
1767
|
declare const _default: TSWebSDK;
|
|
1733
1768
|
|
|
1734
|
-
declare const PACKAGE_VERSION = "1.
|
|
1769
|
+
declare const PACKAGE_VERSION = "1.16.0";
|
|
1735
1770
|
|
|
1736
|
-
export { ErrorCode$1 as ErrorCode, PACKAGE_VERSION, authenticate, crossDevice, _default as default, webSdkModule_d as drs, getDefaultPaths, instance as ido, index_d$1 as idv, initialize, isAutofillSupported, isPlatformAuthenticatorSupported, register, index_d as webauthn };
|
|
1737
|
-
export type { ActionEventOptions, ActionResponse, AuthenticationAutofillActivateHandlers, AutofillHandlers, CrossDeviceController, SdkError, WebauthnApis, WebauthnAuthenticationFlows, WebauthnCrossDeviceFlows, WebauthnCrossDeviceRegistrationOptions, WebauthnRegistrationOptions, initConfigParams };
|
|
1771
|
+
export { ActionEventOptions, ActionResponse, AuthenticationAutofillActivateHandlers, AutofillHandlers, CrossDeviceController, ErrorCode$1 as ErrorCode, PACKAGE_VERSION, SdkError, WebauthnApis, WebauthnAuthenticationFlows, WebauthnCrossDeviceFlows, WebauthnCrossDeviceRegistrationOptions, WebauthnRegistrationOptions, authenticate, crossDevice, _default as default, webSdkModule_d as drs, getDefaultPaths, instance as ido, index_d$1 as idv, initConfigParams, initialize, isAutofillSupported, isPlatformAuthenticatorSupported, register, index_d as webauthn };
|
package/dist/webauthn.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));const t=Symbol("MODULE_INITIALIZED"),e=new Map;function i(t,i){var n,r;null===(n=e.get(t))||void 0===n||n.forEach((r=t=>t(i),function(){try{return r(...arguments)}catch(t){console.log(t)}}))}let n=null;function r(t){n=t}var s=Object.freeze({__proto__:null,getInitConfig:function(){return n},get initConfig(){return n},setInitConfig:r});function a(e){r(e),i(t,void 0)}var o=Object.freeze({__proto__:null,initialize:a});function c(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,n)}return i}function l(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?c(Object(i),!0).forEach((function(e){d(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):c(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function u(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function d(t,e,i){return(e=u(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function h(t,e){return Object.entries(e).reduce(((e,i)=>{let[n,r]=i;return l(l({},e),{},{[n]:p.isPrototypeOf(r)?new r(t.slug):"function"==typeof r?r.bind(t):"object"==typeof r&&!Array.isArray(r)&&r?h(t,r):r})}),{})}class p{constructor(t){this.slug=t}static create(t){return class extends p{constructor(e){super(e),Object.assign(this,h(this,t(this)))}}}}var y=Object.freeze({__proto__:null,Agent:p}),v=Object.freeze({__proto__:null,MODULE_INITIALIZED:t,emit:i,off:function(t,i){const n=e.get(t);if(!n)return;const r=n.indexOf(i);-1!==r&&n.splice(r,1)},on:function(t,i){var n;e.has(t)?null===(n=e.get(t))||void 0===n||n.push(i):e.set(t,[i])}});function g(t,e){const i=!t||"object"!=typeof t||Array.isArray(t)?{}:t;return[e.reduce(((t,e)=>{if(e in t){const i=t[e];if(null!==i&&"object"==typeof i&&!Array.isArray(i))return i}const i={};return t[e]=i,i}),i),i]}function f(t,e){let i=t;return e.every((t=>!(!i||"object"!=typeof i||Array.isArray(i)||!(t in i))&&(i=i[t],!0)),t)}const w="tsec",m="general";function b(t){return t?m:n.clientId}function A(t){return function(t){if(!t)return{};try{return JSON.parse(t)}catch(t){return{}}}((t?sessionStorage:localStorage).getItem(w))}function S(t,e){const i=t?sessionStorage:localStorage,n=e(A(t));i.setItem(w,JSON.stringify(n))}var C=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:w,GENERAL_ID_KEY:m,getValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),n=A(!!e.sessionOnly),[r]=g(n,[this.slug.toString(),i]);return r[t]},hasValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),n=A(!!e.sessionOnly);return f(n,[this.slug.toString(),i,t])},removeValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral);S(!!e.sessionOnly,(e=>{const[n,r]=g(e,[this.slug.toString(),i]);return delete n[t],r}))},setValue:function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=b(!!i.isGeneral);S(!!i.sessionOnly,(i=>{const[r,s]=g(i,[this.slug.toString(),n]);return r[t]=e,s}))}});const _="RSA-OAEP",D="RSA-PSS",k=async(t,e)=>await window.crypto.subtle.generateKey({name:t,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,e),T=async()=>await k(_,["encrypt","decrypt"]),I=async()=>await k(D,["sign"]),P=async(t,e)=>await window.crypto.subtle.encrypt({name:_},e,t),O=async(t,e)=>{const i=(new TextEncoder).encode(e);return await window.crypto.subtle.sign({name:D,saltLength:32},t,i)};class j{constructor(t,e,i){this.slug=t,this.dbName=e,this.dbVersion=i}queryObjectStore(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB).open(`${this.slug}:${this.dbName}`,this.dbVersion||1);n.onupgradeneeded=()=>{var e;const i=n.result;(null===(e=null==i?void 0:i.objectStoreNames)||void 0===e?void 0:e.contains)&&!i.objectStoreNames.contains(t)&&i.createObjectStore(t,{keyPath:"key"})},n.onsuccess=()=>{const r=n.result,s=r.transaction(t,(null==i?void 0:i.operation)||"readwrite"),a=s.objectStore(t);e(a),s.oncomplete=()=>{r.close()}}}put(t,e,i){return new Promise(((n,r)=>{this.queryObjectStore(t,(t=>{const s=t.put({key:e,value:i});s.onsuccess=()=>{n(s.result)},s.onerror=t=>{r("Failed adding item to objectStore, err: "+t)}}))}))}get(t,e){return new Promise(((i,n)=>{this.queryObjectStore(t,(t=>{const r=t.get(e);r.onsuccess=()=>{var t;r.result?i(null===(t=r.result)||void 0===t?void 0:t.value):i(void 0)},r.onerror=t=>{n("Failed adding item to objectStore, err: "+t)}}))}))}getAll(t,e){return new Promise(((i,n)=>{this.queryObjectStore(t,(t=>{const r=t.getAll(null,e);r.onsuccess=()=>{if(r.result){const t=r.result;(null==t?void 0:t.length)?i(t.map((t=>null==t?void 0:t.value))):i(t)}else i([])},r.onerror=t=>{n("Failed getting items, err: "+t)}}))}))}delete(t,e){return new Promise(((i,n)=>{this.queryObjectStore(t,(t=>{const r=t.delete(e);r.onsuccess=()=>{i()},r.onerror=t=>{n(`Failed deleting key: '${e}' from objectStore, err: `+t)}}))}))}clear(t){return new Promise(((e,i)=>{this.queryObjectStore(t,(t=>{const n=t.clear();n.onsuccess=()=>{e()},n.onerror=t=>{i("Failed clearing objectStore, err: "+t)}}))}))}}const R="platform";class K{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",i=arguments.length>2?arguments[2]:void 0;var r,s,a,o;this.agent=t,this.keysType=e,this.options=i;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope);this.keysDatabaseName=c||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(a=this.options)||void 0===a?void 0:a.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName,this.indexedDBClient=new j(c?R:t.slug,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new j((c?R:t.slug)+`:${n.clientId}`,this.keysDatabaseName,this.dbVersion)}getKeysRecordKey(){return`${this.keysType}_keys`}arrayBufferToBase64(t){return window.btoa(String.fromCharCode(...new Uint8Array(t)))}async getPKRepresentations(t){const e=await crypto.subtle.exportKey("spki",t);return{arrayBufferKey:e,base64Key:this.arrayBufferToBase64(e)}}async generateKeyPair(){return"sign"==this.keysType?await I():await T()}async calcKeyIdentifier(t){const e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map((t=>t.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){const t=this.getKeysRecordKey();let e=await this.indexedDBClient.get(this.keysStoreName,t);if(!e){if(e=await this.indexedDBClientFallback.get(this.keysStoreName,t),!e){const t=await this.generateKeyPair(),{arrayBufferKey:i,base64Key:n}=await this.getPKRepresentations(t.publicKey);this.publicKeyBase64=n,this.keyIdentifier=await this.calcKeyIdentifier(i),e=l(l({},t),{},{keyIdentifier:this.keyIdentifier})}await this.indexedDBClient.put(this.keysStoreName,t,e)}if(!this.publicKeyBase64){const{base64Key:t}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=t,this.keyIdentifier=e.keyIdentifier}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier}}async sign(t){if("sign"==this.keysType){const{privateKey:e}=await this.extractKeysData(),i=await O(e,t);return this.arrayBufferToBase64(i)}throw new Error("keysType must be 'sign' in order to use sign keys")}async encrypt(t){if("encrypt"==this.keysType){const{privateKey:e}=await this.extractKeysData();return await P(t,e)}throw new Error("keysType must be 'encrypt' in order to use encryption keys")}async clearKeys(){const t=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,t)}}var x=Object.freeze({__proto__:null,createCryptoBinding:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",e=arguments.length>1?arguments[1]:void 0;return new K(this,t,e)},decryptAssymetric:async(t,e)=>new Uint8Array(await window.crypto.subtle.decrypt({name:_},e,t)),encryptAssymetric:P,generateRSAKeyPair:T,generateRSASignKeyPair:I,signAssymetric:O,verifyAssymetric:async(t,e,i)=>{const n=(new TextEncoder).encode(e);return await window.crypto.subtle.verify(D,t,i,n)}}),B=Object.freeze({__proto__:null});const E=p.create((t=>{class e extends Error{constructor(e,i){super(`${t.slug}-${e} ${i}`)}}return{TsError:e,TsInternalError:class extends e{constructor(t){super(t,"Internal error")}}}}));var N=p.create((()=>l({exceptions:E},y)));class H{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=t,this.middlewares=e,this.logs=[]}info(t,e){this.pushLog(3,t,e)}warn(t,e){this.pushLog(4,t,e)}error(t,e){this.pushLog(5,t,e)}pushLog(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:t,fields:i,message:e});const n=this.middlewares.map((t=>t(this)));Promise.all(n).catch((()=>{}))}}var F=Object.freeze({__proto__:null,consoleMiddleware:function(t){const e=t.logs[t.logs.length-1];console.log(`${e.severity} ${e.message}`,e.fields)},createSdkLogger:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return new H(this,t)}});function z(t,e){if(!(null==t?void 0:t.trim()))return"";if(function(t){try{return new URL(t),!0}catch(t){return!1}}(t))return t;const i="http://mock.com",n=new URL(i);n.search=(null==e?void 0:e.toString())||"",n.pathname=t;return n.href.replace(i,"")}const q={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function M(t,e,i){var n;const r=(s=e||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:t,headers:l(l(l({},{"X-TS-body-size":String(r)}),q),i||{}),body:null!==(n=e&&JSON.stringify(e||{}))&&void 0!==n?n:void 0}}function $(t,e,i,n,r){const s=z(t,n),a=M(e,i,r);return fetch(s,a)}async function W(t,e,i,n,r){let s;if(s=await $(t,e,i,n,r),!s.ok)throw new Error("Request failed");return s}var J=Object.freeze({__proto__:null,httpDelete:async function(t,e){const i=await W(t,"DELETE",void 0,void 0,e);return l(l({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(t,e,i){const n=await W(t,"GET",void 0,e,i);return l(l({data:await n.json()},n),{},{headers:n.headers})},httpPost:async function(t,e,i,n){const r=await W(t,"POST",e,i,n);return l(l({data:await r.json()},r),{},{headers:r.headers})},httpPut:async function(t,e,i,n){const r=await W(t,"PUT",e,i,n);return l(l({data:await r.json()},r),{},{headers:r.headers})},init:M}),L=p.create((()=>({events:v,moduleMetadata:s,mainEntry:o,utils:N,storage:C,crypto:x,indexedDB:B,logger:F,http:J})));class U{static arrayBufferToBase64(t){return btoa(String.fromCharCode(...new Uint8Array(t)))}static base64ToArrayBuffer(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}static stringToBase64(t){return btoa(t)}static jsonToBase64(t){const e=JSON.stringify(t);return btoa(e)}static base64ToJson(t){const e=atob(t);return JSON.parse(e)}}const V={log:console.log,error:console.error};var G,Z;!function(t){t.NotInitialized="not_initialized",t.AuthenticationFailed="authentication_failed",t.AuthenticationAbortedTimeout="authentication_aborted_timeout",t.AuthenticationCanceled="webauthn_authentication_canceled",t.RegistrationFailed="registration_failed",t.AlreadyRegistered="username_already_registered",t.RegistrationAbortedTimeout="registration_aborted_timeout",t.RegistrationCanceled="webauthn_registration_canceled",t.AutofillAuthenticationAborted="autofill_authentication_aborted",t.AuthenticationProcessAlreadyActive="authentication_process_already_active",t.InvalidApprovalData="invalid_approval_data",t.FailedToInitCrossDeviceSession="cross_device_init_failed",t.FailedToGetCrossDeviceStatus="cross_device_status_failed",t.Unknown="unknown"}(G||(G={}));class X extends Error{constructor(t,e){super(t),this.errorCode=G.NotInitialized,this.data=e}}class Y extends X{constructor(t,e){super(null!=t?t:"WebAuthnSdk is not initialized",e),this.errorCode=G.NotInitialized}}class Q extends X{constructor(t,e){super(null!=t?t:"Authentication failed with an error",e),this.errorCode=G.AuthenticationFailed}}class tt extends X{constructor(t,e){super(null!=t?t:"Authentication was canceled by the user or got timeout",e),this.errorCode=G.AuthenticationCanceled}}class et extends X{constructor(t,e){super(null!=t?t:"Registration failed with an error",e),this.errorCode=G.RegistrationFailed}}class it extends X{constructor(t,e){super(null!=t?t:"Registration was canceled by the user or got timeout",e),this.errorCode=G.RegistrationCanceled}}class nt extends X{constructor(t){super(null!=t?t:"Autofill flow was aborted"),this.errorCode=G.AutofillAuthenticationAborted}}class rt extends X{constructor(t){super(null!=t?t:"Operation was aborted by timeout"),this.errorCode=G.AutofillAuthenticationAborted}}class st extends X{constructor(t){super(null!=t?t:"Passkey with this username is already registered with the relying party."),this.errorCode=G.AlreadyRegistered}}class at extends X{constructor(t,e){super(null!=t?t:"Authentication process is already active",e),this.errorCode=G.AuthenticationProcessAlreadyActive}}class ot extends X{constructor(t,e){super(null!=t?t:"Invalid approval data",e),this.errorCode=G.InvalidApprovalData}}class ct extends X{constructor(t,e){super(null!=t?t:"Failed to init cross device authentication",e),this.errorCode=G.FailedToInitCrossDeviceSession}}class lt extends X{constructor(t,e){super(null!=t?t:"Failed to get cross device status",e),this.errorCode=G.FailedToGetCrossDeviceStatus}}function ut(t){return t.errorCode&&Object.values(G).includes(t.errorCode)}!function(t){t[t.persistent=0]="persistent",t[t.session=1]="session"}(Z||(Z={}));class dt{static get(t){return dt.getStorageMedium(dt.allowedKeys[t]).getItem(dt.getStorageKey(t))||void 0}static set(t,e){return dt.getStorageMedium(dt.allowedKeys[t]).setItem(dt.getStorageKey(t),e)}static remove(t){dt.getStorageMedium(dt.allowedKeys[t]).removeItem(dt.getStorageKey(t))}static clear(t){for(const[e,i]of Object.entries(dt.allowedKeys)){const n=e;t&&this.configurationKeys.includes(n)||dt.getStorageMedium(i).removeItem(dt.getStorageKey(n))}}static getStorageKey(t){return`WebAuthnSdk:${t}`}static getStorageMedium(t){return t===Z.session?sessionStorage:localStorage}}dt.allowedKeys={clientId:Z.session},dt.configurationKeys=["clientId"];class ht{static isNewApiDomain(t){return t&&(this.newApiDomains.includes(t)||t.startsWith("api.")&&t.endsWith(".transmitsecurity.io"))}static dnsPrefetch(t){const e=document.createElement("link");e.rel="dns-prefetch",e.href=t,document.head.appendChild(e)}static preconnect(t,e){const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}static warmupConnection(t){this.dnsPrefetch(t),this.preconnect(t,!1),this.preconnect(t,!0)}static init(t,e){var i,n;try{this._serverPath=new URL(e.serverPath),this.isNewApiDomain(null===(i=this._serverPath)||void 0===i?void 0:i.hostname)&&this.warmupConnection(this._serverPath.origin),this._apiPaths=null!==(n=e.webauthnApiPaths)&&void 0!==n?n:this.getDefaultPaths(),this._clientId=t,dt.set("clientId",t)}catch(t){throw new Y("Invalid options.serverPath",{error:t})}}static getDefaultPaths(){var t;const e=this.isNewApiDomain(null===(t=this._serverPath)||void 0===t?void 0:t.hostname)?"/cis":"";return{startAuthentication:`${e}/v1/auth/webauthn/authenticate/start`,startRegistration:`${e}/v1/auth/webauthn/register/start`,initCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/init`,startCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/start`,startCrossDeviceRegistration:`${e}/v1/auth/webauthn/cross-device/register/start`,getCrossDeviceTicketStatus:`${e}/v1/auth/webauthn/cross-device/status`,attachDeviceToCrossDeviceSession:`${e}/v1/auth/webauthn/cross-device/attach-device`}}static getApiPaths(){return this._apiPaths}static async sendRequest(t,e,i){V.log(`[WebAuthn SDK] Calling ${e.method} ${t}...`);const n=new URL(this._serverPath);return n.pathname=t,i&&(n.search=i),fetch(n.toString(),e)}static async startRegistration(t){const e=await this.sendRequest(this._apiPaths.startRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId(),username:t.username,display_name:t.displayName},t.timeout&&{timeout:t.timeout}),t.limitSingleCredentialToDevice&&{limit_single_credential_to_device:t.limitSingleCredentialToDevice}))});if(!(null==e?void 0:e.ok))throw new Q("Failed to start registration",null==e?void 0:e.body);return await e.json()}static async startAuthentication(t){const e=await this.sendRequest(this._apiPaths.startAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}),t.timeout&&{timeout:t.timeout}))});if(!(null==e?void 0:e.ok))throw new Q("Failed to start authentication",null==e?void 0:e.body);return await e.json()}static async initCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.initCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}))});if(!(null==e?void 0:e.ok))throw new ct(void 0,null==e?void 0:e.body);return await e.json()}static async getCrossDeviceTicketStatus(t){const e=await this.sendRequest(this._apiPaths.getCrossDeviceTicketStatus,{method:"GET"},`cross_device_ticket_id=${t.ticketId}`);if(!(null==e?void 0:e.ok))throw new lt(void 0,null==e?void 0:e.body);return await e.json()}static async startCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new Q("Failed to start cross device authentication",null==e?void 0:e.body);return await e.json()}static async startCrossDeviceRegistration(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new et("Failed to start cross device registration",null==e?void 0:e.body);return await e.json()}static async attachDeviceToCrossDeviceSession(t){const e=await this.sendRequest(this._apiPaths.attachDeviceToCrossDeviceSession,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new et("Failed to attach device to cross device session",null==e?void 0:e.body);return await e.json()}static getValidatedClientId(){var t;const e=null!==(t=this._clientId)&&void 0!==t?t:dt.get("clientId");if(!e)throw new Y("Missing clientId");return e}}var pt,yt,vt,gt;ht.newApiDomains=["api.idsec-dev.com","api.idsec-stg.com"],function(t){t.InputAutofill="input-autofill",t.Modal="modal"}(pt||(pt={})),exports.WebauthnCrossDeviceStatus=void 0,(yt=exports.WebauthnCrossDeviceStatus||(exports.WebauthnCrossDeviceStatus={})).Pending="pending",yt.Scanned="scanned",yt.Success="success",yt.Error="error",yt.Timeout="timeout",yt.Aborted="aborted",function(t){t.toAuthenticationError=t=>ut(t)?t:"NotAllowedError"===t.name?new tt:"OperationError"===t.name?new at(t.message):"SecurityError"===t.name?new Q(t.message):t===G.AuthenticationAbortedTimeout?new rt:"AbortError"===t.name||t===G.AutofillAuthenticationAborted?new nt:new Q("Something went wrong during authentication",{error:t}),t.toRegistrationError=t=>ut(t)?t:"NotAllowedError"===t.name?new it:"SecurityError"===t.name?new et(t.message):"InvalidStateError"===t.name?new st:t===G.RegistrationAbortedTimeout?new rt:new et("Something went wrong during registration",{error:t})}(vt||(vt={})),function(t){t.processCredentialRequestOptions=t=>l(l({},t),{},{challenge:U.base64ToArrayBuffer(t.challenge),allowCredentials:t.allowCredentials.map((t=>l(l({},t),{},{id:U.base64ToArrayBuffer(t.id)})))}),t.processCredentialCreationOptions=(t,e)=>{var i;const n=JSON.parse(JSON.stringify(t));return n.challenge=U.base64ToArrayBuffer(t.challenge),n.user.id=U.base64ToArrayBuffer(t.user.id),(null==e?void 0:e.limitSingleCredentialToDevice)&&(n.excludeCredentials=null===(i=t.excludeCredentials)||void 0===i?void 0:i.map((t=>l(l({},t),{},{id:U.base64ToArrayBuffer(t.id)})))),(null==e?void 0:e.registerAsDiscoverable)?(n.authenticatorSelection.residentKey="preferred",n.authenticatorSelection.requireResidentKey=!0):(n.authenticatorSelection.residentKey="discouraged",n.authenticatorSelection.requireResidentKey=!1),n.authenticatorSelection.authenticatorAttachment=(null==e?void 0:e.allowCrossPlatformAuthenticators)?void 0:"platform",n},t.encodeAuthenticationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:U.arrayBufferToBase64(t.rawId),response:{authenticatorData:U.arrayBufferToBase64(i.authenticatorData),clientDataJSON:U.arrayBufferToBase64(i.clientDataJSON),signature:U.arrayBufferToBase64(i.signature),userHandle:U.arrayBufferToBase64(i.userHandle)},authenticatorAttachment:e,type:t.type}},t.encodeRegistrationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:U.arrayBufferToBase64(t.rawId),response:{attestationObject:U.arrayBufferToBase64(i.attestationObject),clientDataJSON:U.arrayBufferToBase64(i.clientDataJSON)},authenticatorAttachment:e,type:t.type}}}(gt||(gt={}));class ft{async modal(t){try{const e=await this.performAuthentication(l(l({},t),{},{mediationType:pt.Modal}));return U.jsonToBase64(e)}catch(t){throw vt.toAuthenticationError(t)}}activateAutofill(t,e){const{onSuccess:i,onError:n,onReady:r}=t;this.performAuthentication({username:e,mediationType:pt.InputAutofill,onReady:r}).then((t=>{i(U.jsonToBase64(t))})).catch((t=>{const e=vt.toAuthenticationError(t);if(!n)throw e;n(e)}))}abortAutofill(){this.abortController&&this.abortController.abort(G.AutofillAuthenticationAborted)}abortAuthentication(){this.abortController&&this.abortController.abort(G.AuthenticationAbortedTimeout)}async performAuthentication(t){var e,i;const n="crossDeviceTicketId"in t?await ht.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await ht.startAuthentication({username:t.username,timeout:null===(e=t.options)||void 0===e?void 0:e.timeout}),r=n.credential_request_options,s=gt.processCredentialRequestOptions(r),a=this.getMediatedCredentialRequest(s,t.mediationType);t.mediationType===pt.InputAutofill&&(null===(i=t.onReady)||void 0===i||i.call(t));const o=await navigator.credentials.get(a).catch((t=>{throw vt.toAuthenticationError(t)}));return{webauthnSessionId:n.webauthn_session_id,publicKeyCredential:gt.encodeAuthenticationResult(o),userAgent:navigator.userAgent}}getMediatedCredentialRequest(t,e){const i={publicKey:t};return this.abortController=new AbortController,i.signal=this.abortController&&this.abortController.signal,e===pt.InputAutofill?i.mediation="conditional":t.timeout&&setTimeout((()=>{this.abortAuthentication()}),t.timeout),i}}class wt{constructor(t,e){this.handler=t,this.intervalInMs=e}begin(){var t;this.intervalId=window.setInterval((t=this.handler,async function(){t.isRunning||(t.isRunning=!0,await t(...arguments),t.isRunning=!1)}),this.intervalInMs)}stop(){clearInterval(this.intervalId)}}const mt=/^[A-Za-z0-9\-_.: ]*$/;function bt(t){if(t&&(!function(t){return Object.keys(t).length<=10}(t)||!function(t){const e=t=>"string"==typeof t,i=t=>mt.test(t);return Object.keys(t).every((n=>e(n)&&e(t[n])&&i(n)&&i(t[n])))}(t)))throw V.error("Failed validating approval data"),new ot("Provided approval data should have 10 properties max. Also, it should contain only \n alphanumeric characters, numbers, and the special characters: '-', '_', '.'")}class At{constructor(t,e,i){this.authenticationHandler=t,this.registrationHandler=e,this.approvalHandler=i,this.init={registration:async t=>(this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(t.crossDeviceTicketId,t.handlers)),authentication:async t=>{const{username:e}=t,i=(await ht.initCrossDeviceAuthentication(l({},e&&{username:e}))).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(i,t.handlers)},approval:async t=>{const{username:e,approvalData:i}=t;bt(i);const n=(await ht.initCrossDeviceAuthentication({username:e,approvalData:i})).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(n,t.handlers)}},this.authenticate={modal:async t=>this.authenticationHandler.modal({crossDeviceTicketId:t})},this.approve={modal:async t=>this.approvalHandler.modal({crossDeviceTicketId:t})}}async register(t,e){return this.registrationHandler.register({crossDeviceTicketId:t},e)}async attachDevice(t){const e=await ht.attachDeviceToCrossDeviceSession({ticketId:t});return l({status:e.status,startedAt:e.started_at},e.approval_data&&{approvalData:e.approval_data})}async pollCrossDeviceSession(t,e){return this.poller=new wt((async()=>{var i,n;const r=await ht.getCrossDeviceTicketStatus({ticketId:t}),s=r.status;if(s!==this.ticketStatus)switch(this.ticketStatus=s,s){case exports.WebauthnCrossDeviceStatus.Scanned:await e.onDeviceAttach();break;case exports.WebauthnCrossDeviceStatus.Error:case exports.WebauthnCrossDeviceStatus.Timeout:case exports.WebauthnCrossDeviceStatus.Aborted:await e.onFailure(r),null===(i=this.poller)||void 0===i||i.stop();break;case exports.WebauthnCrossDeviceStatus.Success:if("onCredentialRegister"in e)await e.onCredentialRegister();else{if(!r.session_id)throw new lt("Cross device session is complete without returning session_id",r);await e.onCredentialAuthenticate(r.session_id)}null===(n=this.poller)||void 0===n||n.stop()}}),1e3),this.poller.begin(),setTimeout((()=>{var t;null===(t=this.poller)||void 0===t||t.stop(),e.onFailure({status:exports.WebauthnCrossDeviceStatus.Timeout})}),3e5),{crossDeviceTicketId:t,stop:()=>{var t;null===(t=this.poller)||void 0===t||t.stop()}}}}class St{async register(t,e){this.abortController=new AbortController;const i=l({allowCrossPlatformAuthenticators:!("crossDeviceTicketId"in t),registerAsDiscoverable:!0},e);try{const n="crossDeviceTicketId"in t?await ht.startCrossDeviceRegistration({ticketId:t.crossDeviceTicketId}):await ht.startRegistration({username:t.username,displayName:(null==e?void 0:e.displayName)||t.username,timeout:null==e?void 0:e.timeout,limitSingleCredentialToDevice:null==e?void 0:e.limitSingleCredentialToDevice}),r=gt.processCredentialCreationOptions(n.credential_creation_options,i);setTimeout((()=>{this.abortRegistration()}),r.timeout);const s=await this.registerCredential(r),a={webauthnSessionId:n.webauthn_session_id,publicKeyCredential:s,userAgent:navigator.userAgent};return U.jsonToBase64(a)}catch(t){throw vt.toRegistrationError(t)}}abortRegistration(){this.abortController&&this.abortController.abort(G.RegistrationAbortedTimeout)}async registerCredential(t){const e=await navigator.credentials.create({publicKey:t,signal:this.abortController&&this.abortController.signal}).catch((t=>{throw vt.toRegistrationError(t)}));return gt.encodeRegistrationResult(e)}}class Ct{async modal(t){try{const e=await this.performApproval(t);return U.jsonToBase64(e)}catch(t){throw vt.toAuthenticationError(t)}}async performApproval(t){"approvalData"in t&&bt(t.approvalData);const e="crossDeviceTicketId"in t?await ht.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await ht.startAuthentication({username:t.username,approvalData:t.approvalData}),i=e.credential_request_options,n=gt.processCredentialRequestOptions(i),r=await navigator.credentials.get({publicKey:n}).catch((t=>{throw vt.toAuthenticationError(t)}));return{webauthnSessionId:e.webauthn_session_id,publicKeyCredential:gt.encodeAuthenticationResult(r),userAgent:navigator.userAgent}}}class _t{constructor(){this._initialized=!1,this._authenticationHandler=new ft,this._registrationHandler=new St,this._approvalHandler=new Ct,this._crossDeviceHandler=new At(this._authenticationHandler,this._registrationHandler,this._approvalHandler),this.authenticate={modal:async(t,e)=>(this.initCheck(),this._authenticationHandler.modal({username:t,options:e})),autofill:{activate:(t,e)=>(this.initCheck(),this._authenticationHandler.activateAutofill(t,e)),abort:()=>this._authenticationHandler.abortAutofill()}},this.approve={modal:async(t,e)=>(this.initCheck(),this._approvalHandler.modal({username:t,approvalData:e}))},this.register=async(t,e)=>(this.initCheck(),this._registrationHandler.register({username:t},e)),this.crossDevice={init:{registration:async t=>(this.initCheck(),this._crossDeviceHandler.init.registration(t)),authentication:async t=>(this.initCheck(),this._crossDeviceHandler.init.authentication(t)),approval:async t=>(this.initCheck(),this._crossDeviceHandler.init.approval(t))},authenticate:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.authenticate.modal(t))},approve:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.approve.modal(t))},register:async(t,e)=>(this.initCheck(),this._crossDeviceHandler.register(t,e)),attachDevice:async t=>(this.initCheck(),this._crossDeviceHandler.attachDevice(t))},this.isPlatformAuthenticatorSupported=async()=>{var t;try{return await(null===(t=_t.StaticPublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable())}catch(t){return!1}},this.isAutofillSupported=async()=>{var t,e;return!(!(null===(t=_t.StaticPublicKeyCredential)||void 0===t?void 0:t.isConditionalMediationAvailable)||!await(null===(e=_t.StaticPublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable()))}}async init(t,e){try{if(!t)throw new Y("Invalid clientId",{clientId:t});if(e.webauthnApiPaths){const t=ht.getDefaultPaths();if(function(t,e){const i=new Set(t),n=new Set(e);return[...t.filter((t=>!n.has(t))),...e.filter((t=>!i.has(t)))]}(Object.keys(e.webauthnApiPaths),Object.keys(t)).length)throw new Y("Invalid custom paths",{customApiPaths:e.webauthnApiPaths})}ht.init(t,e),this._initialized=!0}catch(t){throw ut(t)?t:new Y("Failed to initialize SDK")}}getDefaultPaths(){return this.initCheck(),ht.getDefaultPaths()}getApiPaths(){return this.initCheck(),ht.getApiPaths()}initCheck(){if(!this._initialized)throw new Y}}_t.StaticPublicKeyCredential=window.PublicKeyCredential;const Dt=new L("webauthn"),kt=new _t;Dt.events.on(Dt.events.MODULE_INITIALIZED,(()=>{var t;const e=Dt.moduleMetadata.getInitConfig();if(!(null===(t=null==e?void 0:e.webauthn)||void 0===t?void 0:t.serverPath))return;const{clientId:i,webauthn:n}=e;kt.init(i,l({},n))}));const Tt={modal:async(t,e)=>(kt.initCheck(),kt.authenticate.modal(t,e)),autofill:{activate:(t,e)=>{kt.initCheck(),kt.authenticate.autofill.activate(t,e)},abort:()=>{kt.initCheck(),kt.authenticate.autofill.abort()}}},It={modal:async(t,e)=>(kt.initCheck(),kt.approve.modal(t,e))};async function Pt(t,e){return kt.initCheck(),kt.register(t,e)}const{crossDevice:Ot}=kt,{isPlatformAuthenticatorSupported:jt}=kt,{isAutofillSupported:Rt}=kt,{getDefaultPaths:Kt}=kt;window.localWebAuthnSDK=kt;const xt={initialize:a,...Object.freeze({__proto__:null,get WebauthnCrossDeviceStatus(){return exports.WebauthnCrossDeviceStatus},approve:It,authenticate:Tt,crossDevice:Ot,getDefaultPaths:Kt,isAutofillSupported:Rt,isPlatformAuthenticatorSupported:jt,register:Pt})};exports.PACKAGE_VERSION="1.15.0",exports.approve=It,exports.authenticate=Tt,exports.crossDevice=Ot,exports.getDefaultPaths=Kt,exports.initialize=a,exports.isAutofillSupported=Rt,exports.isPlatformAuthenticatorSupported=jt,exports.register=Pt,exports.webauthn=xt;
|
|
1
|
+
"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));const t=Symbol("MODULE_INITIALIZED"),e=new Map;function i(t,i){var a,s;null===(a=e.get(t))||void 0===a||a.forEach((s=t=>t(i),function(){try{return s(...arguments)}catch(t){console.log(t)}}))}let a=null;function s(t){a=t}var n=Object.freeze({__proto__:null,getInitConfig:function(){return a},get initConfig(){return a},setInitConfig:s});function r(e){s(e),i(t,void 0)}var o=Object.freeze({__proto__:null,initialize:r});function c(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,a)}return i}function l(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?c(Object(i),!0).forEach((function(e){d(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):c(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function u(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var a=i.call(t,e||"default");if("object"!=typeof a)return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function d(t,e,i){return(e=u(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function h(t,e){return Object.entries(e).reduce(((e,i)=>{let[a,s]=i;return l(l({},e),{},{[a]:y.isPrototypeOf(s)?new s(t.slug):"function"==typeof s?s.bind(t):"object"==typeof s&&!Array.isArray(s)&&s?h(t,s):s})}),{})}class y{constructor(t){this.slug=t}static create(t){return class extends y{constructor(e){super(e),Object.assign(this,h(this,t(this)))}}}}var p=Object.freeze({__proto__:null,Agent:y}),g=Object.freeze({__proto__:null,MODULE_INITIALIZED:t,emit:i,off:function(t,i){const a=e.get(t);if(!a)return;const s=a.indexOf(i);-1!==s&&a.splice(s,1)},on:function(t,i){var a;e.has(t)?null===(a=e.get(t))||void 0===a||a.push(i):e.set(t,[i])}});function v(t,e){const i=!t||"object"!=typeof t||Array.isArray(t)?{}:t;return[e.reduce(((t,e)=>{if(e in t){const i=t[e];if(null!==i&&"object"==typeof i&&!Array.isArray(i))return i}const i={};return t[e]=i,i}),i),i]}function f(t,e){let i=t;return e.every((t=>!(!i||"object"!=typeof i||Array.isArray(i)||!(t in i))&&(i=i[t],!0)),t)}const w="tsec",m="general";function b(t){return t?m:a.clientId}function D(t){return function(t){if(!t)return{};try{return JSON.parse(t)}catch(t){return{}}}((t?sessionStorage:localStorage).getItem(w))}function S(t,e){const i=t?sessionStorage:localStorage,a=e(D(t));i.setItem(w,JSON.stringify(a))}var A=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:w,GENERAL_ID_KEY:m,getValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),a=D(!!e.sessionOnly),[s]=v(a,[this.slug.toString(),i]);return s[t]},hasValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),a=D(!!e.sessionOnly);return f(a,[this.slug.toString(),i,t])},removeValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral);S(!!e.sessionOnly,(e=>{const[a,s]=v(e,[this.slug.toString(),i]);return delete a[t],s}))},setValue:function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=b(!!i.isGeneral);S(!!i.sessionOnly,(i=>{const[s,n]=v(i,[this.slug.toString(),a]);return s[t]=e,n}))}});const C="RSA-PSS",_=async(t,e)=>await window.crypto.subtle.generateKey({name:t,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,e),K=async()=>await _("RSA-OAEP",["encrypt","decrypt"]),k=async()=>await _(C,["sign"]),R=async(t,e)=>{const i=(new TextEncoder).encode(e);return await window.crypto.subtle.sign({name:C,saltLength:32},t,i)};class P{constructor(t,e,i){this.slug=t,this.dbName=e,this.dbVersion=i}queryObjectStore(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB).open(`${this.slug}:${this.dbName}`,this.dbVersion||1);a.onupgradeneeded=()=>{var e;const i=a.result;(null===(e=null==i?void 0:i.objectStoreNames)||void 0===e?void 0:e.contains)&&!i.objectStoreNames.contains(t)&&i.createObjectStore(t,{keyPath:"key"})},a.onsuccess=()=>{const s=a.result,n=s.transaction(t,(null==i?void 0:i.operation)||"readwrite"),r=n.objectStore(t);e(r),n.oncomplete=()=>{s.close()}}}put(t,e,i){return new Promise(((a,s)=>{this.queryObjectStore(t,(t=>{const n=t.put({key:e,value:i});n.onsuccess=()=>{a(n.result)},n.onerror=t=>{s("Failed adding item to objectStore, err: "+t)}}))}))}add(t,e,i){return new Promise(((a,s)=>{this.queryObjectStore(t,(t=>{const n=t.add({key:e,value:i});n.onsuccess=()=>{a(n.result)},n.onerror=t=>{const e=t.target.error;s(e)}}))}))}get(t,e){return new Promise(((i,a)=>{this.queryObjectStore(t,(t=>{const s=t.get(e);s.onsuccess=()=>{var t;s.result?i(null===(t=s.result)||void 0===t?void 0:t.value):i(void 0)},s.onerror=t=>{a("Failed adding item to objectStore, err: "+t)}}))}))}getAll(t,e){return new Promise(((i,a)=>{this.queryObjectStore(t,(t=>{const s=t.getAll(null,e);s.onsuccess=()=>{if(s.result){const t=s.result;(null==t?void 0:t.length)?i(t.map((t=>null==t?void 0:t.value))):i(t)}else i([])},s.onerror=t=>{a("Failed getting items, err: "+t)}}))}))}delete(t,e){return new Promise(((i,a)=>{this.queryObjectStore(t,(t=>{const s=t.delete(e);s.onsuccess=()=>{i()},s.onerror=t=>{a(`Failed deleting key: '${e}' from objectStore, err: `+t)}}))}))}clear(t){return new Promise(((e,i)=>{this.queryObjectStore(t,(t=>{const a=t.clear();a.onsuccess=()=>{e()},a.onerror=t=>{i("Failed clearing objectStore, err: "+t)}}))}))}}const T="platform",I="init",O="completed",x="RSA2048",j=[I,O];class B{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",i=arguments.length>2?arguments[2]:void 0;var s,n,r,o;this.agent=t,this.keysType=e,this.options=i,this._extractingKeysPromise=null;const c=!(null===(s=this.options)||void 0===s?void 0:s.productScope);this.keysDatabaseName=c||!(null===(n=this.options)||void 0===n?void 0:n.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(r=this.options)||void 0===r?void 0:r.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName,this.indexedDBClient=new P(c?T:t.slug,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new P((c?T:t.slug)+`:${a.clientId}`,this.keysDatabaseName,this.dbVersion)}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(t){return window.btoa(String.fromCharCode(...new Uint8Array(t)))}async getPKRepresentations(t){const e=await crypto.subtle.exportKey("spki",t);return{arrayBufferKey:e,base64Key:this.arrayBufferToBase64(e)}}async generateKeyPair(){return"sign"==this.keysType?await k():await K()}async calcKeyIdentifier(t){const e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map((t=>t.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var t,e;const i=(null===(e=null===(t=this.options)||void 0===t?void 0:t.keyRotation)||void 0===e?void 0:e.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{base64Key:a}=await this.getPKRepresentations(i.publicKey);return this.publicKeyBase64=a,this.keyIdentifier=i.keyIdentifier,i})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(t){const e=await this.generateKeyPair(),{arrayBufferKey:i}=await this.getPKRepresentations(e.publicKey),a=t||await this.calcKeyIdentifier(i);return l(l({},e),{},{keyIdentifier:a,createdDate:Date.now()})}shouldKeyBeRotated(t){var e;const i=null===(e=this.options)||void 0===e?void 0:e.keyRotation;if(!(null==i?void 0:i.isEnabled)||!i.expiryDays||void 0===i.startedAt)return!1;const a=24*i.expiryDays*60*60*1e3,s=t.createdDate&&t.createdDate>=i.startedAt?t.createdDate:i.startedAt;return Date.now()-s>a-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(t,e){try{return await this.indexedDBClient.add(this.keysStoreName,t,e),e}catch(e){if(e instanceof DOMException&&"ConstraintError"===e.name){const e=await this.indexedDBClient.get(this.keysStoreName,t);if(e)return e}throw e}}async getKeysData(){const t=this.getKeysRecordKey();let e=await this.extractMainKeysData();if(e)return e;if(e=await this.extractFallbackMainKeysData(),e)return this.saveKeyData(t,e);const i=await this.generateKeyPairData();return this.saveKeyData(t,i)}async getOrCreateRotatedKeys(){let t=await this.extractRotatedKeysData();if(!t){const e=this.getRotatedKeysRecordKey(),i=await this.getKeysData(),a=l(l({},i),{},{createdDate:i.createdDate||Date.now()});t=await this.saveKeyData(e,a)}return t}async getRotatedKeysData(){const t=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(t)){if(!await this.extractPendingRotatedKeysData()){const e=this.getRotatedKeysRecordKeyPending(),i=await this.generateKeyPairData(t.keyIdentifier);await this.saveKeyData(e,i)}}return t}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier}}async sign(t){if("sign"==this.keysType){const{privateKey:e}=await this.extractKeysData(),i=await R(e,t);return this.arrayBufferToBase64(i)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const t=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,t)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:x,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var t,e;if(!(null===(e=null===(t=this.options)||void 0===t?void 0:t.keyRotation)||void 0===e?void 0:e.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier||await this.extractKeysData();const i=await this.extractPendingRotatedKeysData();if(i){const{base64Key:t}=await this.getPKRepresentations(i.publicKey),{privateKey:e}=await this.extractKeysData(),a=l(l({},this.getBaseRotationPayload()),{},{newPublicKey:t,createdDate:i.createdDate,newPublicKeyType:x}),s=JSON.stringify(a);return{data:s,signature:await this.signPayload(s,e)}}const a=await this.extractRotatedKeysData();if(a&&!1===a.confirmed){await this.extractKeysData();const t=JSON.stringify(this.getBaseRotationPayload());return{data:t,signature:await this.signPayload(t,a.privateKey)}}}async signPayload(t,e){const i=await R(e,t);return this.arrayBufferToBase64(i)}async handleRotateResponse(t){if(j.includes(t))if(t===I){const t=await this.extractPendingRotatedKeysData();if(t){await this.indexedDBClient.delete(this.keysStoreName,this.getRotatedKeysRecordKey());const e=l(l({},t),{},{confirmed:!1});await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),e),await this.indexedDBClient.delete(this.keysStoreName,this.getRotatedKeysRecordKeyPending());const{base64Key:i}=await this.getPKRepresentations(t.publicKey);this.publicKeyBase64=i,this.keyIdentifier=t.keyIdentifier}}else if(t===O){const t=await this.extractRotatedKeysData();t&&!1===t.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),l(l({},t),{},{confirmed:!0}))}}}var N=Object.freeze({__proto__:null,createCryptoBinding:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",e=arguments.length>1?arguments[1]:void 0;return new B(this,t,e)},generateRSAKeyPair:K,generateRSASignKeyPair:k,signAssymetric:R,verifyAssymetric:async(t,e,i)=>{const a=(new TextEncoder).encode(e);return await window.crypto.subtle.verify(C,t,i,a)}}),E=Object.freeze({__proto__:null});const H=y.create((t=>{class e extends Error{constructor(e,i){super(`${t.slug}-${e} ${i}`)}}return{TsError:e,TsInternalError:class extends e{constructor(t){super(t,"Internal error")}}}}));var F=y.create((()=>l({exceptions:H},p)));class M{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=t,this.middlewares=e,this.logs=[]}info(t,e){this.pushLog(3,t,e)}warn(t,e){this.pushLog(4,t,e)}error(t,e){this.pushLog(5,t,e)}pushLog(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:t,fields:i,message:e});const a=this.middlewares.map((t=>t(this)));Promise.all(a).catch((()=>{}))}}var q=Object.freeze({__proto__:null,consoleMiddleware:function(t){const e=t.logs[t.logs.length-1];console.log(`${e.severity} ${e.message}`,e.fields)},createSdkLogger:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return new M(this,t)}});function z(t,e){if(!(null==t?void 0:t.trim()))return"";if(function(t){try{return new URL(t),!0}catch(t){return!1}}(t))return t;const i="http://mock.com",a=new URL(i);a.search=(null==e?void 0:e.toString())||"",a.pathname=t;return a.href.replace(i,"")}const $={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function J(t,e,i){var a;const s=(n=e||{},encodeURI(JSON.stringify(n)).split(/%..|./).length-1);var n;return{method:t,headers:l(l(l({},{"X-TS-body-size":String(s)}),$),i||{}),body:null!==(a=e&&JSON.stringify(e||{}))&&void 0!==a?a:void 0}}function W(t,e,i,a,s){const n=z(t,a),r=J(e,i,s);return fetch(n,r)}async function L(t,e,i,a,s){let n;if(n=await W(t,e,i,a,s),!n.ok)throw new Error("Request failed");return n}var U=Object.freeze({__proto__:null,httpDelete:async function(t,e){const i=await L(t,"DELETE",void 0,void 0,e);return l(l({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(t,e,i){const a=await L(t,"GET",void 0,e,i);return l(l({data:await a.json()},a),{},{headers:a.headers})},httpPost:async function(t,e,i,a){const s=await L(t,"POST",e,i,a);return l(l({data:await s.json()},s),{},{headers:s.headers})},httpPut:async function(t,e,i,a){const s=await L(t,"PUT",e,i,a);return l(l({data:await s.json()},s),{},{headers:s.headers})},init:J}),V=y.create((()=>({events:g,moduleMetadata:n,mainEntry:o,utils:F,storage:A,crypto:N,indexedDB:E,logger:q,http:U})));class G{static arrayBufferToBase64(t){return btoa(String.fromCharCode(...new Uint8Array(t)))}static base64ToArrayBuffer(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}static stringToBase64(t){return btoa(t)}static jsonToBase64(t){const e=JSON.stringify(t);return btoa(e)}static base64ToJson(t){const e=atob(t);return JSON.parse(e)}}const Z={log:console.log,error:console.error};var X,Y;!function(t){t.NotInitialized="not_initialized",t.AuthenticationFailed="authentication_failed",t.AuthenticationAbortedTimeout="authentication_aborted_timeout",t.AuthenticationCanceled="webauthn_authentication_canceled",t.RegistrationFailed="registration_failed",t.AlreadyRegistered="username_already_registered",t.RegistrationAbortedTimeout="registration_aborted_timeout",t.RegistrationCanceled="webauthn_registration_canceled",t.AutofillAuthenticationAborted="autofill_authentication_aborted",t.AuthenticationProcessAlreadyActive="authentication_process_already_active",t.InvalidApprovalData="invalid_approval_data",t.FailedToInitCrossDeviceSession="cross_device_init_failed",t.FailedToGetCrossDeviceStatus="cross_device_status_failed",t.Unknown="unknown"}(X||(X={}));class Q extends Error{constructor(t,e){super(t),this.errorCode=X.NotInitialized,this.data=e}}class tt extends Q{constructor(t,e){super(null!=t?t:"WebAuthnSdk is not initialized",e),this.errorCode=X.NotInitialized}}class et extends Q{constructor(t,e){super(null!=t?t:"Authentication failed with an error",e),this.errorCode=X.AuthenticationFailed}}class it extends Q{constructor(t,e){super(null!=t?t:"Authentication was canceled by the user or got timeout",e),this.errorCode=X.AuthenticationCanceled}}class at extends Q{constructor(t,e){super(null!=t?t:"Registration failed with an error",e),this.errorCode=X.RegistrationFailed}}class st extends Q{constructor(t,e){super(null!=t?t:"Registration was canceled by the user or got timeout",e),this.errorCode=X.RegistrationCanceled}}class nt extends Q{constructor(t){super(null!=t?t:"Autofill flow was aborted"),this.errorCode=X.AutofillAuthenticationAborted}}class rt extends Q{constructor(t){super(null!=t?t:"Operation was aborted by timeout"),this.errorCode=X.AutofillAuthenticationAborted}}class ot extends Q{constructor(t){super(null!=t?t:"Passkey with this username is already registered with the relying party."),this.errorCode=X.AlreadyRegistered}}class ct extends Q{constructor(t,e){super(null!=t?t:"Authentication process is already active",e),this.errorCode=X.AuthenticationProcessAlreadyActive}}class lt extends Q{constructor(t,e){super(null!=t?t:"Invalid approval data",e),this.errorCode=X.InvalidApprovalData}}class ut extends Q{constructor(t,e){super(null!=t?t:"Failed to init cross device authentication",e),this.errorCode=X.FailedToInitCrossDeviceSession}}class dt extends Q{constructor(t,e){super(null!=t?t:"Failed to get cross device status",e),this.errorCode=X.FailedToGetCrossDeviceStatus}}function ht(t){return t.errorCode&&Object.values(X).includes(t.errorCode)}!function(t){t[t.persistent=0]="persistent",t[t.session=1]="session"}(Y||(Y={}));class yt{static get(t){return yt.getStorageMedium(yt.allowedKeys[t]).getItem(yt.getStorageKey(t))||void 0}static set(t,e){return yt.getStorageMedium(yt.allowedKeys[t]).setItem(yt.getStorageKey(t),e)}static remove(t){yt.getStorageMedium(yt.allowedKeys[t]).removeItem(yt.getStorageKey(t))}static clear(t){for(const[e,i]of Object.entries(yt.allowedKeys)){const a=e;t&&this.configurationKeys.includes(a)||yt.getStorageMedium(i).removeItem(yt.getStorageKey(a))}}static getStorageKey(t){return`WebAuthnSdk:${t}`}static getStorageMedium(t){return t===Y.session?sessionStorage:localStorage}}yt.allowedKeys={clientId:Y.session},yt.configurationKeys=["clientId"];class pt{static isNewApiDomain(t){return t&&(this.newApiDomains.includes(t)||t.startsWith("api.")&&t.endsWith(".transmitsecurity.io"))}static dnsPrefetch(t){const e=document.createElement("link");e.rel="dns-prefetch",e.href=t,document.head.appendChild(e)}static preconnect(t,e){const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}static warmupConnection(t){this.dnsPrefetch(t),this.preconnect(t,!1),this.preconnect(t,!0)}static init(t,e){var i,a;try{this._serverPath=new URL(e.serverPath),this.isNewApiDomain(null===(i=this._serverPath)||void 0===i?void 0:i.hostname)&&this.warmupConnection(this._serverPath.origin),this._apiPaths=null!==(a=e.webauthnApiPaths)&&void 0!==a?a:this.getDefaultPaths(),this._clientId=t,yt.set("clientId",t)}catch(t){throw new tt("Invalid options.serverPath",{error:t})}}static getDefaultPaths(){var t;const e=this.isNewApiDomain(null===(t=this._serverPath)||void 0===t?void 0:t.hostname)?"/cis":"";return{startAuthentication:`${e}/v1/auth/webauthn/authenticate/start`,startRegistration:`${e}/v1/auth/webauthn/register/start`,initCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/init`,startCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/start`,startCrossDeviceRegistration:`${e}/v1/auth/webauthn/cross-device/register/start`,getCrossDeviceTicketStatus:`${e}/v1/auth/webauthn/cross-device/status`,attachDeviceToCrossDeviceSession:`${e}/v1/auth/webauthn/cross-device/attach-device`}}static getApiPaths(){return this._apiPaths}static async sendRequest(t,e,i){Z.log(`[WebAuthn SDK] Calling ${e.method} ${t}...`);const a=new URL(this._serverPath);return a.pathname=t,i&&(a.search=i),fetch(a.toString(),e)}static async startRegistration(t){const e=await this.sendRequest(this._apiPaths.startRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId(),username:t.username,display_name:t.displayName},t.timeout&&{timeout:t.timeout}),t.limitSingleCredentialToDevice&&{limit_single_credential_to_device:t.limitSingleCredentialToDevice}))});if(!(null==e?void 0:e.ok))throw new et("Failed to start registration",null==e?void 0:e.body);return await e.json()}static async startAuthentication(t){const e=await this.sendRequest(this._apiPaths.startAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}),t.timeout&&{timeout:t.timeout}))});if(!(null==e?void 0:e.ok))throw new et("Failed to start authentication",null==e?void 0:e.body);return await e.json()}static async initCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.initCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}))});if(!(null==e?void 0:e.ok))throw new ut(void 0,null==e?void 0:e.body);return await e.json()}static async getCrossDeviceTicketStatus(t){const e=await this.sendRequest(this._apiPaths.getCrossDeviceTicketStatus,{method:"GET"},`cross_device_ticket_id=${t.ticketId}`);if(!(null==e?void 0:e.ok))throw new dt(void 0,null==e?void 0:e.body);return await e.json()}static async startCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new et("Failed to start cross device authentication",null==e?void 0:e.body);return await e.json()}static async startCrossDeviceRegistration(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new at("Failed to start cross device registration",null==e?void 0:e.body);return await e.json()}static async attachDeviceToCrossDeviceSession(t){const e=await this.sendRequest(this._apiPaths.attachDeviceToCrossDeviceSession,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new at("Failed to attach device to cross device session",null==e?void 0:e.body);return await e.json()}static getValidatedClientId(){var t;const e=null!==(t=this._clientId)&&void 0!==t?t:yt.get("clientId");if(!e)throw new tt("Missing clientId");return e}}var gt,vt,ft,wt;pt.newApiDomains=["api.idsec-dev.com","api.idsec-stg.com"],function(t){t.InputAutofill="input-autofill",t.Modal="modal"}(gt||(gt={})),exports.WebauthnCrossDeviceStatus=void 0,(vt=exports.WebauthnCrossDeviceStatus||(exports.WebauthnCrossDeviceStatus={})).Pending="pending",vt.Scanned="scanned",vt.Success="success",vt.Error="error",vt.Timeout="timeout",vt.Aborted="aborted",function(t){t.toAuthenticationError=t=>ht(t)?t:"NotAllowedError"===t.name?new it:"OperationError"===t.name?new ct(t.message):"SecurityError"===t.name?new et(t.message):t===X.AuthenticationAbortedTimeout?new rt:"AbortError"===t.name||t===X.AutofillAuthenticationAborted?new nt:new et("Something went wrong during authentication",{error:t}),t.toRegistrationError=t=>ht(t)?t:"NotAllowedError"===t.name?new st:"SecurityError"===t.name?new at(t.message):"InvalidStateError"===t.name?new ot:t===X.RegistrationAbortedTimeout?new rt:new at("Something went wrong during registration",{error:t})}(ft||(ft={})),function(t){t.processCredentialRequestOptions=t=>l(l({},t),{},{challenge:G.base64ToArrayBuffer(t.challenge),allowCredentials:t.allowCredentials.map((t=>l(l({},t),{},{id:G.base64ToArrayBuffer(t.id)})))}),t.processCredentialCreationOptions=(t,e)=>{var i;const a=JSON.parse(JSON.stringify(t));return a.challenge=G.base64ToArrayBuffer(t.challenge),a.user.id=G.base64ToArrayBuffer(t.user.id),(null==e?void 0:e.limitSingleCredentialToDevice)&&(a.excludeCredentials=null===(i=t.excludeCredentials)||void 0===i?void 0:i.map((t=>l(l({},t),{},{id:G.base64ToArrayBuffer(t.id)})))),(null==e?void 0:e.registerAsDiscoverable)?(a.authenticatorSelection.residentKey="preferred",a.authenticatorSelection.requireResidentKey=!0):(a.authenticatorSelection.residentKey="discouraged",a.authenticatorSelection.requireResidentKey=!1),a.authenticatorSelection.authenticatorAttachment=(null==e?void 0:e.allowCrossPlatformAuthenticators)?void 0:"platform",a},t.encodeAuthenticationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:G.arrayBufferToBase64(t.rawId),response:{authenticatorData:G.arrayBufferToBase64(i.authenticatorData),clientDataJSON:G.arrayBufferToBase64(i.clientDataJSON),signature:G.arrayBufferToBase64(i.signature),userHandle:G.arrayBufferToBase64(i.userHandle)},authenticatorAttachment:e,type:t.type}},t.encodeRegistrationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:G.arrayBufferToBase64(t.rawId),response:{attestationObject:G.arrayBufferToBase64(i.attestationObject),clientDataJSON:G.arrayBufferToBase64(i.clientDataJSON)},authenticatorAttachment:e,type:t.type}}}(wt||(wt={}));class mt{async modal(t){try{const e=await this.performAuthentication(l(l({},t),{},{mediationType:gt.Modal}));return G.jsonToBase64(e)}catch(t){throw ft.toAuthenticationError(t)}}activateAutofill(t,e){const{onSuccess:i,onError:a,onReady:s}=t;this.performAuthentication({username:e,mediationType:gt.InputAutofill,onReady:s}).then((t=>{i(G.jsonToBase64(t))})).catch((t=>{const e=ft.toAuthenticationError(t);if(!a)throw e;a(e)}))}abortAutofill(){this.abortController&&this.abortController.abort(X.AutofillAuthenticationAborted)}abortAuthentication(){this.abortController&&this.abortController.abort(X.AuthenticationAbortedTimeout)}async performAuthentication(t){var e,i;const a="crossDeviceTicketId"in t?await pt.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await pt.startAuthentication({username:t.username,timeout:null===(e=t.options)||void 0===e?void 0:e.timeout}),s=a.credential_request_options,n=wt.processCredentialRequestOptions(s),r=this.getMediatedCredentialRequest(n,t.mediationType);t.mediationType===gt.InputAutofill&&(null===(i=t.onReady)||void 0===i||i.call(t));const o=await navigator.credentials.get(r).catch((t=>{throw ft.toAuthenticationError(t)}));return{webauthnSessionId:a.webauthn_session_id,publicKeyCredential:wt.encodeAuthenticationResult(o),userAgent:navigator.userAgent}}getMediatedCredentialRequest(t,e){const i={publicKey:t};return this.abortController=new AbortController,i.signal=this.abortController&&this.abortController.signal,e===gt.InputAutofill?i.mediation="conditional":t.timeout&&setTimeout((()=>{this.abortAuthentication()}),t.timeout),i}}class bt{constructor(t,e){this.handler=t,this.intervalInMs=e}begin(){var t;this.intervalId=window.setInterval((t=this.handler,async function(){t.isRunning||(t.isRunning=!0,await t(...arguments),t.isRunning=!1)}),this.intervalInMs)}stop(){clearInterval(this.intervalId)}}const Dt=/^[A-Za-z0-9\-_.: ]*$/;function St(t){if(t&&(!function(t){return Object.keys(t).length<=10}(t)||!function(t){const e=t=>"string"==typeof t,i=t=>Dt.test(t);return Object.keys(t).every((a=>e(a)&&e(t[a])&&i(a)&&i(t[a])))}(t)))throw Z.error("Failed validating approval data"),new lt("Provided approval data should have 10 properties max. Also, it should contain only \n alphanumeric characters, numbers, and the special characters: '-', '_', '.'")}class At{constructor(t,e,i){this.authenticationHandler=t,this.registrationHandler=e,this.approvalHandler=i,this.init={registration:async t=>(this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(t.crossDeviceTicketId,t.handlers)),authentication:async t=>{const{username:e}=t,i=(await pt.initCrossDeviceAuthentication(l({},e&&{username:e}))).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(i,t.handlers)},approval:async t=>{const{username:e,approvalData:i}=t;St(i);const a=(await pt.initCrossDeviceAuthentication({username:e,approvalData:i})).cross_device_ticket_id;return this.ticketStatus=exports.WebauthnCrossDeviceStatus.Pending,this.pollCrossDeviceSession(a,t.handlers)}},this.authenticate={modal:async t=>this.authenticationHandler.modal({crossDeviceTicketId:t})},this.approve={modal:async t=>this.approvalHandler.modal({crossDeviceTicketId:t})}}async register(t,e){return this.registrationHandler.register({crossDeviceTicketId:t},e)}async attachDevice(t){const e=await pt.attachDeviceToCrossDeviceSession({ticketId:t});return l({status:e.status,startedAt:e.started_at},e.approval_data&&{approvalData:e.approval_data})}async pollCrossDeviceSession(t,e){return this.poller=new bt((async()=>{var i,a;const s=await pt.getCrossDeviceTicketStatus({ticketId:t}),n=s.status;if(n!==this.ticketStatus)switch(this.ticketStatus=n,n){case exports.WebauthnCrossDeviceStatus.Scanned:await e.onDeviceAttach();break;case exports.WebauthnCrossDeviceStatus.Error:case exports.WebauthnCrossDeviceStatus.Timeout:case exports.WebauthnCrossDeviceStatus.Aborted:await e.onFailure(s),null===(i=this.poller)||void 0===i||i.stop();break;case exports.WebauthnCrossDeviceStatus.Success:if("onCredentialRegister"in e)await e.onCredentialRegister();else{if(!s.session_id)throw new dt("Cross device session is complete without returning session_id",s);await e.onCredentialAuthenticate(s.session_id)}null===(a=this.poller)||void 0===a||a.stop()}}),1e3),this.poller.begin(),setTimeout((()=>{var t;null===(t=this.poller)||void 0===t||t.stop(),e.onFailure({status:exports.WebauthnCrossDeviceStatus.Timeout})}),3e5),{crossDeviceTicketId:t,stop:()=>{var t;null===(t=this.poller)||void 0===t||t.stop()}}}}class Ct{async register(t,e){this.abortController=new AbortController;const i=l({allowCrossPlatformAuthenticators:!("crossDeviceTicketId"in t),registerAsDiscoverable:!0},e);try{const a="crossDeviceTicketId"in t?await pt.startCrossDeviceRegistration({ticketId:t.crossDeviceTicketId}):await pt.startRegistration({username:t.username,displayName:(null==e?void 0:e.displayName)||t.username,timeout:null==e?void 0:e.timeout,limitSingleCredentialToDevice:null==e?void 0:e.limitSingleCredentialToDevice}),s=wt.processCredentialCreationOptions(a.credential_creation_options,i);setTimeout((()=>{this.abortRegistration()}),s.timeout);const n=await this.registerCredential(s),r={webauthnSessionId:a.webauthn_session_id,publicKeyCredential:n,userAgent:navigator.userAgent};return G.jsonToBase64(r)}catch(t){throw ft.toRegistrationError(t)}}abortRegistration(){this.abortController&&this.abortController.abort(X.RegistrationAbortedTimeout)}async registerCredential(t){const e=await navigator.credentials.create({publicKey:t,signal:this.abortController&&this.abortController.signal}).catch((t=>{throw ft.toRegistrationError(t)}));return wt.encodeRegistrationResult(e)}}class _t{async modal(t){try{const e=await this.performApproval(t);return G.jsonToBase64(e)}catch(t){throw ft.toAuthenticationError(t)}}async performApproval(t){"approvalData"in t&&St(t.approvalData);const e="crossDeviceTicketId"in t?await pt.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await pt.startAuthentication({username:t.username,approvalData:t.approvalData}),i=e.credential_request_options,a=wt.processCredentialRequestOptions(i),s=await navigator.credentials.get({publicKey:a}).catch((t=>{throw ft.toAuthenticationError(t)}));return{webauthnSessionId:e.webauthn_session_id,publicKeyCredential:wt.encodeAuthenticationResult(s),userAgent:navigator.userAgent}}}class Kt{constructor(){this._initialized=!1,this._authenticationHandler=new mt,this._registrationHandler=new Ct,this._approvalHandler=new _t,this._crossDeviceHandler=new At(this._authenticationHandler,this._registrationHandler,this._approvalHandler),this.authenticate={modal:async(t,e)=>(this.initCheck(),this._authenticationHandler.modal({username:t,options:e})),autofill:{activate:(t,e)=>(this.initCheck(),this._authenticationHandler.activateAutofill(t,e)),abort:()=>this._authenticationHandler.abortAutofill()}},this.approve={modal:async(t,e)=>(this.initCheck(),this._approvalHandler.modal({username:t,approvalData:e}))},this.register=async(t,e)=>(this.initCheck(),this._registrationHandler.register({username:t},e)),this.crossDevice={init:{registration:async t=>(this.initCheck(),this._crossDeviceHandler.init.registration(t)),authentication:async t=>(this.initCheck(),this._crossDeviceHandler.init.authentication(t)),approval:async t=>(this.initCheck(),this._crossDeviceHandler.init.approval(t))},authenticate:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.authenticate.modal(t))},approve:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.approve.modal(t))},register:async(t,e)=>(this.initCheck(),this._crossDeviceHandler.register(t,e)),attachDevice:async t=>(this.initCheck(),this._crossDeviceHandler.attachDevice(t))},this.isPlatformAuthenticatorSupported=async()=>{var t;try{return await(null===(t=Kt.StaticPublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable())}catch(t){return!1}},this.isAutofillSupported=async()=>{var t,e;return!(!(null===(t=Kt.StaticPublicKeyCredential)||void 0===t?void 0:t.isConditionalMediationAvailable)||!await(null===(e=Kt.StaticPublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable()))}}async init(t,e){try{if(!t)throw new tt("Invalid clientId",{clientId:t});if(e.webauthnApiPaths){const t=pt.getDefaultPaths();if(function(t,e){const i=new Set(t),a=new Set(e);return[...t.filter((t=>!a.has(t))),...e.filter((t=>!i.has(t)))]}(Object.keys(e.webauthnApiPaths),Object.keys(t)).length)throw new tt("Invalid custom paths",{customApiPaths:e.webauthnApiPaths})}pt.init(t,e),this._initialized=!0}catch(t){throw ht(t)?t:new tt("Failed to initialize SDK")}}getDefaultPaths(){return this.initCheck(),pt.getDefaultPaths()}getApiPaths(){return this.initCheck(),pt.getApiPaths()}initCheck(){if(!this._initialized)throw new tt}}Kt.StaticPublicKeyCredential=window.PublicKeyCredential;const kt=new V("webauthn"),Rt=new Kt;kt.events.on(kt.events.MODULE_INITIALIZED,(()=>{var t;const e=kt.moduleMetadata.getInitConfig();if(!(null===(t=null==e?void 0:e.webauthn)||void 0===t?void 0:t.serverPath))return;const{clientId:i,webauthn:a}=e;Rt.init(i,l({},a))}));const Pt={modal:async(t,e)=>(Rt.initCheck(),Rt.authenticate.modal(t,e)),autofill:{activate:(t,e)=>{Rt.initCheck(),Rt.authenticate.autofill.activate(t,e)},abort:()=>{Rt.initCheck(),Rt.authenticate.autofill.abort()}}},Tt={modal:async(t,e)=>(Rt.initCheck(),Rt.approve.modal(t,e))};async function It(t,e){return Rt.initCheck(),Rt.register(t,e)}const{crossDevice:Ot}=Rt,{isPlatformAuthenticatorSupported:xt}=Rt,{isAutofillSupported:jt}=Rt,{getDefaultPaths:Bt}=Rt;window.localWebAuthnSDK=Rt;const Nt={initialize:r,...Object.freeze({__proto__:null,get WebauthnCrossDeviceStatus(){return exports.WebauthnCrossDeviceStatus},approve:Tt,authenticate:Pt,crossDevice:Ot,getDefaultPaths:Bt,isAutofillSupported:jt,isPlatformAuthenticatorSupported:xt,register:It})};exports.PACKAGE_VERSION="1.16.0",exports.approve=Tt,exports.authenticate=Pt,exports.crossDevice=Ot,exports.getDefaultPaths=Bt,exports.initialize=r,exports.isAutofillSupported=jt,exports.isPlatformAuthenticatorSupported=xt,exports.register=It,exports.webauthn=Nt;
|
package/dist/webauthn.d.ts
CHANGED
|
@@ -453,9 +453,11 @@ declare const PACKAGE_VERSION: string;
|
|
|
453
453
|
declare namespace webauthn {
|
|
454
454
|
export function initialize(config: any): void;
|
|
455
455
|
export * from "@transmit-security/authentication-sdk";
|
|
456
|
+
export const authenticate: (...args: any[]) => any;
|
|
457
|
+
export const register: (...args: any[]) => any;
|
|
458
|
+
export const crossDevice: (...args: any[]) => any;
|
|
456
459
|
}
|
|
457
460
|
|
|
458
461
|
declare function initialize(config: any): void;
|
|
459
462
|
|
|
460
|
-
export { ErrorCode, PACKAGE_VERSION, WebauthnCrossDeviceStatus, approve, authenticate, crossDevice, getDefaultPaths, initialize, isAutofillSupported, isPlatformAuthenticatorSupported, register, webauthn };
|
|
461
|
-
export type { ApiCrossDeviceStatusResponse, AttachDeviceResult, AuthenticationAutofillActivateHandlers, AutofillHandlers, CrossDeviceAuthenticationHandlers, CrossDeviceController, CrossDeviceRegistrationHandlers, SdkError, WebauthnApis, WebauthnApprovalFlows, WebauthnAuthenticationFlows, WebauthnAuthenticationOptions, WebauthnCrossDeviceFlows, WebauthnCrossDeviceRegistrationOptions, WebauthnRegistrationOptions };
|
|
463
|
+
export { ApiCrossDeviceStatusResponse, AttachDeviceResult, AuthenticationAutofillActivateHandlers, AutofillHandlers, CrossDeviceAuthenticationHandlers, CrossDeviceController, CrossDeviceRegistrationHandlers, ErrorCode, PACKAGE_VERSION, SdkError, WebauthnApis, WebauthnApprovalFlows, WebauthnAuthenticationFlows, WebauthnAuthenticationOptions, WebauthnCrossDeviceFlows, WebauthnCrossDeviceRegistrationOptions, WebauthnCrossDeviceStatus, WebauthnRegistrationOptions, approve, authenticate, crossDevice, getDefaultPaths, initialize, isAutofillSupported, isPlatformAuthenticatorSupported, register, webauthn };
|
package/dist/webauthn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));const t=Symbol("MODULE_INITIALIZED"),e=new Map;function i(t,i){var n,r;null===(n=e.get(t))||void 0===n||n.forEach((r=t=>t(i),function(){try{return r(...arguments)}catch(t){console.log(t)}}))}let n=null;function r(t){n=t}var a=Object.freeze({__proto__:null,getInitConfig:function(){return n},get initConfig(){return n},setInitConfig:r});function s(e){r(e),i(t,void 0)}var o=Object.freeze({__proto__:null,initialize:s});function c(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,n)}return i}function l(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?c(Object(i),!0).forEach((function(e){d(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):c(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function u(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function d(t,e,i){return(e=u(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function h(t,e){return Object.entries(e).reduce(((e,i)=>{let[n,r]=i;return l(l({},e),{},{[n]:p.isPrototypeOf(r)?new r(t.slug):"function"==typeof r?r.bind(t):"object"==typeof r&&!Array.isArray(r)&&r?h(t,r):r})}),{})}class p{constructor(t){this.slug=t}static create(t){return class extends p{constructor(e){super(e),Object.assign(this,h(this,t(this)))}}}}var y=Object.freeze({__proto__:null,Agent:p}),v=Object.freeze({__proto__:null,MODULE_INITIALIZED:t,emit:i,off:function(t,i){const n=e.get(t);if(!n)return;const r=n.indexOf(i);-1!==r&&n.splice(r,1)},on:function(t,i){var n;e.has(t)?null===(n=e.get(t))||void 0===n||n.push(i):e.set(t,[i])}});function g(t,e){const i=!t||"object"!=typeof t||Array.isArray(t)?{}:t;return[e.reduce(((t,e)=>{if(e in t){const i=t[e];if(null!==i&&"object"==typeof i&&!Array.isArray(i))return i}const i={};return t[e]=i,i}),i),i]}function f(t,e){let i=t;return e.every((t=>!(!i||"object"!=typeof i||Array.isArray(i)||!(t in i))&&(i=i[t],!0)),t)}const w="tsec",m="general";function b(t){return t?m:n.clientId}function A(t){return function(t){if(!t)return{};try{return JSON.parse(t)}catch(t){return{}}}((t?sessionStorage:localStorage).getItem(w))}function _(t,e){const i=t?sessionStorage:localStorage,n=e(A(t));i.setItem(w,JSON.stringify(n))}var S=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:w,GENERAL_ID_KEY:m,getValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),n=A(!!e.sessionOnly),[r]=g(n,[this.slug.toString(),i]);return r[t]},hasValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),n=A(!!e.sessionOnly);return f(n,[this.slug.toString(),i,t])},removeValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral);_(!!e.sessionOnly,(e=>{const[n,r]=g(e,[this.slug.toString(),i]);return delete n[t],r}))},setValue:function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=b(!!i.isGeneral);_(!!i.sessionOnly,(i=>{const[r,a]=g(i,[this.slug.toString(),n]);return r[t]=e,a}))}});const C="RSA-OAEP",D="RSA-PSS",k=async(t,e)=>await window.crypto.subtle.generateKey({name:t,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,e),T=async()=>await k(C,["encrypt","decrypt"]),I=async()=>await k(D,["sign"]),P=async(t,e)=>await window.crypto.subtle.encrypt({name:C},e,t),O=async(t,e)=>{const i=(new TextEncoder).encode(e);return await window.crypto.subtle.sign({name:D,saltLength:32},t,i)};class j{constructor(t,e,i){this.slug=t,this.dbName=e,this.dbVersion=i}queryObjectStore(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB).open(`${this.slug}:${this.dbName}`,this.dbVersion||1);n.onupgradeneeded=()=>{var e;const i=n.result;(null===(e=null==i?void 0:i.objectStoreNames)||void 0===e?void 0:e.contains)&&!i.objectStoreNames.contains(t)&&i.createObjectStore(t,{keyPath:"key"})},n.onsuccess=()=>{const r=n.result,a=r.transaction(t,(null==i?void 0:i.operation)||"readwrite"),s=a.objectStore(t);e(s),a.oncomplete=()=>{r.close()}}}put(t,e,i){return new Promise(((n,r)=>{this.queryObjectStore(t,(t=>{const a=t.put({key:e,value:i});a.onsuccess=()=>{n(a.result)},a.onerror=t=>{r("Failed adding item to objectStore, err: "+t)}}))}))}get(t,e){return new Promise(((i,n)=>{this.queryObjectStore(t,(t=>{const r=t.get(e);r.onsuccess=()=>{var t;r.result?i(null===(t=r.result)||void 0===t?void 0:t.value):i(void 0)},r.onerror=t=>{n("Failed adding item to objectStore, err: "+t)}}))}))}getAll(t,e){return new Promise(((i,n)=>{this.queryObjectStore(t,(t=>{const r=t.getAll(null,e);r.onsuccess=()=>{if(r.result){const t=r.result;(null==t?void 0:t.length)?i(t.map((t=>null==t?void 0:t.value))):i(t)}else i([])},r.onerror=t=>{n("Failed getting items, err: "+t)}}))}))}delete(t,e){return new Promise(((i,n)=>{this.queryObjectStore(t,(t=>{const r=t.delete(e);r.onsuccess=()=>{i()},r.onerror=t=>{n(`Failed deleting key: '${e}' from objectStore, err: `+t)}}))}))}clear(t){return new Promise(((e,i)=>{this.queryObjectStore(t,(t=>{const n=t.clear();n.onsuccess=()=>{e()},n.onerror=t=>{i("Failed clearing objectStore, err: "+t)}}))}))}}const R="platform";class K{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",i=arguments.length>2?arguments[2]:void 0;var r,a,s,o;this.agent=t,this.keysType=e,this.options=i;const c=!(null===(r=this.options)||void 0===r?void 0:r.productScope);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,this.indexedDBClient=new j(c?R:t.slug,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new j((c?R:t.slug)+`:${n.clientId}`,this.keysDatabaseName,this.dbVersion)}getKeysRecordKey(){return`${this.keysType}_keys`}arrayBufferToBase64(t){return window.btoa(String.fromCharCode(...new Uint8Array(t)))}async getPKRepresentations(t){const e=await crypto.subtle.exportKey("spki",t);return{arrayBufferKey:e,base64Key:this.arrayBufferToBase64(e)}}async generateKeyPair(){return"sign"==this.keysType?await I():await T()}async calcKeyIdentifier(t){const e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map((t=>t.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){const t=this.getKeysRecordKey();let e=await this.indexedDBClient.get(this.keysStoreName,t);if(!e){if(e=await this.indexedDBClientFallback.get(this.keysStoreName,t),!e){const t=await this.generateKeyPair(),{arrayBufferKey:i,base64Key:n}=await this.getPKRepresentations(t.publicKey);this.publicKeyBase64=n,this.keyIdentifier=await this.calcKeyIdentifier(i),e=l(l({},t),{},{keyIdentifier:this.keyIdentifier})}await this.indexedDBClient.put(this.keysStoreName,t,e)}if(!this.publicKeyBase64){const{base64Key:t}=await this.getPKRepresentations(e.publicKey);this.publicKeyBase64=t,this.keyIdentifier=e.keyIdentifier}return e}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier}}async sign(t){if("sign"==this.keysType){const{privateKey:e}=await this.extractKeysData(),i=await O(e,t);return this.arrayBufferToBase64(i)}throw new Error("keysType must be 'sign' in order to use sign keys")}async encrypt(t){if("encrypt"==this.keysType){const{privateKey:e}=await this.extractKeysData();return await P(t,e)}throw new Error("keysType must be 'encrypt' in order to use encryption keys")}async clearKeys(){const t=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,t)}}var B=Object.freeze({__proto__:null,createCryptoBinding:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",e=arguments.length>1?arguments[1]:void 0;return new K(this,t,e)},decryptAssymetric:async(t,e)=>new Uint8Array(await window.crypto.subtle.decrypt({name:C},e,t)),encryptAssymetric:P,generateRSAKeyPair:T,generateRSASignKeyPair:I,signAssymetric:O,verifyAssymetric:async(t,e,i)=>{const n=(new TextEncoder).encode(e);return await window.crypto.subtle.verify(D,t,i,n)}}),E=Object.freeze({__proto__:null});const N=p.create((t=>{class e extends Error{constructor(e,i){super(`${t.slug}-${e} ${i}`)}}return{TsError:e,TsInternalError:class extends e{constructor(t){super(t,"Internal error")}}}}));var x=p.create((()=>l({exceptions:N},y)));class H{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=t,this.middlewares=e,this.logs=[]}info(t,e){this.pushLog(3,t,e)}warn(t,e){this.pushLog(4,t,e)}error(t,e){this.pushLog(5,t,e)}pushLog(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:t,fields:i,message:e});const n=this.middlewares.map((t=>t(this)));Promise.all(n).catch((()=>{}))}}var F=Object.freeze({__proto__:null,consoleMiddleware:function(t){const e=t.logs[t.logs.length-1];console.log(`${e.severity} ${e.message}`,e.fields)},createSdkLogger:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return new H(this,t)}});function q(t,e){if(!(null==t?void 0:t.trim()))return"";if(function(t){try{return new URL(t),!0}catch(t){return!1}}(t))return t;const i="http://mock.com",n=new URL(i);n.search=(null==e?void 0:e.toString())||"",n.pathname=t;return n.href.replace(i,"")}const z={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function M(t,e,i){var n;const r=(a=e||{},encodeURI(JSON.stringify(a)).split(/%..|./).length-1);var a;return{method:t,headers:l(l(l({},{"X-TS-body-size":String(r)}),z),i||{}),body:null!==(n=e&&JSON.stringify(e||{}))&&void 0!==n?n:void 0}}function $(t,e,i,n,r){const a=q(t,n),s=M(e,i,r);return fetch(a,s)}async function J(t,e,i,n,r){let a;if(a=await $(t,e,i,n,r),!a.ok)throw new Error("Request failed");return a}var L=Object.freeze({__proto__:null,httpDelete:async function(t,e){const i=await J(t,"DELETE",void 0,void 0,e);return l(l({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(t,e,i){const n=await J(t,"GET",void 0,e,i);return l(l({data:await n.json()},n),{},{headers:n.headers})},httpPost:async function(t,e,i,n){const r=await J(t,"POST",e,i,n);return l(l({data:await r.json()},r),{},{headers:r.headers})},httpPut:async function(t,e,i,n){const r=await J(t,"PUT",e,i,n);return l(l({data:await r.json()},r),{},{headers:r.headers})},init:M}),U=p.create((()=>({events:v,moduleMetadata:a,mainEntry:o,utils:x,storage:S,crypto:B,indexedDB:E,logger:F,http:L})));class V{static arrayBufferToBase64(t){return btoa(String.fromCharCode(...new Uint8Array(t)))}static base64ToArrayBuffer(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}static stringToBase64(t){return btoa(t)}static jsonToBase64(t){const e=JSON.stringify(t);return btoa(e)}static base64ToJson(t){const e=atob(t);return JSON.parse(e)}}const G={log:console.log,error:console.error};var W,Z;!function(t){t.NotInitialized="not_initialized",t.AuthenticationFailed="authentication_failed",t.AuthenticationAbortedTimeout="authentication_aborted_timeout",t.AuthenticationCanceled="webauthn_authentication_canceled",t.RegistrationFailed="registration_failed",t.AlreadyRegistered="username_already_registered",t.RegistrationAbortedTimeout="registration_aborted_timeout",t.RegistrationCanceled="webauthn_registration_canceled",t.AutofillAuthenticationAborted="autofill_authentication_aborted",t.AuthenticationProcessAlreadyActive="authentication_process_already_active",t.InvalidApprovalData="invalid_approval_data",t.FailedToInitCrossDeviceSession="cross_device_init_failed",t.FailedToGetCrossDeviceStatus="cross_device_status_failed",t.Unknown="unknown"}(W||(W={}));class X extends Error{constructor(t,e){super(t),this.errorCode=W.NotInitialized,this.data=e}}class Y extends X{constructor(t,e){super(null!=t?t:"WebAuthnSdk is not initialized",e),this.errorCode=W.NotInitialized}}class Q extends X{constructor(t,e){super(null!=t?t:"Authentication failed with an error",e),this.errorCode=W.AuthenticationFailed}}class tt extends X{constructor(t,e){super(null!=t?t:"Authentication was canceled by the user or got timeout",e),this.errorCode=W.AuthenticationCanceled}}class et extends X{constructor(t,e){super(null!=t?t:"Registration failed with an error",e),this.errorCode=W.RegistrationFailed}}class it extends X{constructor(t,e){super(null!=t?t:"Registration was canceled by the user or got timeout",e),this.errorCode=W.RegistrationCanceled}}class nt extends X{constructor(t){super(null!=t?t:"Autofill flow was aborted"),this.errorCode=W.AutofillAuthenticationAborted}}class rt extends X{constructor(t){super(null!=t?t:"Operation was aborted by timeout"),this.errorCode=W.AutofillAuthenticationAborted}}class at extends X{constructor(t){super(null!=t?t:"Passkey with this username is already registered with the relying party."),this.errorCode=W.AlreadyRegistered}}class st extends X{constructor(t,e){super(null!=t?t:"Authentication process is already active",e),this.errorCode=W.AuthenticationProcessAlreadyActive}}class ot extends X{constructor(t,e){super(null!=t?t:"Invalid approval data",e),this.errorCode=W.InvalidApprovalData}}class ct extends X{constructor(t,e){super(null!=t?t:"Failed to init cross device authentication",e),this.errorCode=W.FailedToInitCrossDeviceSession}}class lt extends X{constructor(t,e){super(null!=t?t:"Failed to get cross device status",e),this.errorCode=W.FailedToGetCrossDeviceStatus}}function ut(t){return t.errorCode&&Object.values(W).includes(t.errorCode)}!function(t){t[t.persistent=0]="persistent",t[t.session=1]="session"}(Z||(Z={}));class dt{static get(t){return dt.getStorageMedium(dt.allowedKeys[t]).getItem(dt.getStorageKey(t))||void 0}static set(t,e){return dt.getStorageMedium(dt.allowedKeys[t]).setItem(dt.getStorageKey(t),e)}static remove(t){dt.getStorageMedium(dt.allowedKeys[t]).removeItem(dt.getStorageKey(t))}static clear(t){for(const[e,i]of Object.entries(dt.allowedKeys)){const n=e;t&&this.configurationKeys.includes(n)||dt.getStorageMedium(i).removeItem(dt.getStorageKey(n))}}static getStorageKey(t){return`WebAuthnSdk:${t}`}static getStorageMedium(t){return t===Z.session?sessionStorage:localStorage}}dt.allowedKeys={clientId:Z.session},dt.configurationKeys=["clientId"];class ht{static isNewApiDomain(t){return t&&(this.newApiDomains.includes(t)||t.startsWith("api.")&&t.endsWith(".transmitsecurity.io"))}static dnsPrefetch(t){const e=document.createElement("link");e.rel="dns-prefetch",e.href=t,document.head.appendChild(e)}static preconnect(t,e){const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}static warmupConnection(t){this.dnsPrefetch(t),this.preconnect(t,!1),this.preconnect(t,!0)}static init(t,e){var i,n;try{this._serverPath=new URL(e.serverPath),this.isNewApiDomain(null===(i=this._serverPath)||void 0===i?void 0:i.hostname)&&this.warmupConnection(this._serverPath.origin),this._apiPaths=null!==(n=e.webauthnApiPaths)&&void 0!==n?n:this.getDefaultPaths(),this._clientId=t,dt.set("clientId",t)}catch(t){throw new Y("Invalid options.serverPath",{error:t})}}static getDefaultPaths(){var t;const e=this.isNewApiDomain(null===(t=this._serverPath)||void 0===t?void 0:t.hostname)?"/cis":"";return{startAuthentication:`${e}/v1/auth/webauthn/authenticate/start`,startRegistration:`${e}/v1/auth/webauthn/register/start`,initCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/init`,startCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/start`,startCrossDeviceRegistration:`${e}/v1/auth/webauthn/cross-device/register/start`,getCrossDeviceTicketStatus:`${e}/v1/auth/webauthn/cross-device/status`,attachDeviceToCrossDeviceSession:`${e}/v1/auth/webauthn/cross-device/attach-device`}}static getApiPaths(){return this._apiPaths}static async sendRequest(t,e,i){G.log(`[WebAuthn SDK] Calling ${e.method} ${t}...`);const n=new URL(this._serverPath);return n.pathname=t,i&&(n.search=i),fetch(n.toString(),e)}static async startRegistration(t){const e=await this.sendRequest(this._apiPaths.startRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId(),username:t.username,display_name:t.displayName},t.timeout&&{timeout:t.timeout}),t.limitSingleCredentialToDevice&&{limit_single_credential_to_device:t.limitSingleCredentialToDevice}))});if(!(null==e?void 0:e.ok))throw new Q("Failed to start registration",null==e?void 0:e.body);return await e.json()}static async startAuthentication(t){const e=await this.sendRequest(this._apiPaths.startAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}),t.timeout&&{timeout:t.timeout}))});if(!(null==e?void 0:e.ok))throw new Q("Failed to start authentication",null==e?void 0:e.body);return await e.json()}static async initCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.initCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}))});if(!(null==e?void 0:e.ok))throw new ct(void 0,null==e?void 0:e.body);return await e.json()}static async getCrossDeviceTicketStatus(t){const e=await this.sendRequest(this._apiPaths.getCrossDeviceTicketStatus,{method:"GET"},`cross_device_ticket_id=${t.ticketId}`);if(!(null==e?void 0:e.ok))throw new lt(void 0,null==e?void 0:e.body);return await e.json()}static async startCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new Q("Failed to start cross device authentication",null==e?void 0:e.body);return await e.json()}static async startCrossDeviceRegistration(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new et("Failed to start cross device registration",null==e?void 0:e.body);return await e.json()}static async attachDeviceToCrossDeviceSession(t){const e=await this.sendRequest(this._apiPaths.attachDeviceToCrossDeviceSession,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new et("Failed to attach device to cross device session",null==e?void 0:e.body);return await e.json()}static getValidatedClientId(){var t;const e=null!==(t=this._clientId)&&void 0!==t?t:dt.get("clientId");if(!e)throw new Y("Missing clientId");return e}}var pt,yt,vt,gt;ht.newApiDomains=["api.idsec-dev.com","api.idsec-stg.com"],function(t){t.InputAutofill="input-autofill",t.Modal="modal"}(pt||(pt={})),function(t){t.Pending="pending",t.Scanned="scanned",t.Success="success",t.Error="error",t.Timeout="timeout",t.Aborted="aborted"}(yt||(yt={})),function(t){t.toAuthenticationError=t=>ut(t)?t:"NotAllowedError"===t.name?new tt:"OperationError"===t.name?new st(t.message):"SecurityError"===t.name?new Q(t.message):t===W.AuthenticationAbortedTimeout?new rt:"AbortError"===t.name||t===W.AutofillAuthenticationAborted?new nt:new Q("Something went wrong during authentication",{error:t}),t.toRegistrationError=t=>ut(t)?t:"NotAllowedError"===t.name?new it:"SecurityError"===t.name?new et(t.message):"InvalidStateError"===t.name?new at:t===W.RegistrationAbortedTimeout?new rt:new et("Something went wrong during registration",{error:t})}(vt||(vt={})),function(t){t.processCredentialRequestOptions=t=>l(l({},t),{},{challenge:V.base64ToArrayBuffer(t.challenge),allowCredentials:t.allowCredentials.map((t=>l(l({},t),{},{id:V.base64ToArrayBuffer(t.id)})))}),t.processCredentialCreationOptions=(t,e)=>{var i;const n=JSON.parse(JSON.stringify(t));return n.challenge=V.base64ToArrayBuffer(t.challenge),n.user.id=V.base64ToArrayBuffer(t.user.id),(null==e?void 0:e.limitSingleCredentialToDevice)&&(n.excludeCredentials=null===(i=t.excludeCredentials)||void 0===i?void 0:i.map((t=>l(l({},t),{},{id:V.base64ToArrayBuffer(t.id)})))),(null==e?void 0:e.registerAsDiscoverable)?(n.authenticatorSelection.residentKey="preferred",n.authenticatorSelection.requireResidentKey=!0):(n.authenticatorSelection.residentKey="discouraged",n.authenticatorSelection.requireResidentKey=!1),n.authenticatorSelection.authenticatorAttachment=(null==e?void 0:e.allowCrossPlatformAuthenticators)?void 0:"platform",n},t.encodeAuthenticationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:V.arrayBufferToBase64(t.rawId),response:{authenticatorData:V.arrayBufferToBase64(i.authenticatorData),clientDataJSON:V.arrayBufferToBase64(i.clientDataJSON),signature:V.arrayBufferToBase64(i.signature),userHandle:V.arrayBufferToBase64(i.userHandle)},authenticatorAttachment:e,type:t.type}},t.encodeRegistrationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:V.arrayBufferToBase64(t.rawId),response:{attestationObject:V.arrayBufferToBase64(i.attestationObject),clientDataJSON:V.arrayBufferToBase64(i.clientDataJSON)},authenticatorAttachment:e,type:t.type}}}(gt||(gt={}));class ft{async modal(t){try{const e=await this.performAuthentication(l(l({},t),{},{mediationType:pt.Modal}));return V.jsonToBase64(e)}catch(t){throw vt.toAuthenticationError(t)}}activateAutofill(t,e){const{onSuccess:i,onError:n,onReady:r}=t;this.performAuthentication({username:e,mediationType:pt.InputAutofill,onReady:r}).then((t=>{i(V.jsonToBase64(t))})).catch((t=>{const e=vt.toAuthenticationError(t);if(!n)throw e;n(e)}))}abortAutofill(){this.abortController&&this.abortController.abort(W.AutofillAuthenticationAborted)}abortAuthentication(){this.abortController&&this.abortController.abort(W.AuthenticationAbortedTimeout)}async performAuthentication(t){var e,i;const n="crossDeviceTicketId"in t?await ht.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await ht.startAuthentication({username:t.username,timeout:null===(e=t.options)||void 0===e?void 0:e.timeout}),r=n.credential_request_options,a=gt.processCredentialRequestOptions(r),s=this.getMediatedCredentialRequest(a,t.mediationType);t.mediationType===pt.InputAutofill&&(null===(i=t.onReady)||void 0===i||i.call(t));const o=await navigator.credentials.get(s).catch((t=>{throw vt.toAuthenticationError(t)}));return{webauthnSessionId:n.webauthn_session_id,publicKeyCredential:gt.encodeAuthenticationResult(o),userAgent:navigator.userAgent}}getMediatedCredentialRequest(t,e){const i={publicKey:t};return this.abortController=new AbortController,i.signal=this.abortController&&this.abortController.signal,e===pt.InputAutofill?i.mediation="conditional":t.timeout&&setTimeout((()=>{this.abortAuthentication()}),t.timeout),i}}class wt{constructor(t,e){this.handler=t,this.intervalInMs=e}begin(){var t;this.intervalId=window.setInterval((t=this.handler,async function(){t.isRunning||(t.isRunning=!0,await t(...arguments),t.isRunning=!1)}),this.intervalInMs)}stop(){clearInterval(this.intervalId)}}const mt=/^[A-Za-z0-9\-_.: ]*$/;function bt(t){if(t&&(!function(t){return Object.keys(t).length<=10}(t)||!function(t){const e=t=>"string"==typeof t,i=t=>mt.test(t);return Object.keys(t).every((n=>e(n)&&e(t[n])&&i(n)&&i(t[n])))}(t)))throw G.error("Failed validating approval data"),new ot("Provided approval data should have 10 properties max. Also, it should contain only \n alphanumeric characters, numbers, and the special characters: '-', '_', '.'")}class At{constructor(t,e,i){this.authenticationHandler=t,this.registrationHandler=e,this.approvalHandler=i,this.init={registration:async t=>(this.ticketStatus=yt.Pending,this.pollCrossDeviceSession(t.crossDeviceTicketId,t.handlers)),authentication:async t=>{const{username:e}=t,i=(await ht.initCrossDeviceAuthentication(l({},e&&{username:e}))).cross_device_ticket_id;return this.ticketStatus=yt.Pending,this.pollCrossDeviceSession(i,t.handlers)},approval:async t=>{const{username:e,approvalData:i}=t;bt(i);const n=(await ht.initCrossDeviceAuthentication({username:e,approvalData:i})).cross_device_ticket_id;return this.ticketStatus=yt.Pending,this.pollCrossDeviceSession(n,t.handlers)}},this.authenticate={modal:async t=>this.authenticationHandler.modal({crossDeviceTicketId:t})},this.approve={modal:async t=>this.approvalHandler.modal({crossDeviceTicketId:t})}}async register(t,e){return this.registrationHandler.register({crossDeviceTicketId:t},e)}async attachDevice(t){const e=await ht.attachDeviceToCrossDeviceSession({ticketId:t});return l({status:e.status,startedAt:e.started_at},e.approval_data&&{approvalData:e.approval_data})}async pollCrossDeviceSession(t,e){return this.poller=new wt((async()=>{var i,n;const r=await ht.getCrossDeviceTicketStatus({ticketId:t}),a=r.status;if(a!==this.ticketStatus)switch(this.ticketStatus=a,a){case yt.Scanned:await e.onDeviceAttach();break;case yt.Error:case yt.Timeout:case yt.Aborted:await e.onFailure(r),null===(i=this.poller)||void 0===i||i.stop();break;case yt.Success:if("onCredentialRegister"in e)await e.onCredentialRegister();else{if(!r.session_id)throw new lt("Cross device session is complete without returning session_id",r);await e.onCredentialAuthenticate(r.session_id)}null===(n=this.poller)||void 0===n||n.stop()}}),1e3),this.poller.begin(),setTimeout((()=>{var t;null===(t=this.poller)||void 0===t||t.stop(),e.onFailure({status:yt.Timeout})}),3e5),{crossDeviceTicketId:t,stop:()=>{var t;null===(t=this.poller)||void 0===t||t.stop()}}}}class _t{async register(t,e){this.abortController=new AbortController;const i=l({allowCrossPlatformAuthenticators:!("crossDeviceTicketId"in t),registerAsDiscoverable:!0},e);try{const n="crossDeviceTicketId"in t?await ht.startCrossDeviceRegistration({ticketId:t.crossDeviceTicketId}):await ht.startRegistration({username:t.username,displayName:(null==e?void 0:e.displayName)||t.username,timeout:null==e?void 0:e.timeout,limitSingleCredentialToDevice:null==e?void 0:e.limitSingleCredentialToDevice}),r=gt.processCredentialCreationOptions(n.credential_creation_options,i);setTimeout((()=>{this.abortRegistration()}),r.timeout);const a=await this.registerCredential(r),s={webauthnSessionId:n.webauthn_session_id,publicKeyCredential:a,userAgent:navigator.userAgent};return V.jsonToBase64(s)}catch(t){throw vt.toRegistrationError(t)}}abortRegistration(){this.abortController&&this.abortController.abort(W.RegistrationAbortedTimeout)}async registerCredential(t){const e=await navigator.credentials.create({publicKey:t,signal:this.abortController&&this.abortController.signal}).catch((t=>{throw vt.toRegistrationError(t)}));return gt.encodeRegistrationResult(e)}}class St{async modal(t){try{const e=await this.performApproval(t);return V.jsonToBase64(e)}catch(t){throw vt.toAuthenticationError(t)}}async performApproval(t){"approvalData"in t&&bt(t.approvalData);const e="crossDeviceTicketId"in t?await ht.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await ht.startAuthentication({username:t.username,approvalData:t.approvalData}),i=e.credential_request_options,n=gt.processCredentialRequestOptions(i),r=await navigator.credentials.get({publicKey:n}).catch((t=>{throw vt.toAuthenticationError(t)}));return{webauthnSessionId:e.webauthn_session_id,publicKeyCredential:gt.encodeAuthenticationResult(r),userAgent:navigator.userAgent}}}class Ct{constructor(){this._initialized=!1,this._authenticationHandler=new ft,this._registrationHandler=new _t,this._approvalHandler=new St,this._crossDeviceHandler=new At(this._authenticationHandler,this._registrationHandler,this._approvalHandler),this.authenticate={modal:async(t,e)=>(this.initCheck(),this._authenticationHandler.modal({username:t,options:e})),autofill:{activate:(t,e)=>(this.initCheck(),this._authenticationHandler.activateAutofill(t,e)),abort:()=>this._authenticationHandler.abortAutofill()}},this.approve={modal:async(t,e)=>(this.initCheck(),this._approvalHandler.modal({username:t,approvalData:e}))},this.register=async(t,e)=>(this.initCheck(),this._registrationHandler.register({username:t},e)),this.crossDevice={init:{registration:async t=>(this.initCheck(),this._crossDeviceHandler.init.registration(t)),authentication:async t=>(this.initCheck(),this._crossDeviceHandler.init.authentication(t)),approval:async t=>(this.initCheck(),this._crossDeviceHandler.init.approval(t))},authenticate:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.authenticate.modal(t))},approve:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.approve.modal(t))},register:async(t,e)=>(this.initCheck(),this._crossDeviceHandler.register(t,e)),attachDevice:async t=>(this.initCheck(),this._crossDeviceHandler.attachDevice(t))},this.isPlatformAuthenticatorSupported=async()=>{var t;try{return await(null===(t=Ct.StaticPublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable())}catch(t){return!1}},this.isAutofillSupported=async()=>{var t,e;return!(!(null===(t=Ct.StaticPublicKeyCredential)||void 0===t?void 0:t.isConditionalMediationAvailable)||!await(null===(e=Ct.StaticPublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable()))}}async init(t,e){try{if(!t)throw new Y("Invalid clientId",{clientId:t});if(e.webauthnApiPaths){const t=ht.getDefaultPaths();if(function(t,e){const i=new Set(t),n=new Set(e);return[...t.filter((t=>!n.has(t))),...e.filter((t=>!i.has(t)))]}(Object.keys(e.webauthnApiPaths),Object.keys(t)).length)throw new Y("Invalid custom paths",{customApiPaths:e.webauthnApiPaths})}ht.init(t,e),this._initialized=!0}catch(t){throw ut(t)?t:new Y("Failed to initialize SDK")}}getDefaultPaths(){return this.initCheck(),ht.getDefaultPaths()}getApiPaths(){return this.initCheck(),ht.getApiPaths()}initCheck(){if(!this._initialized)throw new Y}}Ct.StaticPublicKeyCredential=window.PublicKeyCredential;const Dt=new U("webauthn"),kt=new Ct;Dt.events.on(Dt.events.MODULE_INITIALIZED,(()=>{var t;const e=Dt.moduleMetadata.getInitConfig();if(!(null===(t=null==e?void 0:e.webauthn)||void 0===t?void 0:t.serverPath))return;const{clientId:i,webauthn:n}=e;kt.init(i,l({},n))}));const Tt={modal:async(t,e)=>(kt.initCheck(),kt.authenticate.modal(t,e)),autofill:{activate:(t,e)=>{kt.initCheck(),kt.authenticate.autofill.activate(t,e)},abort:()=>{kt.initCheck(),kt.authenticate.autofill.abort()}}},It={modal:async(t,e)=>(kt.initCheck(),kt.approve.modal(t,e))};async function Pt(t,e){return kt.initCheck(),kt.register(t,e)}const{crossDevice:Ot}=kt,{isPlatformAuthenticatorSupported:jt}=kt,{isAutofillSupported:Rt}=kt,{getDefaultPaths:Kt}=kt;window.localWebAuthnSDK=kt;const Bt="1.15.0",Et={initialize:s,...Object.freeze({__proto__:null,get WebauthnCrossDeviceStatus(){return yt},approve:It,authenticate:Tt,crossDevice:Ot,getDefaultPaths:Kt,isAutofillSupported:Rt,isPlatformAuthenticatorSupported:jt,register:Pt})};export{Bt as PACKAGE_VERSION,yt as WebauthnCrossDeviceStatus,It as approve,Tt as authenticate,Ot as crossDevice,Kt as getDefaultPaths,s as initialize,Rt as isAutofillSupported,jt as isPlatformAuthenticatorSupported,Pt as register,Et as webauthn};
|
|
1
|
+
"undefined"==typeof globalThis&&("undefined"!=typeof window?(window.globalThis=window,window.global=window):"undefined"!=typeof self&&(self.globalThis=self,self.global=self));const t=Symbol("MODULE_INITIALIZED"),e=new Map;function i(t,i){var a,n;null===(a=e.get(t))||void 0===a||a.forEach((n=t=>t(i),function(){try{return n(...arguments)}catch(t){console.log(t)}}))}let a=null;function n(t){a=t}var s=Object.freeze({__proto__:null,getInitConfig:function(){return a},get initConfig(){return a},setInitConfig:n});function r(e){n(e),i(t,void 0)}var o=Object.freeze({__proto__:null,initialize:r});function c(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,a)}return i}function l(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?c(Object(i),!0).forEach((function(e){u(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):c(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function d(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var a=i.call(t,e||"default");if("object"!=typeof a)return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function u(t,e,i){return(e=d(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function h(t,e){return Object.entries(e).reduce(((e,i)=>{let[a,n]=i;return l(l({},e),{},{[a]:y.isPrototypeOf(n)?new n(t.slug):"function"==typeof n?n.bind(t):"object"==typeof n&&!Array.isArray(n)&&n?h(t,n):n})}),{})}class y{constructor(t){this.slug=t}static create(t){return class extends y{constructor(e){super(e),Object.assign(this,h(this,t(this)))}}}}var p=Object.freeze({__proto__:null,Agent:y}),g=Object.freeze({__proto__:null,MODULE_INITIALIZED:t,emit:i,off:function(t,i){const a=e.get(t);if(!a)return;const n=a.indexOf(i);-1!==n&&a.splice(n,1)},on:function(t,i){var a;e.has(t)?null===(a=e.get(t))||void 0===a||a.push(i):e.set(t,[i])}});function v(t,e){const i=!t||"object"!=typeof t||Array.isArray(t)?{}:t;return[e.reduce(((t,e)=>{if(e in t){const i=t[e];if(null!==i&&"object"==typeof i&&!Array.isArray(i))return i}const i={};return t[e]=i,i}),i),i]}function w(t,e){let i=t;return e.every((t=>!(!i||"object"!=typeof i||Array.isArray(i)||!(t in i))&&(i=i[t],!0)),t)}const f="tsec",m="general";function b(t){return t?m:a.clientId}function D(t){return function(t){if(!t)return{};try{return JSON.parse(t)}catch(t){return{}}}((t?sessionStorage:localStorage).getItem(f))}function A(t,e){const i=t?sessionStorage:localStorage,a=e(D(t));i.setItem(f,JSON.stringify(a))}var _=Object.freeze({__proto__:null,COMMON_STORAGE_KEY:f,GENERAL_ID_KEY:m,getValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),a=D(!!e.sessionOnly),[n]=v(a,[this.slug.toString(),i]);return n[t]},hasValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral),a=D(!!e.sessionOnly);return w(a,[this.slug.toString(),i,t])},removeValue:function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=b(!!e.isGeneral);A(!!e.sessionOnly,(e=>{const[a,n]=v(e,[this.slug.toString(),i]);return delete a[t],n}))},setValue:function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=b(!!i.isGeneral);A(!!i.sessionOnly,(i=>{const[n,s]=v(i,[this.slug.toString(),a]);return n[t]=e,s}))}});const S="RSA-PSS",C=async(t,e)=>await window.crypto.subtle.generateKey({name:t,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!1,e),K=async()=>await C("RSA-OAEP",["encrypt","decrypt"]),k=async()=>await C(S,["sign"]),R=async(t,e)=>{const i=(new TextEncoder).encode(e);return await window.crypto.subtle.sign({name:S,saltLength:32},t,i)};class P{constructor(t,e,i){this.slug=t,this.dbName=e,this.dbVersion=i}queryObjectStore(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=(window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB||window.shimIndexedDB).open(`${this.slug}:${this.dbName}`,this.dbVersion||1);a.onupgradeneeded=()=>{var e;const i=a.result;(null===(e=null==i?void 0:i.objectStoreNames)||void 0===e?void 0:e.contains)&&!i.objectStoreNames.contains(t)&&i.createObjectStore(t,{keyPath:"key"})},a.onsuccess=()=>{const n=a.result,s=n.transaction(t,(null==i?void 0:i.operation)||"readwrite"),r=s.objectStore(t);e(r),s.oncomplete=()=>{n.close()}}}put(t,e,i){return new Promise(((a,n)=>{this.queryObjectStore(t,(t=>{const s=t.put({key:e,value:i});s.onsuccess=()=>{a(s.result)},s.onerror=t=>{n("Failed adding item to objectStore, err: "+t)}}))}))}add(t,e,i){return new Promise(((a,n)=>{this.queryObjectStore(t,(t=>{const s=t.add({key:e,value:i});s.onsuccess=()=>{a(s.result)},s.onerror=t=>{const e=t.target.error;n(e)}}))}))}get(t,e){return new Promise(((i,a)=>{this.queryObjectStore(t,(t=>{const n=t.get(e);n.onsuccess=()=>{var t;n.result?i(null===(t=n.result)||void 0===t?void 0:t.value):i(void 0)},n.onerror=t=>{a("Failed adding item to objectStore, err: "+t)}}))}))}getAll(t,e){return new Promise(((i,a)=>{this.queryObjectStore(t,(t=>{const n=t.getAll(null,e);n.onsuccess=()=>{if(n.result){const t=n.result;(null==t?void 0:t.length)?i(t.map((t=>null==t?void 0:t.value))):i(t)}else i([])},n.onerror=t=>{a("Failed getting items, err: "+t)}}))}))}delete(t,e){return new Promise(((i,a)=>{this.queryObjectStore(t,(t=>{const n=t.delete(e);n.onsuccess=()=>{i()},n.onerror=t=>{a(`Failed deleting key: '${e}' from objectStore, err: `+t)}}))}))}clear(t){return new Promise(((e,i)=>{this.queryObjectStore(t,(t=>{const a=t.clear();a.onsuccess=()=>{e()},a.onerror=t=>{i("Failed clearing objectStore, err: "+t)}}))}))}}const T="platform",I="init",O="completed",j="RSA2048",x=[I,O];class B{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"sign",i=arguments.length>2?arguments[2]:void 0;var n,s,r,o;this.agent=t,this.keysType=e,this.options=i,this._extractingKeysPromise=null;const c=!(null===(n=this.options)||void 0===n?void 0:n.productScope);this.keysDatabaseName=c||!(null===(s=this.options)||void 0===s?void 0:s.indexedDBName)?"ts_crypto_binding":this.options.indexedDBName,this.dbVersion=c?1:(null===(r=this.options)||void 0===r?void 0:r.dbVersion)||1,this.keysStoreName=c||!(null===(o=this.options)||void 0===o?void 0:o.keysStoreName)?"identifiers_store":this.options.keysStoreName,this.indexedDBClient=new P(c?T:t.slug,this.keysDatabaseName,this.dbVersion),this.indexedDBClientFallback=new P((c?T:t.slug)+`:${a.clientId}`,this.keysDatabaseName,this.dbVersion)}getKeysRecordKey(){return`${this.keysType}_keys`}getRotatedKeysRecordKey(){return`rotated_${this.keysType}_keys`}getRotatedKeysRecordKeyPending(){return`rotated_pending_${this.keysType}_keys`}arrayBufferToBase64(t){return window.btoa(String.fromCharCode(...new Uint8Array(t)))}async getPKRepresentations(t){const e=await crypto.subtle.exportKey("spki",t);return{arrayBufferKey:e,base64Key:this.arrayBufferToBase64(e)}}async generateKeyPair(){return"sign"==this.keysType?await k():await K()}async calcKeyIdentifier(t){const e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map((t=>t.toString(16).padStart(2,"0"))).join("")}async extractKeysData(){if(this._extractingKeysPromise)return this._extractingKeysPromise;this._extractingKeysPromise=(async()=>{var t,e;const i=(null===(e=null===(t=this.options)||void 0===t?void 0:t.keyRotation)||void 0===e?void 0:e.isEnabled)?await this.getRotatedKeysData():await this.getKeysData(),{base64Key:a}=await this.getPKRepresentations(i.publicKey);return this.publicKeyBase64=a,this.keyIdentifier=i.keyIdentifier,i})();try{return await this._extractingKeysPromise}finally{this._extractingKeysPromise=null}}async generateKeyPairData(t){const e=await this.generateKeyPair(),{arrayBufferKey:i}=await this.getPKRepresentations(e.publicKey),a=t||await this.calcKeyIdentifier(i);return l(l({},e),{},{keyIdentifier:a,createdDate:Date.now()})}shouldKeyBeRotated(t){var e;const i=null===(e=this.options)||void 0===e?void 0:e.keyRotation;if(!(null==i?void 0:i.isEnabled)||!i.expiryDays||void 0===i.startedAt)return!1;const a=24*i.expiryDays*60*60*1e3,n=t.createdDate&&t.createdDate>=i.startedAt?t.createdDate:i.startedAt;return Date.now()-n>a-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(t,e){try{return await this.indexedDBClient.add(this.keysStoreName,t,e),e}catch(e){if(e instanceof DOMException&&"ConstraintError"===e.name){const e=await this.indexedDBClient.get(this.keysStoreName,t);if(e)return e}throw e}}async getKeysData(){const t=this.getKeysRecordKey();let e=await this.extractMainKeysData();if(e)return e;if(e=await this.extractFallbackMainKeysData(),e)return this.saveKeyData(t,e);const i=await this.generateKeyPairData();return this.saveKeyData(t,i)}async getOrCreateRotatedKeys(){let t=await this.extractRotatedKeysData();if(!t){const e=this.getRotatedKeysRecordKey(),i=await this.getKeysData(),a=l(l({},i),{},{createdDate:i.createdDate||Date.now()});t=await this.saveKeyData(e,a)}return t}async getRotatedKeysData(){const t=await this.getOrCreateRotatedKeys();if(this.shouldKeyBeRotated(t)){if(!await this.extractPendingRotatedKeysData()){const e=this.getRotatedKeysRecordKeyPending(),i=await this.generateKeyPairData(t.keyIdentifier);await this.saveKeyData(e,i)}}return t}async getPublicData(){return this.publicKeyBase64&&this.keyIdentifier||await this.extractKeysData(),{publicKey:this.publicKeyBase64,keyIdentifier:this.keyIdentifier}}async sign(t){if("sign"==this.keysType){const{privateKey:e}=await this.extractKeysData(),i=await R(e,t);return this.arrayBufferToBase64(i)}throw new Error("keysType must be 'sign' in order to use sign keys")}async clearKeys(){const t=this.getKeysRecordKey();await this.indexedDBClient.delete(this.keysStoreName,t)}getBaseRotationPayload(){return{keyIdentifier:this.keyIdentifier,slot:this.getRotatedKeysRecordKey(),publicKey:this.publicKeyBase64,publicKeyType:j,tenantId:this.options.keyRotation.tenantId}}async getRotationData(){var t,e;if(!(null===(e=null===(t=this.options)||void 0===t?void 0:t.keyRotation)||void 0===e?void 0:e.isEnabled))return;this.publicKeyBase64&&this.keyIdentifier||await this.extractKeysData();const i=await this.extractPendingRotatedKeysData();if(i){const{base64Key:t}=await this.getPKRepresentations(i.publicKey),{privateKey:e}=await this.extractKeysData(),a=l(l({},this.getBaseRotationPayload()),{},{newPublicKey:t,createdDate:i.createdDate,newPublicKeyType:j}),n=JSON.stringify(a);return{data:n,signature:await this.signPayload(n,e)}}const a=await this.extractRotatedKeysData();if(a&&!1===a.confirmed){await this.extractKeysData();const t=JSON.stringify(this.getBaseRotationPayload());return{data:t,signature:await this.signPayload(t,a.privateKey)}}}async signPayload(t,e){const i=await R(e,t);return this.arrayBufferToBase64(i)}async handleRotateResponse(t){if(x.includes(t))if(t===I){const t=await this.extractPendingRotatedKeysData();if(t){await this.indexedDBClient.delete(this.keysStoreName,this.getRotatedKeysRecordKey());const e=l(l({},t),{},{confirmed:!1});await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),e),await this.indexedDBClient.delete(this.keysStoreName,this.getRotatedKeysRecordKeyPending());const{base64Key:i}=await this.getPKRepresentations(t.publicKey);this.publicKeyBase64=i,this.keyIdentifier=t.keyIdentifier}}else if(t===O){const t=await this.extractRotatedKeysData();t&&!1===t.confirmed&&await this.indexedDBClient.put(this.keysStoreName,this.getRotatedKeysRecordKey(),l(l({},t),{},{confirmed:!0}))}}}var N=Object.freeze({__proto__:null,createCryptoBinding:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"sign",e=arguments.length>1?arguments[1]:void 0;return new B(this,t,e)},generateRSAKeyPair:K,generateRSASignKeyPair:k,signAssymetric:R,verifyAssymetric:async(t,e,i)=>{const a=(new TextEncoder).encode(e);return await window.crypto.subtle.verify(S,t,i,a)}}),E=Object.freeze({__proto__:null});const H=y.create((t=>{class e extends Error{constructor(e,i){super(`${t.slug}-${e} ${i}`)}}return{TsError:e,TsInternalError:class extends e{constructor(t){super(t,"Internal error")}}}}));var F=y.create((()=>l({exceptions:H},p)));class M{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.agent=t,this.middlewares=e,this.logs=[]}info(t,e){this.pushLog(3,t,e)}warn(t,e){this.pushLog(4,t,e)}error(t,e){this.pushLog(5,t,e)}pushLog(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.logs.push({timestamp:Date.now(),module:this.agent.slug,severity:t,fields:i,message:e});const a=this.middlewares.map((t=>t(this)));Promise.all(a).catch((()=>{}))}}var q=Object.freeze({__proto__:null,consoleMiddleware:function(t){const e=t.logs[t.logs.length-1];console.log(`${e.severity} ${e.message}`,e.fields)},createSdkLogger:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return new M(this,t)}});function z(t,e){if(!(null==t?void 0:t.trim()))return"";if(function(t){try{return new URL(t),!0}catch(t){return!1}}(t))return t;const i="http://mock.com",a=new URL(i);a.search=(null==e?void 0:e.toString())||"",a.pathname=t;return a.href.replace(i,"")}const $={"Content-Type":"application/json","X-TS-client-time":(new Date).toUTCString(),"X-TS-ua":navigator.userAgent};function J(t,e,i){var a;const n=(s=e||{},encodeURI(JSON.stringify(s)).split(/%..|./).length-1);var s;return{method:t,headers:l(l(l({},{"X-TS-body-size":String(n)}),$),i||{}),body:null!==(a=e&&JSON.stringify(e||{}))&&void 0!==a?a:void 0}}function L(t,e,i,a,n){const s=z(t,a),r=J(e,i,n);return fetch(s,r)}async function U(t,e,i,a,n){let s;if(s=await L(t,e,i,a,n),!s.ok)throw new Error("Request failed");return s}var V=Object.freeze({__proto__:null,httpDelete:async function(t,e){const i=await U(t,"DELETE",void 0,void 0,e);return l(l({data:await i.json()},i),{},{headers:i.headers})},httpGet:async function(t,e,i){const a=await U(t,"GET",void 0,e,i);return l(l({data:await a.json()},a),{},{headers:a.headers})},httpPost:async function(t,e,i,a){const n=await U(t,"POST",e,i,a);return l(l({data:await n.json()},n),{},{headers:n.headers})},httpPut:async function(t,e,i,a){const n=await U(t,"PUT",e,i,a);return l(l({data:await n.json()},n),{},{headers:n.headers})},init:J}),G=y.create((()=>({events:g,moduleMetadata:s,mainEntry:o,utils:F,storage:_,crypto:N,indexedDB:E,logger:q,http:V})));class W{static arrayBufferToBase64(t){return btoa(String.fromCharCode(...new Uint8Array(t)))}static base64ToArrayBuffer(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}static stringToBase64(t){return btoa(t)}static jsonToBase64(t){const e=JSON.stringify(t);return btoa(e)}static base64ToJson(t){const e=atob(t);return JSON.parse(e)}}const Z={log:console.log,error:console.error};var X,Y;!function(t){t.NotInitialized="not_initialized",t.AuthenticationFailed="authentication_failed",t.AuthenticationAbortedTimeout="authentication_aborted_timeout",t.AuthenticationCanceled="webauthn_authentication_canceled",t.RegistrationFailed="registration_failed",t.AlreadyRegistered="username_already_registered",t.RegistrationAbortedTimeout="registration_aborted_timeout",t.RegistrationCanceled="webauthn_registration_canceled",t.AutofillAuthenticationAborted="autofill_authentication_aborted",t.AuthenticationProcessAlreadyActive="authentication_process_already_active",t.InvalidApprovalData="invalid_approval_data",t.FailedToInitCrossDeviceSession="cross_device_init_failed",t.FailedToGetCrossDeviceStatus="cross_device_status_failed",t.Unknown="unknown"}(X||(X={}));class Q extends Error{constructor(t,e){super(t),this.errorCode=X.NotInitialized,this.data=e}}class tt extends Q{constructor(t,e){super(null!=t?t:"WebAuthnSdk is not initialized",e),this.errorCode=X.NotInitialized}}class et extends Q{constructor(t,e){super(null!=t?t:"Authentication failed with an error",e),this.errorCode=X.AuthenticationFailed}}class it extends Q{constructor(t,e){super(null!=t?t:"Authentication was canceled by the user or got timeout",e),this.errorCode=X.AuthenticationCanceled}}class at extends Q{constructor(t,e){super(null!=t?t:"Registration failed with an error",e),this.errorCode=X.RegistrationFailed}}class nt extends Q{constructor(t,e){super(null!=t?t:"Registration was canceled by the user or got timeout",e),this.errorCode=X.RegistrationCanceled}}class st extends Q{constructor(t){super(null!=t?t:"Autofill flow was aborted"),this.errorCode=X.AutofillAuthenticationAborted}}class rt extends Q{constructor(t){super(null!=t?t:"Operation was aborted by timeout"),this.errorCode=X.AutofillAuthenticationAborted}}class ot extends Q{constructor(t){super(null!=t?t:"Passkey with this username is already registered with the relying party."),this.errorCode=X.AlreadyRegistered}}class ct extends Q{constructor(t,e){super(null!=t?t:"Authentication process is already active",e),this.errorCode=X.AuthenticationProcessAlreadyActive}}class lt extends Q{constructor(t,e){super(null!=t?t:"Invalid approval data",e),this.errorCode=X.InvalidApprovalData}}class dt extends Q{constructor(t,e){super(null!=t?t:"Failed to init cross device authentication",e),this.errorCode=X.FailedToInitCrossDeviceSession}}class ut extends Q{constructor(t,e){super(null!=t?t:"Failed to get cross device status",e),this.errorCode=X.FailedToGetCrossDeviceStatus}}function ht(t){return t.errorCode&&Object.values(X).includes(t.errorCode)}!function(t){t[t.persistent=0]="persistent",t[t.session=1]="session"}(Y||(Y={}));class yt{static get(t){return yt.getStorageMedium(yt.allowedKeys[t]).getItem(yt.getStorageKey(t))||void 0}static set(t,e){return yt.getStorageMedium(yt.allowedKeys[t]).setItem(yt.getStorageKey(t),e)}static remove(t){yt.getStorageMedium(yt.allowedKeys[t]).removeItem(yt.getStorageKey(t))}static clear(t){for(const[e,i]of Object.entries(yt.allowedKeys)){const a=e;t&&this.configurationKeys.includes(a)||yt.getStorageMedium(i).removeItem(yt.getStorageKey(a))}}static getStorageKey(t){return`WebAuthnSdk:${t}`}static getStorageMedium(t){return t===Y.session?sessionStorage:localStorage}}yt.allowedKeys={clientId:Y.session},yt.configurationKeys=["clientId"];class pt{static isNewApiDomain(t){return t&&(this.newApiDomains.includes(t)||t.startsWith("api.")&&t.endsWith(".transmitsecurity.io"))}static dnsPrefetch(t){const e=document.createElement("link");e.rel="dns-prefetch",e.href=t,document.head.appendChild(e)}static preconnect(t,e){const i=document.createElement("link");i.rel="preconnect",i.href=t,e&&(i.crossOrigin="anonymous"),document.head.appendChild(i)}static warmupConnection(t){this.dnsPrefetch(t),this.preconnect(t,!1),this.preconnect(t,!0)}static init(t,e){var i,a;try{this._serverPath=new URL(e.serverPath),this.isNewApiDomain(null===(i=this._serverPath)||void 0===i?void 0:i.hostname)&&this.warmupConnection(this._serverPath.origin),this._apiPaths=null!==(a=e.webauthnApiPaths)&&void 0!==a?a:this.getDefaultPaths(),this._clientId=t,yt.set("clientId",t)}catch(t){throw new tt("Invalid options.serverPath",{error:t})}}static getDefaultPaths(){var t;const e=this.isNewApiDomain(null===(t=this._serverPath)||void 0===t?void 0:t.hostname)?"/cis":"";return{startAuthentication:`${e}/v1/auth/webauthn/authenticate/start`,startRegistration:`${e}/v1/auth/webauthn/register/start`,initCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/init`,startCrossDeviceAuthentication:`${e}/v1/auth/webauthn/cross-device/authenticate/start`,startCrossDeviceRegistration:`${e}/v1/auth/webauthn/cross-device/register/start`,getCrossDeviceTicketStatus:`${e}/v1/auth/webauthn/cross-device/status`,attachDeviceToCrossDeviceSession:`${e}/v1/auth/webauthn/cross-device/attach-device`}}static getApiPaths(){return this._apiPaths}static async sendRequest(t,e,i){Z.log(`[WebAuthn SDK] Calling ${e.method} ${t}...`);const a=new URL(this._serverPath);return a.pathname=t,i&&(a.search=i),fetch(a.toString(),e)}static async startRegistration(t){const e=await this.sendRequest(this._apiPaths.startRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId(),username:t.username,display_name:t.displayName},t.timeout&&{timeout:t.timeout}),t.limitSingleCredentialToDevice&&{limit_single_credential_to_device:t.limitSingleCredentialToDevice}))});if(!(null==e?void 0:e.ok))throw new et("Failed to start registration",null==e?void 0:e.body);return await e.json()}static async startAuthentication(t){const e=await this.sendRequest(this._apiPaths.startAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}),t.timeout&&{timeout:t.timeout}))});if(!(null==e?void 0:e.ok))throw new et("Failed to start authentication",null==e?void 0:e.body);return await e.json()}static async initCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.initCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l(l({client_id:this.getValidatedClientId()},t.username&&{username:t.username}),t.approvalData&&{approval_data:t.approvalData}))});if(!(null==e?void 0:e.ok))throw new dt(void 0,null==e?void 0:e.body);return await e.json()}static async getCrossDeviceTicketStatus(t){const e=await this.sendRequest(this._apiPaths.getCrossDeviceTicketStatus,{method:"GET"},`cross_device_ticket_id=${t.ticketId}`);if(!(null==e?void 0:e.ok))throw new ut(void 0,null==e?void 0:e.body);return await e.json()}static async startCrossDeviceAuthentication(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceAuthentication,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new et("Failed to start cross device authentication",null==e?void 0:e.body);return await e.json()}static async startCrossDeviceRegistration(t){const e=await this.sendRequest(this._apiPaths.startCrossDeviceRegistration,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new at("Failed to start cross device registration",null==e?void 0:e.body);return await e.json()}static async attachDeviceToCrossDeviceSession(t){const e=await this.sendRequest(this._apiPaths.attachDeviceToCrossDeviceSession,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cross_device_ticket_id:t.ticketId})});if(!(null==e?void 0:e.ok))throw new at("Failed to attach device to cross device session",null==e?void 0:e.body);return await e.json()}static getValidatedClientId(){var t;const e=null!==(t=this._clientId)&&void 0!==t?t:yt.get("clientId");if(!e)throw new tt("Missing clientId");return e}}var gt,vt,wt,ft;pt.newApiDomains=["api.idsec-dev.com","api.idsec-stg.com"],function(t){t.InputAutofill="input-autofill",t.Modal="modal"}(gt||(gt={})),function(t){t.Pending="pending",t.Scanned="scanned",t.Success="success",t.Error="error",t.Timeout="timeout",t.Aborted="aborted"}(vt||(vt={})),function(t){t.toAuthenticationError=t=>ht(t)?t:"NotAllowedError"===t.name?new it:"OperationError"===t.name?new ct(t.message):"SecurityError"===t.name?new et(t.message):t===X.AuthenticationAbortedTimeout?new rt:"AbortError"===t.name||t===X.AutofillAuthenticationAborted?new st:new et("Something went wrong during authentication",{error:t}),t.toRegistrationError=t=>ht(t)?t:"NotAllowedError"===t.name?new nt:"SecurityError"===t.name?new at(t.message):"InvalidStateError"===t.name?new ot:t===X.RegistrationAbortedTimeout?new rt:new at("Something went wrong during registration",{error:t})}(wt||(wt={})),function(t){t.processCredentialRequestOptions=t=>l(l({},t),{},{challenge:W.base64ToArrayBuffer(t.challenge),allowCredentials:t.allowCredentials.map((t=>l(l({},t),{},{id:W.base64ToArrayBuffer(t.id)})))}),t.processCredentialCreationOptions=(t,e)=>{var i;const a=JSON.parse(JSON.stringify(t));return a.challenge=W.base64ToArrayBuffer(t.challenge),a.user.id=W.base64ToArrayBuffer(t.user.id),(null==e?void 0:e.limitSingleCredentialToDevice)&&(a.excludeCredentials=null===(i=t.excludeCredentials)||void 0===i?void 0:i.map((t=>l(l({},t),{},{id:W.base64ToArrayBuffer(t.id)})))),(null==e?void 0:e.registerAsDiscoverable)?(a.authenticatorSelection.residentKey="preferred",a.authenticatorSelection.requireResidentKey=!0):(a.authenticatorSelection.residentKey="discouraged",a.authenticatorSelection.requireResidentKey=!1),a.authenticatorSelection.authenticatorAttachment=(null==e?void 0:e.allowCrossPlatformAuthenticators)?void 0:"platform",a},t.encodeAuthenticationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:W.arrayBufferToBase64(t.rawId),response:{authenticatorData:W.arrayBufferToBase64(i.authenticatorData),clientDataJSON:W.arrayBufferToBase64(i.clientDataJSON),signature:W.arrayBufferToBase64(i.signature),userHandle:W.arrayBufferToBase64(i.userHandle)},authenticatorAttachment:e,type:t.type}},t.encodeRegistrationResult=t=>{const{authenticatorAttachment:e}=t,i=t.response;return{id:t.id,rawId:W.arrayBufferToBase64(t.rawId),response:{attestationObject:W.arrayBufferToBase64(i.attestationObject),clientDataJSON:W.arrayBufferToBase64(i.clientDataJSON)},authenticatorAttachment:e,type:t.type}}}(ft||(ft={}));class mt{async modal(t){try{const e=await this.performAuthentication(l(l({},t),{},{mediationType:gt.Modal}));return W.jsonToBase64(e)}catch(t){throw wt.toAuthenticationError(t)}}activateAutofill(t,e){const{onSuccess:i,onError:a,onReady:n}=t;this.performAuthentication({username:e,mediationType:gt.InputAutofill,onReady:n}).then((t=>{i(W.jsonToBase64(t))})).catch((t=>{const e=wt.toAuthenticationError(t);if(!a)throw e;a(e)}))}abortAutofill(){this.abortController&&this.abortController.abort(X.AutofillAuthenticationAborted)}abortAuthentication(){this.abortController&&this.abortController.abort(X.AuthenticationAbortedTimeout)}async performAuthentication(t){var e,i;const a="crossDeviceTicketId"in t?await pt.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await pt.startAuthentication({username:t.username,timeout:null===(e=t.options)||void 0===e?void 0:e.timeout}),n=a.credential_request_options,s=ft.processCredentialRequestOptions(n),r=this.getMediatedCredentialRequest(s,t.mediationType);t.mediationType===gt.InputAutofill&&(null===(i=t.onReady)||void 0===i||i.call(t));const o=await navigator.credentials.get(r).catch((t=>{throw wt.toAuthenticationError(t)}));return{webauthnSessionId:a.webauthn_session_id,publicKeyCredential:ft.encodeAuthenticationResult(o),userAgent:navigator.userAgent}}getMediatedCredentialRequest(t,e){const i={publicKey:t};return this.abortController=new AbortController,i.signal=this.abortController&&this.abortController.signal,e===gt.InputAutofill?i.mediation="conditional":t.timeout&&setTimeout((()=>{this.abortAuthentication()}),t.timeout),i}}class bt{constructor(t,e){this.handler=t,this.intervalInMs=e}begin(){var t;this.intervalId=window.setInterval((t=this.handler,async function(){t.isRunning||(t.isRunning=!0,await t(...arguments),t.isRunning=!1)}),this.intervalInMs)}stop(){clearInterval(this.intervalId)}}const Dt=/^[A-Za-z0-9\-_.: ]*$/;function At(t){if(t&&(!function(t){return Object.keys(t).length<=10}(t)||!function(t){const e=t=>"string"==typeof t,i=t=>Dt.test(t);return Object.keys(t).every((a=>e(a)&&e(t[a])&&i(a)&&i(t[a])))}(t)))throw Z.error("Failed validating approval data"),new lt("Provided approval data should have 10 properties max. Also, it should contain only \n alphanumeric characters, numbers, and the special characters: '-', '_', '.'")}class _t{constructor(t,e,i){this.authenticationHandler=t,this.registrationHandler=e,this.approvalHandler=i,this.init={registration:async t=>(this.ticketStatus=vt.Pending,this.pollCrossDeviceSession(t.crossDeviceTicketId,t.handlers)),authentication:async t=>{const{username:e}=t,i=(await pt.initCrossDeviceAuthentication(l({},e&&{username:e}))).cross_device_ticket_id;return this.ticketStatus=vt.Pending,this.pollCrossDeviceSession(i,t.handlers)},approval:async t=>{const{username:e,approvalData:i}=t;At(i);const a=(await pt.initCrossDeviceAuthentication({username:e,approvalData:i})).cross_device_ticket_id;return this.ticketStatus=vt.Pending,this.pollCrossDeviceSession(a,t.handlers)}},this.authenticate={modal:async t=>this.authenticationHandler.modal({crossDeviceTicketId:t})},this.approve={modal:async t=>this.approvalHandler.modal({crossDeviceTicketId:t})}}async register(t,e){return this.registrationHandler.register({crossDeviceTicketId:t},e)}async attachDevice(t){const e=await pt.attachDeviceToCrossDeviceSession({ticketId:t});return l({status:e.status,startedAt:e.started_at},e.approval_data&&{approvalData:e.approval_data})}async pollCrossDeviceSession(t,e){return this.poller=new bt((async()=>{var i,a;const n=await pt.getCrossDeviceTicketStatus({ticketId:t}),s=n.status;if(s!==this.ticketStatus)switch(this.ticketStatus=s,s){case vt.Scanned:await e.onDeviceAttach();break;case vt.Error:case vt.Timeout:case vt.Aborted:await e.onFailure(n),null===(i=this.poller)||void 0===i||i.stop();break;case vt.Success:if("onCredentialRegister"in e)await e.onCredentialRegister();else{if(!n.session_id)throw new ut("Cross device session is complete without returning session_id",n);await e.onCredentialAuthenticate(n.session_id)}null===(a=this.poller)||void 0===a||a.stop()}}),1e3),this.poller.begin(),setTimeout((()=>{var t;null===(t=this.poller)||void 0===t||t.stop(),e.onFailure({status:vt.Timeout})}),3e5),{crossDeviceTicketId:t,stop:()=>{var t;null===(t=this.poller)||void 0===t||t.stop()}}}}class St{async register(t,e){this.abortController=new AbortController;const i=l({allowCrossPlatformAuthenticators:!("crossDeviceTicketId"in t),registerAsDiscoverable:!0},e);try{const a="crossDeviceTicketId"in t?await pt.startCrossDeviceRegistration({ticketId:t.crossDeviceTicketId}):await pt.startRegistration({username:t.username,displayName:(null==e?void 0:e.displayName)||t.username,timeout:null==e?void 0:e.timeout,limitSingleCredentialToDevice:null==e?void 0:e.limitSingleCredentialToDevice}),n=ft.processCredentialCreationOptions(a.credential_creation_options,i);setTimeout((()=>{this.abortRegistration()}),n.timeout);const s=await this.registerCredential(n),r={webauthnSessionId:a.webauthn_session_id,publicKeyCredential:s,userAgent:navigator.userAgent};return W.jsonToBase64(r)}catch(t){throw wt.toRegistrationError(t)}}abortRegistration(){this.abortController&&this.abortController.abort(X.RegistrationAbortedTimeout)}async registerCredential(t){const e=await navigator.credentials.create({publicKey:t,signal:this.abortController&&this.abortController.signal}).catch((t=>{throw wt.toRegistrationError(t)}));return ft.encodeRegistrationResult(e)}}class Ct{async modal(t){try{const e=await this.performApproval(t);return W.jsonToBase64(e)}catch(t){throw wt.toAuthenticationError(t)}}async performApproval(t){"approvalData"in t&&At(t.approvalData);const e="crossDeviceTicketId"in t?await pt.startCrossDeviceAuthentication({ticketId:t.crossDeviceTicketId}):await pt.startAuthentication({username:t.username,approvalData:t.approvalData}),i=e.credential_request_options,a=ft.processCredentialRequestOptions(i),n=await navigator.credentials.get({publicKey:a}).catch((t=>{throw wt.toAuthenticationError(t)}));return{webauthnSessionId:e.webauthn_session_id,publicKeyCredential:ft.encodeAuthenticationResult(n),userAgent:navigator.userAgent}}}class Kt{constructor(){this._initialized=!1,this._authenticationHandler=new mt,this._registrationHandler=new St,this._approvalHandler=new Ct,this._crossDeviceHandler=new _t(this._authenticationHandler,this._registrationHandler,this._approvalHandler),this.authenticate={modal:async(t,e)=>(this.initCheck(),this._authenticationHandler.modal({username:t,options:e})),autofill:{activate:(t,e)=>(this.initCheck(),this._authenticationHandler.activateAutofill(t,e)),abort:()=>this._authenticationHandler.abortAutofill()}},this.approve={modal:async(t,e)=>(this.initCheck(),this._approvalHandler.modal({username:t,approvalData:e}))},this.register=async(t,e)=>(this.initCheck(),this._registrationHandler.register({username:t},e)),this.crossDevice={init:{registration:async t=>(this.initCheck(),this._crossDeviceHandler.init.registration(t)),authentication:async t=>(this.initCheck(),this._crossDeviceHandler.init.authentication(t)),approval:async t=>(this.initCheck(),this._crossDeviceHandler.init.approval(t))},authenticate:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.authenticate.modal(t))},approve:{modal:async t=>(this.initCheck(),this._crossDeviceHandler.approve.modal(t))},register:async(t,e)=>(this.initCheck(),this._crossDeviceHandler.register(t,e)),attachDevice:async t=>(this.initCheck(),this._crossDeviceHandler.attachDevice(t))},this.isPlatformAuthenticatorSupported=async()=>{var t;try{return await(null===(t=Kt.StaticPublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable())}catch(t){return!1}},this.isAutofillSupported=async()=>{var t,e;return!(!(null===(t=Kt.StaticPublicKeyCredential)||void 0===t?void 0:t.isConditionalMediationAvailable)||!await(null===(e=Kt.StaticPublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable()))}}async init(t,e){try{if(!t)throw new tt("Invalid clientId",{clientId:t});if(e.webauthnApiPaths){const t=pt.getDefaultPaths();if(function(t,e){const i=new Set(t),a=new Set(e);return[...t.filter((t=>!a.has(t))),...e.filter((t=>!i.has(t)))]}(Object.keys(e.webauthnApiPaths),Object.keys(t)).length)throw new tt("Invalid custom paths",{customApiPaths:e.webauthnApiPaths})}pt.init(t,e),this._initialized=!0}catch(t){throw ht(t)?t:new tt("Failed to initialize SDK")}}getDefaultPaths(){return this.initCheck(),pt.getDefaultPaths()}getApiPaths(){return this.initCheck(),pt.getApiPaths()}initCheck(){if(!this._initialized)throw new tt}}Kt.StaticPublicKeyCredential=window.PublicKeyCredential;const kt=new G("webauthn"),Rt=new Kt;kt.events.on(kt.events.MODULE_INITIALIZED,(()=>{var t;const e=kt.moduleMetadata.getInitConfig();if(!(null===(t=null==e?void 0:e.webauthn)||void 0===t?void 0:t.serverPath))return;const{clientId:i,webauthn:a}=e;Rt.init(i,l({},a))}));const Pt={modal:async(t,e)=>(Rt.initCheck(),Rt.authenticate.modal(t,e)),autofill:{activate:(t,e)=>{Rt.initCheck(),Rt.authenticate.autofill.activate(t,e)},abort:()=>{Rt.initCheck(),Rt.authenticate.autofill.abort()}}},Tt={modal:async(t,e)=>(Rt.initCheck(),Rt.approve.modal(t,e))};async function It(t,e){return Rt.initCheck(),Rt.register(t,e)}const{crossDevice:Ot}=Rt,{isPlatformAuthenticatorSupported:jt}=Rt,{isAutofillSupported:xt}=Rt,{getDefaultPaths:Bt}=Rt;window.localWebAuthnSDK=Rt;const Nt="1.16.0",Et={initialize:r,...Object.freeze({__proto__:null,get WebauthnCrossDeviceStatus(){return vt},approve:Tt,authenticate:Pt,crossDevice:Ot,getDefaultPaths:Bt,isAutofillSupported:xt,isPlatformAuthenticatorSupported:jt,register:It})};export{Nt as PACKAGE_VERSION,vt as WebauthnCrossDeviceStatus,Tt as approve,Pt as authenticate,Ot as crossDevice,Bt as getDefaultPaths,r as initialize,xt as isAutofillSupported,jt as isPlatformAuthenticatorSupported,It as register,Et as webauthn};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@transmitsecurity/platform-web-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"private": false,
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -68,7 +68,9 @@
|
|
|
68
68
|
"prebuild": "yarn tsc -p ./src",
|
|
69
69
|
"build": "web-sdk-bundler \"`cat bundler-config.json`\"",
|
|
70
70
|
"prepare": "yarn build",
|
|
71
|
-
"distribute": "
|
|
71
|
+
"distribute": "platform_sdk_cdn=platform-websdk.idsec-dev.com yarn distribute:env",
|
|
72
|
+
"promote-latest:env": "./scripts/make-semver-aliases.sh",
|
|
73
|
+
"distribute:env": "./scripts/upload-dist.sh",
|
|
72
74
|
"publish:npm": "npm publish --access public"
|
|
73
75
|
},
|
|
74
76
|
"devDependencies": {
|
|
@@ -76,10 +78,10 @@
|
|
|
76
78
|
"@transmit-security/web-sdk-bundler": "0.1.14",
|
|
77
79
|
"@types/node": "20.3.3",
|
|
78
80
|
"@transmit-security/authentication-sdk": "4.12.0",
|
|
79
|
-
"@transmit-security/ido-web-sdk": "0.0.
|
|
80
|
-
"@transmit-security/riskid_sdk": "1.
|
|
81
|
+
"@transmit-security/ido-web-sdk": "0.0.73",
|
|
82
|
+
"@transmit-security/riskid_sdk": "1.52.0",
|
|
81
83
|
"@transmit-security/ts-identity-verification": "1.4.8",
|
|
82
|
-
"@transmit-security/web-sdk-common": "1.
|
|
84
|
+
"@transmit-security/web-sdk-common": "1.2.0",
|
|
83
85
|
"vite": "^5.0.0"
|
|
84
86
|
},
|
|
85
87
|
"engines": {
|
|
@@ -93,6 +95,5 @@
|
|
|
93
95
|
"security",
|
|
94
96
|
"identity"
|
|
95
97
|
],
|
|
96
|
-
"description": "Transmit Security Web SDK - Browser-only authentication and identity verification"
|
|
97
|
-
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
|
|
98
|
+
"description": "Transmit Security Web SDK - Browser-only authentication and identity verification"
|
|
98
99
|
}
|
package/scripts/upload-dist.sh
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
2
|
|
|
3
|
+
# Set default CDN bucket if not provided
|
|
4
|
+
platform_sdk_cdn=${platform_sdk_cdn:-"platform-websdk.idsec-dev.com"}
|
|
5
|
+
|
|
3
6
|
cdn_dir=gs://$platform_sdk_cdn/platform-websdk/$npm_package_version
|
|
4
7
|
|
|
5
8
|
gsutil cp dist/web-sdk-*.js $cdn_dir/ts-platform-websdk.js
|
package/VITE_CONFIG.md
DELETED
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
# Vite Configuration for Platform Web SDK
|
|
2
|
-
|
|
3
|
-
If you encounter dependency resolution errors when using this SDK with Vite, follow these solutions:
|
|
4
|
-
|
|
5
|
-
## Solution 1: Exclude from Dependency Optimization (Required)
|
|
6
|
-
|
|
7
|
-
Add this to your `vite.config.js`:
|
|
8
|
-
|
|
9
|
-
```js
|
|
10
|
-
import { defineConfig } from 'vite'
|
|
11
|
-
|
|
12
|
-
export default defineConfig({
|
|
13
|
-
optimizeDeps: {
|
|
14
|
-
exclude: [
|
|
15
|
-
'@transmitsecurity/platform-web-sdk',
|
|
16
|
-
'@transmitsecurity/platform-web-sdk/drs',
|
|
17
|
-
'@transmitsecurity/platform-web-sdk/webauthn',
|
|
18
|
-
'@transmitsecurity/platform-web-sdk/idv',
|
|
19
|
-
'@transmitsecurity/platform-web-sdk/ido'
|
|
20
|
-
]
|
|
21
|
-
},
|
|
22
|
-
build: {
|
|
23
|
-
rollupOptions: {
|
|
24
|
-
external: [
|
|
25
|
-
'@transmit-security/web-sdk-common',
|
|
26
|
-
'@transmit-security/riskid_sdk',
|
|
27
|
-
'@transmit-security/authentication-sdk',
|
|
28
|
-
'@transmit-security/ts-identity-verification',
|
|
29
|
-
'@transmit-security/ido-web-sdk'
|
|
30
|
-
]
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
})
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
## Solution 2: Use Full SDK Import (Recommended)
|
|
37
|
-
|
|
38
|
-
**❌ Avoid individual module imports for now:**
|
|
39
|
-
```js
|
|
40
|
-
// This causes dependency resolution errors
|
|
41
|
-
import { drs, initialize } from '@transmitsecurity/platform-web-sdk/drs';
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
**✅ Use full SDK import instead:**
|
|
45
|
-
```js
|
|
46
|
-
// This works reliably
|
|
47
|
-
import { drs, webauthn, initialize } from '@transmitsecurity/platform-web-sdk';
|
|
48
|
-
|
|
49
|
-
await initialize({
|
|
50
|
-
clientId: 'your-client-id',
|
|
51
|
-
drs: { serverPath: 'https://api.transmitsecurity.io/risk-collect/' },
|
|
52
|
-
webauthn: { serverPath: 'https://api.transmitsecurity.io' }
|
|
53
|
-
});
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
## Solution 3: Alternative Vite Configuration
|
|
57
|
-
|
|
58
|
-
If you still want to try individual imports, add this more comprehensive configuration:
|
|
59
|
-
|
|
60
|
-
```js
|
|
61
|
-
import { defineConfig } from 'vite'
|
|
62
|
-
|
|
63
|
-
export default defineConfig({
|
|
64
|
-
optimizeDeps: {
|
|
65
|
-
exclude: [
|
|
66
|
-
'@transmitsecurity/platform-web-sdk',
|
|
67
|
-
'@transmitsecurity/platform-web-sdk/drs',
|
|
68
|
-
'@transmitsecurity/platform-web-sdk/webauthn',
|
|
69
|
-
'@transmitsecurity/platform-web-sdk/idv',
|
|
70
|
-
'@transmitsecurity/platform-web-sdk/ido'
|
|
71
|
-
],
|
|
72
|
-
include: []
|
|
73
|
-
},
|
|
74
|
-
define: {
|
|
75
|
-
global: 'globalThis',
|
|
76
|
-
},
|
|
77
|
-
resolve: {
|
|
78
|
-
alias: {
|
|
79
|
-
// Fallback for missing dependencies
|
|
80
|
-
'@transmit-security/web-sdk-common': '@transmitsecurity/platform-web-sdk',
|
|
81
|
-
'@transmit-security/riskid_sdk': '@transmitsecurity/platform-web-sdk',
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
})
|
|
85
|
-
```
|
|
86
|
-
|
|
87
|
-
## Solution 4: Clear Vite Cache
|
|
88
|
-
|
|
89
|
-
Always clear the Vite cache when switching configurations:
|
|
90
|
-
|
|
91
|
-
```bash
|
|
92
|
-
rm -rf node_modules/.vite
|
|
93
|
-
npm run dev
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
## Current Limitation
|
|
97
|
-
|
|
98
|
-
**Individual module imports are currently not fully supported** due to dependency bundling architecture.
|
|
99
|
-
|
|
100
|
-
**Recommended approach**: Use the full SDK import until the build system is updated to create truly self-contained modules.
|
|
101
|
-
|
|
102
|
-
## Bundle Size Impact
|
|
103
|
-
|
|
104
|
-
Even with full SDK import, the bundle is optimized:
|
|
105
|
-
- **Gzipped size**: ~180KB
|
|
106
|
-
- **Uncompressed**: ~565KB
|
|
107
|
-
- **Tree-shaking**: Unused functions are still eliminated by modern bundlers
|