@loginid/websdk3 3.3.1 → 3.4.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/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ee=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var r in t)ee(e,r,{get:t[r],enumerable:!0})},tt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qe(t))!Ze.call(e,o)&&o!==r&&ee(e,o,{get:()=>t[o],enumerable:!(s=Xe(t,o))||s.enumerable});return e};var rt=e=>tt(ee({},"__esModule",{value:!0}),e);var Ot={};et(Ot,{AbortError:()=>N,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>R,createPasskeyCredential:()=>$,default:()=>Tt,getPasskeyCredential:()=>V,isConditionalUIAvailable:()=>j,isPlatformAuthenticatorAvailable:()=>M});module.exports=rt(Ot);var I=async e=>{let t=JSON.stringify(await Ae()),r=await Ie(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},M=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},j=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Ae=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await M(),t=await j();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},Ie=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},K=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},te=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var N=class extends Error{constructor(e){super(e),this.name="AbortError"}},y=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},h=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var D=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Te=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=B(t);return D(s)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Te(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},re=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},W=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),v=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),se=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(s)},Oe=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},F=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Oe(24);var E=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new N("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},ve=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new h("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new h("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new h("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new h("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Ee=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new h("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new h("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},st=new y("User needs to be logged in to perform this operation."),oe=new y("No login options available."),$=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:O(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:O(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?ve(o,s):o}},V=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:O(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ee(o,s):o}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?E.assignWebAuthnAbortController(t.abortController):(E.renewWebAuthnAbortController(),t.abortController=E.abortController);let o=await V(r,t),a=o.response;return{assertionResult:{authenticatorData:k(a.authenticatorData),clientDataJSON:k(a.clientDataJSON),credentialId:o.id,signature:k(a.signature),...a.userHandle&&{userHandle:k(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;E.renewWebAuthnAbortController();let s=await $(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:k(o.attestationObject),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:k(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var U=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},J=(e,t,r)=>(r||(r=re()),{id:r,username:t,aud:e}),S=async(e,t,r)=>{let s=D(B(JSON.stringify({alg:"ES256",jwk:t}))),o=D(B(JSON.stringify(e))),a=`${s}.${o}`,i=await se(r,a);return`${a}.${i}`};var ne=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var Se=e=>`LoginID_${e}_device-id`,w=class extends ne{static persistDeviceId(e,t){this.setItem(Se(e),t)}static getDeviceId(e){return this.getItem(Se(e))||""}},ue=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new c("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var at="lid_c_wtid",it="lid-wtid-k",qe=class extends ue{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await W(),t=await v(e),r={id:F()},s=await S(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new c("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new c("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var le=class extends qe{constructor(){super(at,it)}},nt=1,Ce="app_id_idx",ut="username_idx",lt="loginid-trust-store",dt="LoginID_trust-id",ae="app_id_username_idx",q=class extends ue{appId;constructor(e){super(lt,nt,dt,[{name:ut,keyPath:["username"]},{name:Ce,keyPath:["appId"]},{name:ae,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await W(),r=await v(t),s=J(this.appId,e),o=await S(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(ae,[this.appId,e]),r=await v(t.keyPair),s=J(this.appId,e,t.id);return await S(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof c&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ce,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ae,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Pe=e=>`LoginID_${e}_mfa-session`,m=class ie extends ne{static persistInfo(t,r){this.setItem(Pe(t),r)}static getInfo(t){return this.getItem(Pe(t))}static updateSession(t,r){let s=ie.getInfo(t);s?s.session=r:s={session:r},ie.persistInfo(t,s)}};var xe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},_e=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Ne=class{constructor(e){this.config=e}},De=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Be=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new De("Request aborted"))}}get isCancelled(){return this.#e}},A=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},ce=e=>e!=null,z=e=>typeof e=="string",de=e=>z(e)&&e!=="",pe=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof FormData,ct=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},pt=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{ce(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},ht=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${pt(t.query)}`:o},yt=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{z(o)||pe(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>ce(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},G=async(e,t)=>typeof t=="function"?t(e):t,mt=async(e,t)=>{let[r,s,o,a]=await Promise.all([G(t,e.TOKEN),G(t,e.USERNAME),G(t,e.PASSWORD),G(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>ce(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(de(r)&&(i.Authorization=`Bearer ${r}`),de(s)&&de(o)){let n=ct(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:pe(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":z(t.body)?i["Content-Type"]="text/plain":Fe(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ft=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):z(e.body)||pe(e.body)||Fe(e.body)?e.body:JSON.stringify(e.body)},gt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},kt=(e,t)=>{if(t){let r=e.headers.get(t);if(z(r))return r}},Rt=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},bt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new A(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new A(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},wt=(e,t)=>new Be(async(r,s,o)=>{try{let a=ht(e,t),i=yt(t),n=ft(t),u=await mt(e,t);if(!o.isCancelled){let l=await gt(e,t,a,n,i,u,o),d=await Rt(l),p=kt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};bt(t,g),r(g.body)}}catch(a){s(a)}}),At=class extends Ne{constructor(e){super(e)}request(e){return wt(this.config,e)}},Ue=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Le=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},Me=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},he=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=At){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Ue(this.request),this.clientEvents=new xe(this.request),this.mfa=new ze(this.request),this.passkeys=new _e(this.request),this.reg=new Le(this.request),this.tx=new Me(this.request)}};var je=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ye=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),x=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(d=>(a==="otp:sms"||a==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let d=o.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],s=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var H=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},fe=class me{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new y("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new y("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new y(`No matching factor found for ${t}.`);let u=(l,d)=>{if(!l.options?.length)throw new y(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(d?p=l.options.find(g=>g.name===d)?.label:p=l.options[0]?.label,!p)throw new y(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new y("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new y("Payload is required for passkeys.");let r=b("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(me.isPublicKeyCredentialCreationOptions(r)||me.isPublicKeyCredentialRequestOptions(r))return r;throw new y("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Ke=class{config;constructor(e){this.config=new H(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=b(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=b(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;te(s)}getJwtCookie(){return K(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){T(this.getJwtCookieName()),T(this.getIdTokenName()),T(this.getAccessTokenName()),T(this.getRefreshTokenName()),T(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=b(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return K(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new H(e),this.service=new he({BASE:e.baseUrl}),this.session=new Ke(e)}},L=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await I(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof A&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},It=new Set(["ERROR_PASSKEY_ABORTED"]),Y=class extends f{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof h){if(It.has(t.code))return{session:""};let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},ge=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await I(s),a=je(e,t),i="";t.txPayload&&(i=await new le().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new q(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),d=ye(l,e);return m.persistInfo(r,d),this.session.logout(),x(d)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=fe.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=fe.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),x(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return x(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return x(a,s)}catch(s){if(s instanceof A&&s.status===401&&s.body.session){let o=s.body,a=ye(o,t);return m.persistInfo(e,a),x(a)}if(s instanceof Error){let o=new Y(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var We=class extends f{constructor(e){super(e)}};U(We,[f,ge,L]);var $e=We;var ke=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ve=ke;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Je=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||F()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var Ge=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Re=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return E.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},X=Re;var be=class extends X{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await I(a),n=new q(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:d,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await R.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let Z=await this.service.reg.regRegComplete({requestBody:g}),Ye=_(Z);return this.session.setJwtCookie(Z.jwtAccess),w.persistDeviceId(o,a||Z.deviceId),Ye})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await I(w.getDeviceId(s)),a=new q(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let d=await R.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:d}),g=_(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=Ge(l);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw oe}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=Je(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await R.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:d})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new Y(this.config.getConfig()).reportError(t,s),s}}},He=be;var Q=class extends f{constructor(t){super(t)}};U(Q,[f,He,X,Ve,L]);var we=Q;var Tt=we;0&&(module.exports={AbortError,ApiError,LoginIDMfa,LoginIDWebSDK,PasskeyError,WebAuthnHelper,createPasskeyCredential,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
1
+ "use strict";var ee=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var r in t)ee(e,r,{get:t[r],enumerable:!0})},tt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qe(t))!Ze.call(e,o)&&o!==r&&ee(e,o,{get:()=>t[o],enumerable:!(s=Xe(t,o))||s.enumerable});return e};var rt=e=>tt(ee({},"__esModule",{value:!0}),e);var Ot={};et(Ot,{AbortError:()=>D,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>k,createPasskeyCredential:()=>V,default:()=>Tt,getPasskeyCredential:()=>J,isConditionalUIAvailable:()=>j,isPlatformAuthenticatorAvailable:()=>L});module.exports=rt(Ot);var I=async e=>{let t=JSON.stringify(await Ae()),r=await Ie(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},L=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},j=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Ae=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await L(),t=await j();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},Ie=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},K=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},te=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var y=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},h=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},d=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}},D=class extends Error{constructor(e){super(e),this.name="AbortError"}};var B=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),F=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Te=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},R=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=F(t);return B(s)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Te(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},re=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},W=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),v=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),se=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return R(s)},Oe=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},$=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Oe(24);var E=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new D("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},ve=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new h("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new h("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new h("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new h("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Ee=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new h("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new h("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},st=new y("User needs to be logged in to perform this operation."),oe=new y("No login options available."),V=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:O(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:O(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?ve(o,s):o}},J=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:O(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ee(o,s):o}},k=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?E.assignWebAuthnAbortController(t.abortController):(E.renewWebAuthnAbortController(),t.abortController=E.abortController);let o=await J(r,t),a=o.response;return{assertionResult:{authenticatorData:R(a.authenticatorData),clientDataJSON:R(a.clientDataJSON),credentialId:o.id,signature:R(a.signature),...a.userHandle&&{userHandle:R(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;E.renewWebAuthnAbortController();let s=await V(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:R(o.attestationObject),clientDataJSON:R(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:R(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:R(n)},...u&&{transports:u}},session:r}}};var U=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},q=e=>(e||(e=re()),{id:e,exp:Math.floor(Date.now()/1e3)+60}),S=async(e,t,r)=>{let s=B(F(JSON.stringify({alg:"ES256",jwk:t}))),o=B(F(JSON.stringify(e))),a=`${s}.${o}`,i=await se(r,a);return`${a}.${i}`};var ne=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var Se=e=>`LoginID_${e}_device-id`,w=class extends ne{static persistDeviceId(e,t){this.setItem(Se(e),t)}static getDeviceId(e){return this.getItem(Se(e))||""}},ue=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new d(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new d(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new d(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new d("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new d("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new d("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new d("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var at="lid_c_wtid",it="lid-wtid-k",qe=class extends ue{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await W(),t=await v(e),r=q(),s=await S(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await v(e.keyPair),r=q(e.id);return await S(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new d("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new d("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var le=class extends qe{constructor(){super(at,it)}},nt=1,Ce="app_id_idx",ut="username_idx",lt="loginid-trust-store",ct="LoginID_trust-id",ae="app_id_username_idx",x=class extends ue{appId;constructor(e){super(lt,nt,ct,[{name:ut,keyPath:["username"]},{name:Ce,keyPath:["appId"]},{name:ae,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await W(),r=await v(t),s=q(),o=await S(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(ae,[this.appId,e]),r=await v(t.keyPair),s=q(t.id);return await S(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof d&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ce,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ae,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Pe=e=>`LoginID_${e}_mfa-session`,m=class ie extends ne{static persistInfo(t,r){this.setItem(Pe(t),r)}static getInfo(t){return this.getItem(Pe(t))}static updateSession(t,r){let s=ie.getInfo(t);s?s.session=r:s={session:r},ie.persistInfo(t,s)}};var xe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},_e=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Ne=class{constructor(e){this.config=e}},De=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Be=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new De("Request aborted"))}}get isCancelled(){return this.#e}},A=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},de=e=>e!=null,z=e=>typeof e=="string",ce=e=>z(e)&&e!=="",pe=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof FormData,dt=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},pt=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{de(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},ht=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${pt(t.query)}`:o},yt=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{z(o)||pe(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>de(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},G=async(e,t)=>typeof t=="function"?t(e):t,mt=async(e,t)=>{let[r,s,o,a]=await Promise.all([G(t,e.TOKEN),G(t,e.USERNAME),G(t,e.PASSWORD),G(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>de(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(ce(r)&&(i.Authorization=`Bearer ${r}`),ce(s)&&ce(o)){let n=dt(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:pe(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":z(t.body)?i["Content-Type"]="text/plain":Fe(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ft=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):z(e.body)||pe(e.body)||Fe(e.body)?e.body:JSON.stringify(e.body)},gt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},Rt=(e,t)=>{if(t){let r=e.headers.get(t);if(z(r))return r}},kt=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},bt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new A(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new A(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},wt=(e,t)=>new Be(async(r,s,o)=>{try{let a=ht(e,t),i=yt(t),n=ft(t),u=await mt(e,t);if(!o.isCancelled){let l=await gt(e,t,a,n,i,u,o),c=await kt(l),p=Rt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??c};bt(t,g),r(g.body)}}catch(a){s(a)}}),At=class extends Ne{constructor(e){super(e)}request(e){return wt(this.config,e)}},Ue=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Me=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},Le=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},he=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=At){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Ue(this.request),this.clientEvents=new xe(this.request),this.mfa=new ze(this.request),this.passkeys=new _e(this.request),this.reg=new Me(this.request),this.tx=new Le(this.request)}};var je=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ye=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),_=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(c=>(a==="otp:sms"||a==="otp:email")&&c.label).map(c=>c.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let c=o.options.find(p=>p.value);c&&(u.value=c.value)}}return u})||[],s=["passkey:reg","passkey:auth","passkey:tx","otp:sms","otp:email","external"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var H=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},fe=class me{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new y("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new y("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new y(`No matching factor found for ${t}.`);let u=(l,c)=>{if(!l.options?.length)throw new y(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(c?p=l.options.find(g=>g.name===c)?.label:p=l.options[0]?.label,!p)throw new y(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new y("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new y("Payload is required for passkeys.");let r=b("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(me.isPublicKeyCredentialCreationOptions(r)||me.isPublicKeyCredentialRequestOptions(r))return r;throw new y("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Ke=class{config;constructor(e){this.config=new H(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=b(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=b(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;te(s)}getJwtCookie(){return K(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){T(this.getJwtCookieName()),T(this.getIdTokenName()),T(this.getAccessTokenName()),T(this.getRefreshTokenName()),T(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=b(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return K(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new H(e),this.service=new he({BASE:e.baseUrl}),this.session=new Ke(e)}},M=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await I(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof A&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},It=new Set(["ERROR_PASSKEY_ABORTED"]),Y=class extends f{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof h){if(It.has(t.code))return{session:""};let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},ge=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await I(s),a=je(e,t),i="";t.txPayload&&(i=await new le().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new x(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload},...t.traceId&&{traceId:t.traceId}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),c=ye(l,e);return m.persistInfo(r,c),this.session.logout(),_(c)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=fe.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=fe.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await k.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await k.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),_(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return _(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return _(a,s)}catch(s){if(s instanceof A&&s.status===401&&s.body.session){let o=s.body,a=ye(o,t);return m.persistInfo(e,a),_(a)}if(s instanceof Error){let o=new Y(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var We=class extends f{constructor(e){super(e)}};U(We,[f,ge,M]);var $e=We;var Re=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ve=Re;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Je=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||$()}),N=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var Ge=e=>[...e.crossAuthMethods,...e.fallbackMethods];var ke=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=N(i);return E.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},X=ke;var be=class extends X{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await I(a),n=new x(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),c={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:c,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await k.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let Z=await this.service.reg.regRegComplete({requestBody:g}),Ye=N(Z);return this.session.setJwtCookie(Z.jwtAccess),w.persistDeviceId(o,a||Z.deviceId),Ye})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await I(w.getDeviceId(s)),a=new x(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let c=await k.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:c}),g=N(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=Ge(l);await i.callbacks.onFallback(t,p)}return N({userId:"",jwtAccess:""},!1,!0)}default:throw oe}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=Je(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await k.getNavigatorCredential(u),c={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:c})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new Y(this.config.getConfig()).reportError(t,s),s}}},He=be;var Q=class extends f{constructor(t){super(t)}};U(Q,[f,He,X,Ve,M]);var we=Q;var Tt=we;0&&(module.exports={AbortError,ApiError,LoginIDMfa,LoginIDWebSDK,PasskeyError,WebAuthnHelper,createPasskeyCredential,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.ts CHANGED
@@ -544,6 +544,15 @@ interface MfaBeginOptions {
544
544
  * enabling secure transaction confirmation without revealing end-user identity to the merchant.
545
545
  */
546
546
  checkoutId?: string;
547
+ /**
548
+ * A unique identifier used to trace and correlate all events associated with a single MFA interaction.
549
+ *
550
+ * This ID is useful for end-to-end observability, logging, and debugging across distributed systems.
551
+ * It can be generated by the client or left unset—if not provided, a secure random ID will be created automatically by LoginID.
552
+ *
553
+ * Example: `6957cf6e-a86c-44fb-b25a-bd97cb9ff830`
554
+ */
555
+ traceId?: string;
547
556
  }
548
557
  interface MfaPerformActionOptions {
549
558
  /**
@@ -1079,6 +1088,10 @@ type MfaBeginRequestBody = {
1079
1088
  * Payload to be signed
1080
1089
  */
1081
1090
  payload?: string;
1091
+ /**
1092
+ * A unique id for tracing all events associated with an interaction. A random ID will be generated by the system if not provided.
1093
+ */
1094
+ traceId?: string;
1082
1095
  /**
1083
1096
  * TrustIDs provided with the request
1084
1097
  */
@@ -1676,21 +1689,29 @@ export interface PasskeyManagementOptions {
1676
1689
  }
1677
1690
  /**
1678
1691
  * List passkeys options.
1692
+ *
1693
+ * @expand
1679
1694
  */
1680
1695
  export interface ListPasskeysOptions extends PasskeyManagementOptions {
1681
1696
  }
1682
1697
  /**
1683
1698
  * Rename passkeys options.
1699
+ *
1700
+ * @expand
1684
1701
  */
1685
1702
  export interface RenamePasskeyOptions extends PasskeyManagementOptions {
1686
1703
  }
1687
1704
  /**
1688
1705
  * Delete passkeys options.
1706
+ *
1707
+ * @expand
1689
1708
  */
1690
1709
  export interface DeletePasskeyOptions extends PasskeyManagementOptions {
1691
1710
  }
1692
1711
  /**
1693
1712
  * Authenticate with passkeys options.
1713
+ *
1714
+ * @expand
1694
1715
  */
1695
1716
  export interface AuthenticateWithPasskeysOptions extends MainPasskeyOptions {
1696
1717
  /**
@@ -1705,11 +1726,15 @@ export interface AuthenticateWithPasskeysOptions extends MainPasskeyOptions {
1705
1726
  }
1706
1727
  /**
1707
1728
  * Authenticate with passkey autofill options.
1729
+ *
1730
+ * @expand
1708
1731
  */
1709
1732
  export interface AuthenticateWithPasskeyAutofillOptions extends AuthenticateWithPasskeysOptions {
1710
1733
  }
1711
1734
  /**
1712
1735
  * Create passkeys options interface.
1736
+ *
1737
+ * @expand
1713
1738
  */
1714
1739
  export interface CreatePasskeyOptions extends MainPasskeyOptions {
1715
1740
  /**
@@ -1728,6 +1753,8 @@ export interface CreatePasskeyOptions extends MainPasskeyOptions {
1728
1753
  }
1729
1754
  /**
1730
1755
  * Confirm transaction options.
1756
+ *
1757
+ * @expand
1731
1758
  */
1732
1759
  export interface ConfirmTransactionOptions extends MainPasskeyOptions {
1733
1760
  /**
@@ -1741,6 +1768,8 @@ export interface ConfirmTransactionOptions extends MainPasskeyOptions {
1741
1768
  }
1742
1769
  /**
1743
1770
  * Request and send OTP options.
1771
+ *
1772
+ * @expand
1744
1773
  */
1745
1774
  export interface RequestAndSendOtpOptions {
1746
1775
  /**
@@ -1750,11 +1779,15 @@ export interface RequestAndSendOtpOptions {
1750
1779
  }
1751
1780
  /**
1752
1781
  * Request OTP options.
1782
+ *
1783
+ * @expand
1753
1784
  */
1754
1785
  export interface RequestOtpOptions extends AuthenticateWithPasskeyAutofillOptions {
1755
1786
  }
1756
1787
  /**
1757
1788
  * Validate OTP options.
1789
+ *
1790
+ * @expand
1758
1791
  */
1759
1792
  export interface ValidateOtpOptions extends RequestAndSendOtpOptions {
1760
1793
  }
@@ -2134,7 +2167,7 @@ declare class Passkeys extends OTP {
2134
2167
  * @param {AuthenticateWithPasskeyAutofillOptions} options Additional authentication options.
2135
2168
  * @returns {Promise<AuthResult>} Result of the passkey authentication operation.
2136
2169
  * @example
2137
- * * import { isConditionalUIAvailable, LoginIDWebSDK } from "@loginid/websdk3";
2170
+ * import { isConditionalUIAvailable, LoginIDWebSDK } from "@loginid/websdk3";
2138
2171
  *
2139
2172
  * // Obtain credentials from LoginID
2140
2173
  * const BASE_URL = process.env.BASE_URL;
@@ -2216,7 +2249,7 @@ declare class Passkeys extends OTP {
2216
2249
  * or changes to sensitive account information, ensuring that the transaction is being authorized
2217
2250
  * by the rightful owner of the passkey.
2218
2251
  *
2219
- * For a more detailed guide click [here](https://docs.loginid.io/scenarios/transaction-confirmation).
2252
+ * For a more detailed guide click [here](https://docs.loginid.io/user-scenario/authentication/step-up/transaction-confirmation/).
2220
2253
  *
2221
2254
  * @param {string} username The username of the user confirming the transaction.
2222
2255
  * @param {string} txPayload The transaction-specific payload, which could include details
@@ -1,2 +1,2 @@
1
- "use strict";var LoginID=(()=>{var ee=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var r in t)ee(e,r,{get:t[r],enumerable:!0})},tt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qe(t))!Ze.call(e,o)&&o!==r&&ee(e,o,{get:()=>t[o],enumerable:!(s=Xe(t,o))||s.enumerable});return e};var rt=e=>tt(ee({},"__esModule",{value:!0}),e);var Ot={};et(Ot,{AbortError:()=>N,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>R,createPasskeyCredential:()=>$,default:()=>Tt,getPasskeyCredential:()=>V,isConditionalUIAvailable:()=>j,isPlatformAuthenticatorAvailable:()=>M});var I=async e=>{let t=JSON.stringify(await Ae()),r=await Ie(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},M=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},j=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Ae=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await M(),t=await j();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},Ie=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},K=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},te=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var N=class extends Error{constructor(e){super(e),this.name="AbortError"}},y=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},h=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var D=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Te=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=B(t);return D(s)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Te(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},re=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},W=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),v=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),se=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(s)},Oe=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},F=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Oe(24);var E=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new N("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},ve=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new h("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new h("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new h("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new h("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Ee=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new h("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new h("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},st=new y("User needs to be logged in to perform this operation."),oe=new y("No login options available."),$=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:O(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:O(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?ve(o,s):o}},V=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:O(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ee(o,s):o}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?E.assignWebAuthnAbortController(t.abortController):(E.renewWebAuthnAbortController(),t.abortController=E.abortController);let o=await V(r,t),a=o.response;return{assertionResult:{authenticatorData:k(a.authenticatorData),clientDataJSON:k(a.clientDataJSON),credentialId:o.id,signature:k(a.signature),...a.userHandle&&{userHandle:k(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;E.renewWebAuthnAbortController();let s=await $(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:k(o.attestationObject),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:k(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var U=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},J=(e,t,r)=>(r||(r=re()),{id:r,username:t,aud:e}),S=async(e,t,r)=>{let s=D(B(JSON.stringify({alg:"ES256",jwk:t}))),o=D(B(JSON.stringify(e))),a=`${s}.${o}`,i=await se(r,a);return`${a}.${i}`};var ne=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var Se=e=>`LoginID_${e}_device-id`,w=class extends ne{static persistDeviceId(e,t){this.setItem(Se(e),t)}static getDeviceId(e){return this.getItem(Se(e))||""}},ue=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new c("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var at="lid_c_wtid",it="lid-wtid-k",qe=class extends ue{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await W(),t=await v(e),r={id:F()},s=await S(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new c("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new c("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var le=class extends qe{constructor(){super(at,it)}},nt=1,Ce="app_id_idx",ut="username_idx",lt="loginid-trust-store",dt="LoginID_trust-id",ae="app_id_username_idx",q=class extends ue{appId;constructor(e){super(lt,nt,dt,[{name:ut,keyPath:["username"]},{name:Ce,keyPath:["appId"]},{name:ae,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await W(),r=await v(t),s=J(this.appId,e),o=await S(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(ae,[this.appId,e]),r=await v(t.keyPair),s=J(this.appId,e,t.id);return await S(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof c&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ce,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ae,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Pe=e=>`LoginID_${e}_mfa-session`,m=class ie extends ne{static persistInfo(t,r){this.setItem(Pe(t),r)}static getInfo(t){return this.getItem(Pe(t))}static updateSession(t,r){let s=ie.getInfo(t);s?s.session=r:s={session:r},ie.persistInfo(t,s)}};var xe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},_e=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Ne=class{constructor(e){this.config=e}},De=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Be=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new De("Request aborted"))}}get isCancelled(){return this.#e}},A=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},ce=e=>e!=null,z=e=>typeof e=="string",de=e=>z(e)&&e!=="",pe=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof FormData,ct=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},pt=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{ce(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},ht=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${pt(t.query)}`:o},yt=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{z(o)||pe(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>ce(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},G=async(e,t)=>typeof t=="function"?t(e):t,mt=async(e,t)=>{let[r,s,o,a]=await Promise.all([G(t,e.TOKEN),G(t,e.USERNAME),G(t,e.PASSWORD),G(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>ce(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(de(r)&&(i.Authorization=`Bearer ${r}`),de(s)&&de(o)){let n=ct(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:pe(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":z(t.body)?i["Content-Type"]="text/plain":Fe(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ft=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):z(e.body)||pe(e.body)||Fe(e.body)?e.body:JSON.stringify(e.body)},gt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},kt=(e,t)=>{if(t){let r=e.headers.get(t);if(z(r))return r}},Rt=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},bt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new A(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new A(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},wt=(e,t)=>new Be(async(r,s,o)=>{try{let a=ht(e,t),i=yt(t),n=ft(t),u=await mt(e,t);if(!o.isCancelled){let l=await gt(e,t,a,n,i,u,o),d=await Rt(l),p=kt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};bt(t,g),r(g.body)}}catch(a){s(a)}}),At=class extends Ne{constructor(e){super(e)}request(e){return wt(this.config,e)}},Ue=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Le=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},Me=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},he=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=At){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Ue(this.request),this.clientEvents=new xe(this.request),this.mfa=new ze(this.request),this.passkeys=new _e(this.request),this.reg=new Le(this.request),this.tx=new Me(this.request)}};var je=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ye=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),x=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(d=>(a==="otp:sms"||a==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let d=o.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],s=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var H=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},fe=class me{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new y("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new y("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new y(`No matching factor found for ${t}.`);let u=(l,d)=>{if(!l.options?.length)throw new y(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(d?p=l.options.find(g=>g.name===d)?.label:p=l.options[0]?.label,!p)throw new y(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new y("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new y("Payload is required for passkeys.");let r=b("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(me.isPublicKeyCredentialCreationOptions(r)||me.isPublicKeyCredentialRequestOptions(r))return r;throw new y("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Ke=class{config;constructor(e){this.config=new H(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=b(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=b(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;te(s)}getJwtCookie(){return K(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){T(this.getJwtCookieName()),T(this.getIdTokenName()),T(this.getAccessTokenName()),T(this.getRefreshTokenName()),T(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=b(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return K(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new H(e),this.service=new he({BASE:e.baseUrl}),this.session=new Ke(e)}},L=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await I(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof A&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},It=new Set(["ERROR_PASSKEY_ABORTED"]),Y=class extends f{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof h){if(It.has(t.code))return{session:""};let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},ge=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await I(s),a=je(e,t),i="";t.txPayload&&(i=await new le().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new q(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),d=ye(l,e);return m.persistInfo(r,d),this.session.logout(),x(d)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=fe.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=fe.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),x(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return x(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return x(a,s)}catch(s){if(s instanceof A&&s.status===401&&s.body.session){let o=s.body,a=ye(o,t);return m.persistInfo(e,a),x(a)}if(s instanceof Error){let o=new Y(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var We=class extends f{constructor(e){super(e)}};U(We,[f,ge,L]);var $e=We;var ke=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ve=ke;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Je=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||F()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var Ge=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Re=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return E.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},X=Re;var be=class extends X{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await I(a),n=new q(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:d,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await R.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let Z=await this.service.reg.regRegComplete({requestBody:g}),Ye=_(Z);return this.session.setJwtCookie(Z.jwtAccess),w.persistDeviceId(o,a||Z.deviceId),Ye})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await I(w.getDeviceId(s)),a=new q(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let d=await R.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:d}),g=_(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=Ge(l);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw oe}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=Je(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await R.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:d})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new Y(this.config.getConfig()).reportError(t,s),s}}},He=be;var Q=class extends f{constructor(t){super(t)}};U(Q,[f,He,X,Ve,L]);var we=Q;var Tt=we;return rt(Ot);})();
1
+ "use strict";var LoginID=(()=>{var ee=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var r in t)ee(e,r,{get:t[r],enumerable:!0})},tt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qe(t))!Ze.call(e,o)&&o!==r&&ee(e,o,{get:()=>t[o],enumerable:!(s=Xe(t,o))||s.enumerable});return e};var rt=e=>tt(ee({},"__esModule",{value:!0}),e);var Ot={};et(Ot,{AbortError:()=>D,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>k,createPasskeyCredential:()=>V,default:()=>Tt,getPasskeyCredential:()=>J,isConditionalUIAvailable:()=>j,isPlatformAuthenticatorAvailable:()=>L});var I=async e=>{let t=JSON.stringify(await Ae()),r=await Ie(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},L=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},j=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Ae=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await L(),t=await j();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},Ie=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},K=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},te=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var y=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},h=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},d=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}},D=class extends Error{constructor(e){super(e),this.name="AbortError"}};var B=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),F=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Te=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},R=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=F(t);return B(s)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Te(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},re=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},W=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),v=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),se=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return R(s)},Oe=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},$=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Oe(24);var E=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new D("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},ve=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new h("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new h("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new h("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new h("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Ee=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new h("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new h("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},st=new y("User needs to be logged in to perform this operation."),oe=new y("No login options available."),V=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:O(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:O(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?ve(o,s):o}},J=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:O(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ee(o,s):o}},k=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?E.assignWebAuthnAbortController(t.abortController):(E.renewWebAuthnAbortController(),t.abortController=E.abortController);let o=await J(r,t),a=o.response;return{assertionResult:{authenticatorData:R(a.authenticatorData),clientDataJSON:R(a.clientDataJSON),credentialId:o.id,signature:R(a.signature),...a.userHandle&&{userHandle:R(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;E.renewWebAuthnAbortController();let s=await V(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:R(o.attestationObject),clientDataJSON:R(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:R(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:R(n)},...u&&{transports:u}},session:r}}};var U=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},q=e=>(e||(e=re()),{id:e,exp:Math.floor(Date.now()/1e3)+60}),S=async(e,t,r)=>{let s=B(F(JSON.stringify({alg:"ES256",jwk:t}))),o=B(F(JSON.stringify(e))),a=`${s}.${o}`,i=await se(r,a);return`${a}.${i}`};var ne=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var Se=e=>`LoginID_${e}_device-id`,w=class extends ne{static persistDeviceId(e,t){this.setItem(Se(e),t)}static getDeviceId(e){return this.getItem(Se(e))||""}},ue=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new d(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new d(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new d(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new d("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new d("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new d("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new d("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var at="lid_c_wtid",it="lid-wtid-k",qe=class extends ue{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await W(),t=await v(e),r=q(),s=await S(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await v(e.keyPair),r=q(e.id);return await S(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new d("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new d("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var le=class extends qe{constructor(){super(at,it)}},nt=1,Ce="app_id_idx",ut="username_idx",lt="loginid-trust-store",ct="LoginID_trust-id",ae="app_id_username_idx",x=class extends ue{appId;constructor(e){super(lt,nt,ct,[{name:ut,keyPath:["username"]},{name:Ce,keyPath:["appId"]},{name:ae,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await W(),r=await v(t),s=q(),o=await S(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(ae,[this.appId,e]),r=await v(t.keyPair),s=q(t.id);return await S(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof d&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ce,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ae,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Pe=e=>`LoginID_${e}_mfa-session`,m=class ie extends ne{static persistInfo(t,r){this.setItem(Pe(t),r)}static getInfo(t){return this.getItem(Pe(t))}static updateSession(t,r){let s=ie.getInfo(t);s?s.session=r:s={session:r},ie.persistInfo(t,s)}};var xe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},_e=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Ne=class{constructor(e){this.config=e}},De=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Be=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new De("Request aborted"))}}get isCancelled(){return this.#e}},A=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},de=e=>e!=null,z=e=>typeof e=="string",ce=e=>z(e)&&e!=="",pe=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof FormData,dt=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},pt=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{de(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},ht=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${pt(t.query)}`:o},yt=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{z(o)||pe(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>de(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},G=async(e,t)=>typeof t=="function"?t(e):t,mt=async(e,t)=>{let[r,s,o,a]=await Promise.all([G(t,e.TOKEN),G(t,e.USERNAME),G(t,e.PASSWORD),G(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>de(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(ce(r)&&(i.Authorization=`Bearer ${r}`),ce(s)&&ce(o)){let n=dt(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:pe(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":z(t.body)?i["Content-Type"]="text/plain":Fe(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ft=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):z(e.body)||pe(e.body)||Fe(e.body)?e.body:JSON.stringify(e.body)},gt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},Rt=(e,t)=>{if(t){let r=e.headers.get(t);if(z(r))return r}},kt=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},bt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new A(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new A(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},wt=(e,t)=>new Be(async(r,s,o)=>{try{let a=ht(e,t),i=yt(t),n=ft(t),u=await mt(e,t);if(!o.isCancelled){let l=await gt(e,t,a,n,i,u,o),c=await kt(l),p=Rt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??c};bt(t,g),r(g.body)}}catch(a){s(a)}}),At=class extends Ne{constructor(e){super(e)}request(e){return wt(this.config,e)}},Ue=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Me=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},Le=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},he=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=At){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Ue(this.request),this.clientEvents=new xe(this.request),this.mfa=new ze(this.request),this.passkeys=new _e(this.request),this.reg=new Me(this.request),this.tx=new Le(this.request)}};var je=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ye=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),_=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(c=>(a==="otp:sms"||a==="otp:email")&&c.label).map(c=>c.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let c=o.options.find(p=>p.value);c&&(u.value=c.value)}}return u})||[],s=["passkey:reg","passkey:auth","passkey:tx","otp:sms","otp:email","external"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var H=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},fe=class me{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new y("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new y("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new y(`No matching factor found for ${t}.`);let u=(l,c)=>{if(!l.options?.length)throw new y(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(c?p=l.options.find(g=>g.name===c)?.label:p=l.options[0]?.label,!p)throw new y(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new y("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new y("Payload is required for passkeys.");let r=b("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(me.isPublicKeyCredentialCreationOptions(r)||me.isPublicKeyCredentialRequestOptions(r))return r;throw new y("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Ke=class{config;constructor(e){this.config=new H(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=b(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=b(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;te(s)}getJwtCookie(){return K(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){T(this.getJwtCookieName()),T(this.getIdTokenName()),T(this.getAccessTokenName()),T(this.getRefreshTokenName()),T(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=b(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return K(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new H(e),this.service=new he({BASE:e.baseUrl}),this.session=new Ke(e)}},M=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await I(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof A&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},It=new Set(["ERROR_PASSKEY_ABORTED"]),Y=class extends f{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof h){if(It.has(t.code))return{session:""};let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},ge=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await I(s),a=je(e,t),i="";t.txPayload&&(i=await new le().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new x(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload},...t.traceId&&{traceId:t.traceId}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),c=ye(l,e);return m.persistInfo(r,c),this.session.logout(),_(c)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=fe.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=fe.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await k.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await k.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),_(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return _(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return _(a,s)}catch(s){if(s instanceof A&&s.status===401&&s.body.session){let o=s.body,a=ye(o,t);return m.persistInfo(e,a),_(a)}if(s instanceof Error){let o=new Y(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var We=class extends f{constructor(e){super(e)}};U(We,[f,ge,M]);var $e=We;var Re=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ve=Re;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Je=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||$()}),N=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var Ge=e=>[...e.crossAuthMethods,...e.fallbackMethods];var ke=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=N(i);return E.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},X=ke;var be=class extends X{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await I(a),n=new x(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),c={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:c,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await k.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let Z=await this.service.reg.regRegComplete({requestBody:g}),Ye=N(Z);return this.session.setJwtCookie(Z.jwtAccess),w.persistDeviceId(o,a||Z.deviceId),Ye})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await I(w.getDeviceId(s)),a=new x(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let c=await k.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:c}),g=N(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=Ge(l);await i.callbacks.onFallback(t,p)}return N({userId:"",jwtAccess:""},!1,!0)}default:throw oe}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=Je(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await k.getNavigatorCredential(u),c={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:c})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new Y(this.config.getConfig()).reportError(t,s),s}}},He=be;var Q=class extends f{constructor(t){super(t)}};U(Q,[f,He,X,Ve,M]);var we=Q;var Tt=we;return rt(Ot);})();
2
2
  //# sourceMappingURL=index.global.js.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var A=async e=>{let t=JSON.stringify(await be()),r=await we(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},Y=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},X=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},be=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await Y(),t=await X();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},we=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},L=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},Q=e=>{document.cookie=e},I=e=>{document.cookie=`${e}=; expires=${new Date}`};var M=class extends Error{constructor(e){super(e),this.name="AbortError"}},h=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},y=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var N=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),D=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Ae=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=D(t);return N(s)},T=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Ae(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},R=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},Z=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},j=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),O=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),ee=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(s)},Ie=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},B=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Ie(24);var v=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new M("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},Te=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new y("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new y("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new y("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new y("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new y("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new y(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new y("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Oe=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new y("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new y("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new y(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new y("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},He=new h("User needs to be logged in to perform this operation."),te=new h("No login options available."),re=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:T(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:T(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:T(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Te(o,s):o}},se=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:T(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:T(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Oe(o,s):o}},b=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?v.assignWebAuthnAbortController(t.abortController):(v.renewWebAuthnAbortController(),t.abortController=v.abortController);let o=await se(r,t),a=o.response;return{assertionResult:{authenticatorData:k(a.authenticatorData),clientDataJSON:k(a.clientDataJSON),credentialId:o.id,signature:k(a.signature),...a.userHandle&&{userHandle:k(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;v.renewWebAuthnAbortController();let s=await re(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:k(o.attestationObject),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:k(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var F=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},K=(e,t,r)=>(r||(r=Z()),{id:r,username:t,aud:e}),E=async(e,t,r)=>{let s=N(D(JSON.stringify({alg:"ES256",jwk:t}))),o=N(D(JSON.stringify(e))),a=`${s}.${o}`,i=await ee(r,a);return`${a}.${i}`};var ie=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var ve=e=>`LoginID_${e}_device-id`,w=class extends ie{static persistDeviceId(e,t){this.setItem(ve(e),t)}static getDeviceId(e){return this.getItem(ve(e))||""}},ne=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new c("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},Ye=1;var Xe="lid_c_wtid",Qe="lid-wtid-k",Ce=class extends ne{constructor(e,t){super(e,Ye,t)}async setCheckoutId(){let e=await j(),t=await O(e),r={id:B()},s=await E(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await O(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await O(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new c("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new c("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var ue=class extends Ce{constructor(){super(Xe,Qe)}},Ze=1,Ee="app_id_idx",et="username_idx",tt="loginid-trust-store",rt="LoginID_trust-id",oe="app_id_username_idx",q=class extends ne{appId;constructor(e){super(tt,Ze,rt,[{name:et,keyPath:["username"]},{name:Ee,keyPath:["appId"]},{name:oe,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await j(),r=await O(t),s=K(this.appId,e),o=await E(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(oe,[this.appId,e]),r=await O(t.keyPair),s=K(this.appId,e,t.id);return await E(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof c&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ee,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(oe,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Se=e=>`LoginID_${e}_mfa-session`,m=class ae extends ie{static persistInfo(t,r){this.setItem(Se(t),r)}static getInfo(t){return this.getItem(Se(t))}static updateSession(t,r){let s=ae.getInfo(t);s?s.session=r:s={session:r},ae.persistInfo(t,s)}};var Pe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},qe=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},xe=class{constructor(e){this.config=e}},_e=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Ne=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new _e("Request aborted"))}}get isCancelled(){return this.#e}},S=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},de=e=>e!=null,U=e=>typeof e=="string",le=e=>U(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),De=e=>e instanceof FormData,st=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},ot=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{de(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},at=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${ot(t.query)}`:o},it=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{U(o)||ce(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>de(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},W=async(e,t)=>typeof t=="function"?t(e):t,nt=async(e,t)=>{let[r,s,o,a]=await Promise.all([W(t,e.TOKEN),W(t,e.USERNAME),W(t,e.PASSWORD),W(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>de(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(le(r)&&(i.Authorization=`Bearer ${r}`),le(s)&&le(o)){let n=st(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:ce(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":U(t.body)?i["Content-Type"]="text/plain":De(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ut=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):U(e.body)||ce(e.body)||De(e.body)?e.body:JSON.stringify(e.body)},lt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},dt=(e,t)=>{if(t){let r=e.headers.get(t);if(U(r))return r}},ct=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},pt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new S(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new S(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},ht=(e,t)=>new Ne(async(r,s,o)=>{try{let a=at(e,t),i=it(t),n=ut(t),u=await nt(e,t);if(!o.isCancelled){let l=await lt(e,t,a,n,i,u,o),d=await ct(l),p=dt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};pt(t,g),r(g.body)}}catch(a){s(a)}}),yt=class extends xe{constructor(e){super(e)}request(e){return ht(this.config,e)}},Be=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Fe=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Ue=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},pe=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=yt){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Be(this.request),this.clientEvents=new Pe(this.request),this.mfa=new Fe(this.request),this.passkeys=new qe(this.request),this.reg=new Ue(this.request),this.tx=new ze(this.request)}};var Le=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),he=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),x=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(d=>(a==="otp:sms"||a==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let d=o.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],s=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var $=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},me=class ye{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new h("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new h("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new h(`No matching factor found for ${t}.`);let u=(l,d)=>{if(!l.options?.length)throw new h(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(d?p=l.options.find(g=>g.name===d)?.label:p=l.options[0]?.label,!p)throw new h(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new h("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new h("Payload is required for passkeys.");let r=R("."+t);if(!r)throw new h("Invalid payload for passkeys.");if(ye.isPublicKeyCredentialCreationOptions(r)||ye.isPublicKeyCredentialRequestOptions(r))return r;throw new h("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Me=class{config;constructor(e){this.config=new $(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=R(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=R(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;Q(s)}getJwtCookie(){return L(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){I(this.getJwtCookieName()),I(this.getIdTokenName()),I(this.getAccessTokenName()),I(this.getRefreshTokenName()),I(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=R(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return L(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new $(e),this.service=new pe({BASE:e.baseUrl}),this.session=new Me(e)}},z=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await A(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof S&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},mt=new Set(["ERROR_PASSKEY_ABORTED"]),V=class extends f{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof y){if(mt.has(t.code))return{session:""};let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},fe=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await A(s),a=Le(e,t),i="";t.txPayload&&(i=await new ue().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new q(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),d=he(l,e);return m.persistInfo(r,d),this.session.logout(),x(d)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=me.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=me.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await b.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await b.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),x(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new h(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return x(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return x(a,s)}catch(s){if(s instanceof S&&s.status===401&&s.body.session){let o=s.body,a=he(o,t);return m.persistInfo(e,a),x(a)}if(s instanceof Error){let o=new V(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var je=class extends f{constructor(e){super(e)}};F(je,[f,fe,z]);var ft=je;var ge=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ke=ge;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),We=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||B()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var $e=e=>[...e.crossAuthMethods,...e.fallbackMethods];var ke=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return v.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},J=ke;var Re=class extends J{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await A(a),n=new q(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&R(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:d,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await b.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let H=await this.service.reg.regRegComplete({requestBody:g}),Ge=_(H);return this.session.setJwtCookie(H.jwtAccess),w.persistDeviceId(o,a||H.deviceId),Ge})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await A(w.getDeviceId(s)),a=new q(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let d=await b.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:d}),g=_(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=$e(l);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw te}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=We(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await b.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:d})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new V(this.config.getConfig()).reportError(t,s),s}}},Ve=Re;var G=class extends f{constructor(t){super(t)}};F(G,[f,Ve,J,Ke,z]);var Je=G;var po=Je;export{M as AbortError,S as ApiError,ft as LoginIDMfa,Je as LoginIDWebSDK,y as PasskeyError,b as WebAuthnHelper,re as createPasskeyCredential,po as default,se as getPasskeyCredential,X as isConditionalUIAvailable,Y as isPlatformAuthenticatorAvailable};
1
+ var A=async e=>{let t=JSON.stringify(await be()),r=await we(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},Y=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},X=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},be=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await Y(),t=await X();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},we=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},M=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},Q=e=>{document.cookie=e},I=e=>{document.cookie=`${e}=; expires=${new Date}`};var h=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},y=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},d=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}},L=class extends Error{constructor(e){super(e),this.name="AbortError"}};var D=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Ae=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},R=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=B(t);return D(s)},T=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Ae(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},k=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},Z=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},j=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),O=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),ee=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return R(s)},Ie=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},K=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Ie(24);var v=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new L("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},Te=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new y("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new y("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new y("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new y("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new y("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new y(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new y("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Oe=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new y("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new y("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new y(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new y("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},He=new h("User needs to be logged in to perform this operation."),te=new h("No login options available."),re=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:T(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:T(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:T(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Te(o,s):o}},se=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:T(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:T(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Oe(o,s):o}},b=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?v.assignWebAuthnAbortController(t.abortController):(v.renewWebAuthnAbortController(),t.abortController=v.abortController);let o=await se(r,t),a=o.response;return{assertionResult:{authenticatorData:R(a.authenticatorData),clientDataJSON:R(a.clientDataJSON),credentialId:o.id,signature:R(a.signature),...a.userHandle&&{userHandle:R(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;v.renewWebAuthnAbortController();let s=await re(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:R(o.attestationObject),clientDataJSON:R(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:R(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:R(n)},...u&&{transports:u}},session:r}}};var F=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},q=e=>(e||(e=Z()),{id:e,exp:Math.floor(Date.now()/1e3)+60}),E=async(e,t,r)=>{let s=D(B(JSON.stringify({alg:"ES256",jwk:t}))),o=D(B(JSON.stringify(e))),a=`${s}.${o}`,i=await ee(r,a);return`${a}.${i}`};var ie=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var ve=e=>`LoginID_${e}_device-id`,w=class extends ie{static persistDeviceId(e,t){this.setItem(ve(e),t)}static getDeviceId(e){return this.getItem(ve(e))||""}},ne=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new d(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new d(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new d(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new d("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new d("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new d("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new d("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new d("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},Ye=1;var Xe="lid_c_wtid",Qe="lid-wtid-k",Ce=class extends ne{constructor(e,t){super(e,Ye,t)}async setCheckoutId(){let e=await j(),t=await O(e),r=q(),s=await E(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await O(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await O(e.keyPair),r=q(e.id);return await E(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new d("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof d&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new d("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var ue=class extends Ce{constructor(){super(Xe,Qe)}},Ze=1,Ee="app_id_idx",et="username_idx",tt="loginid-trust-store",rt="LoginID_trust-id",oe="app_id_username_idx",x=class extends ne{appId;constructor(e){super(tt,Ze,rt,[{name:et,keyPath:["username"]},{name:Ee,keyPath:["appId"]},{name:oe,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await j(),r=await O(t),s=q(),o=await E(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(oe,[this.appId,e]),r=await O(t.keyPair),s=q(t.id);return await E(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof d&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ee,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(oe,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Se=e=>`LoginID_${e}_mfa-session`,m=class ae extends ie{static persistInfo(t,r){this.setItem(Se(t),r)}static getInfo(t){return this.getItem(Se(t))}static updateSession(t,r){let s=ae.getInfo(t);s?s.session=r:s={session:r},ae.persistInfo(t,s)}};var Pe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},qe=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},xe=class{constructor(e){this.config=e}},_e=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Ne=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new _e("Request aborted"))}}get isCancelled(){return this.#e}},S=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},ce=e=>e!=null,U=e=>typeof e=="string",le=e=>U(e)&&e!=="",de=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),De=e=>e instanceof FormData,st=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},ot=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{ce(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},at=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${ot(t.query)}`:o},it=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{U(o)||de(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>ce(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},W=async(e,t)=>typeof t=="function"?t(e):t,nt=async(e,t)=>{let[r,s,o,a]=await Promise.all([W(t,e.TOKEN),W(t,e.USERNAME),W(t,e.PASSWORD),W(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>ce(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(le(r)&&(i.Authorization=`Bearer ${r}`),le(s)&&le(o)){let n=st(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:de(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":U(t.body)?i["Content-Type"]="text/plain":De(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ut=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):U(e.body)||de(e.body)||De(e.body)?e.body:JSON.stringify(e.body)},lt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},ct=(e,t)=>{if(t){let r=e.headers.get(t);if(U(r))return r}},dt=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},pt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new S(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new S(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},ht=(e,t)=>new Ne(async(r,s,o)=>{try{let a=at(e,t),i=it(t),n=ut(t),u=await nt(e,t);if(!o.isCancelled){let l=await lt(e,t,a,n,i,u,o),c=await dt(l),p=ct(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??c};pt(t,g),r(g.body)}}catch(a){s(a)}}),yt=class extends xe{constructor(e){super(e)}request(e){return ht(this.config,e)}},Be=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Fe=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Ue=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},pe=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=yt){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Be(this.request),this.clientEvents=new Pe(this.request),this.mfa=new Fe(this.request),this.passkeys=new qe(this.request),this.reg=new Ue(this.request),this.tx=new ze(this.request)}};var Me=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),he=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),_=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(c=>(a==="otp:sms"||a==="otp:email")&&c.label).map(c=>c.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let c=o.options.find(p=>p.value);c&&(u.value=c.value)}}return u})||[],s=["passkey:reg","passkey:auth","passkey:tx","otp:sms","otp:email","external"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var $=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},me=class ye{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new h("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new h("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new h(`No matching factor found for ${t}.`);let u=(l,c)=>{if(!l.options?.length)throw new h(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(c?p=l.options.find(g=>g.name===c)?.label:p=l.options[0]?.label,!p)throw new h(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new h("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new h("Payload is required for passkeys.");let r=k("."+t);if(!r)throw new h("Invalid payload for passkeys.");if(ye.isPublicKeyCredentialCreationOptions(r)||ye.isPublicKeyCredentialRequestOptions(r))return r;throw new h("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Le=class{config;constructor(e){this.config=new $(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=k(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=k(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;Q(s)}getJwtCookie(){return M(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){I(this.getJwtCookieName()),I(this.getIdTokenName()),I(this.getAccessTokenName()),I(this.getRefreshTokenName()),I(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=k(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return M(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new $(e),this.service=new pe({BASE:e.baseUrl}),this.session=new Le(e)}},z=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await A(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof S&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},mt=new Set(["ERROR_PASSKEY_ABORTED"]),V=class extends f{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof y){if(mt.has(t.code))return{session:""};let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},fe=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await A(s),a=Me(e,t),i="";t.txPayload&&(i=await new ue().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new x(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload},...t.traceId&&{traceId:t.traceId}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),c=he(l,e);return m.persistInfo(r,c),this.session.logout(),_(c)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=me.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=me.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await b.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await b.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),_(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new h(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return _(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return _(a,s)}catch(s){if(s instanceof S&&s.status===401&&s.body.session){let o=s.body,a=he(o,t);return m.persistInfo(e,a),_(a)}if(s instanceof Error){let o=new V(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var je=class extends f{constructor(e){super(e)}};F(je,[f,fe,z]);var ft=je;var ge=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ke=ge;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),We=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||K()}),N=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var $e=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Re=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=N(i);return v.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},J=Re;var ke=class extends J{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await A(a),n=new x(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&k(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),c={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:c,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await b.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let H=await this.service.reg.regRegComplete({requestBody:g}),Ge=N(H);return this.session.setJwtCookie(H.jwtAccess),w.persistDeviceId(o,a||H.deviceId),Ge})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await A(w.getDeviceId(s)),a=new x(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let c=await b.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:c}),g=N(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=$e(l);await i.callbacks.onFallback(t,p)}return N({userId:"",jwtAccess:""},!1,!0)}default:throw te}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=We(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await b.getNavigatorCredential(u),c={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:c})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new V(this.config.getConfig()).reportError(t,s),s}}},Ve=ke;var G=class extends f{constructor(t){super(t)}};F(G,[f,Ve,J,Ke,z]);var Je=G;var ho=Je;export{L as AbortError,S as ApiError,ft as LoginIDMfa,Je as LoginIDWebSDK,y as PasskeyError,b as WebAuthnHelper,re as createPasskeyCredential,ho as default,se as getPasskeyCredential,X as isConditionalUIAvailable,Y as isPlatformAuthenticatorAvailable};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loginid/websdk3",
3
- "version": "3.3.1",
3
+ "version": "3.4.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -29,7 +29,8 @@
29
29
  "delete-map-files": "find ./dist -name '*.map' -delete",
30
30
  "delete-references-to-map-files": "find ./dist -name '*.js' -or -name '*.mjs' -exec sed -i -e 's/sourceMappingURL=[^ ]*.map//g' {} +",
31
31
  "lint": "eslint \"src/**/*.ts?(x)\"",
32
- "test": "jest"
32
+ "test": "jest",
33
+ "docs": "typedoc"
33
34
  },
34
35
  "author": "LoginID Inc.",
35
36
  "license": "ISC",