@loginid/websdk3 3.3.2 → 3.5.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 +1 -1
- package/dist/index.d.ts +140 -20
- package/dist/index.global.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +3 -2
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:()=>D,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>R,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 D=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}},d=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};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},k=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 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)},$=()=>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}},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 J(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 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: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))})})},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)},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),c=await Rt(l),p=kt(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: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,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}},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 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),_(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 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||$()}),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 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 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 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 R.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 R.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 R.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});
|
|
1
|
+
"use strict";var ie=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var lt=(e,t)=>{for(var r in t)ie(e,r,{get:t[r],enumerable:!0})},dt=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nt(t))!ut.call(e,s)&&s!==r&&ie(e,s,{get:()=>t[s],enumerable:!(a=it(t,s))||a.enumerable});return e};var ct=e=>dt(ie({},"__esModule",{value:!0}),e);var Nt={};lt(Nt,{AbortError:()=>U,ApiError:()=>T,LoginIDMfa:()=>et,LoginIDWebSDK:()=>Ce,PasskeyError:()=>h,WebAuthnHelper:()=>R,createPasskeyCredential:()=>Y,default:()=>_t,getPasskeyCredential:()=>X,isConditionalUIAvailable:()=>V,isPlatformAuthenticatorAvailable:()=>$});module.exports=ct(Nt);var b=class ne{logLevel;static createDefault(){let t=process.env.NODE_ENV==="production"?4:0;return new ne(t)}static logger=ne.createDefault();constructor(t=2){this.logLevel=t}debug(t){this.logLevel<=0&&console.debug(`[DEBUG] ${t}`)}info(t){this.logLevel<=1&&console.info(`[INFO] ${t}`)}warn(t){this.logLevel<=2&&console.warn(`[WARN] ${t}`)}error(t){this.logLevel<=3&&console.error(`[ERROR] ${t}`)}get level(){return this.logLevel}},v=async e=>{let t=JSON.stringify(await Pe()),r=await qe(),a={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(a.deviceId=e),a},$=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},V=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Pe=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await $(),t=await V();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},ue=async(e,t,r)=>{try{if(!window.PublicKeyCredential){b.logger.debug("PublicKeyCredential is not available.");return}if(!window.PublicKeyCredential.signalAllAcceptedCredentials){b.logger.debug("signalAllAcceptedCredentials is not available.");return}await window.PublicKeyCredential.signalAllAcceptedCredentials({rpId:e,userId:t,allAcceptedCredentialIds:r})}catch(a){b.logger.debug(`Error at signalAllAcceptedCredentials: ${a}`);return}},le=async(e,t)=>{try{if(!window.PublicKeyCredential){b.logger.debug("PublicKeyCredential is not available.");return}if(!window.PublicKeyCredential.signalUnknownCredential){b.logger.debug("signalUnknownCredential is not available.");return}await window.PublicKeyCredential.signalUnknownCredential({rpId:e,credentialId:t})}catch(r){b.logger.debug(`Error at signalUnknownCredential: ${r}`);return}},qe=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},J=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},de=e=>{document.cookie=e},O=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}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}},U=class extends Error{constructor(e){super(e),this.name="AbortError"}};var z=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),L=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],a=0;for(;a<e.length;){let i=e.charCodeAt(a++),n=e.charCodeAt(a++),u=e.charCodeAt(a++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let s=r.join(""),o=e.length%3;return o?s.slice(0,o-3)+"===".slice(o||3):s},xe=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},a=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let s=0,o=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(s=(s<<6)+u,o+=6;o>=8;)i+=a(s>>(o-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)t+=String.fromCharCode(r[s]);let a=L(t);return z(a)},E=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=xe(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++)r[a]=t.charCodeAt(a);return r.buffer},w=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(a=>"%"+("00"+a.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},ce=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let a=0;a<e;a++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},G=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),S=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),pe=async(e,t)=>{let r=new TextEncoder().encode(t),a=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(a)},_e=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},H=()=>window.crypto?.randomUUID?window.crypto.randomUUID():_e(24);var C=class x{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new U("Cancelling current WebAuthn request");x.abortController.abort(t)};static renewWebAuthnAbortController=()=>{x.abortWebAuthnRequest();let t=new AbortController;x.abortController=t};static assignWebAuthnAbortController=t=>{x.abortWebAuthnRequest(),x.abortController=t}},Ne=(e,t)=>{let r=e.name,{publicKey:a}=t;if(r==="ConstraintError"){if(a?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(a?.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 s=a?.rp?.id;if(s!==window.location.hostname)return new h(`The domain of the relying party (${s}) 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},De=(e,t)=>{let r=e.name,{publicKey:a}=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 s=a?.rpId;if(s!==window.location.hostname)return new h(`The domain of the relying party (${s}) 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},pt=new y("User needs to be logged in to perform this operation."),he=new y("No login options available."),Y=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let s of e.excludeCredentials){let o={id:E(s.id),transports:s.transports,type:s.type};t.push(o)}}let r=e.pubKeyCredParams,a={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:E(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:E(e.user.id)}}};try{let s=await navigator.credentials.create(a);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?Ne(s,a):s}},X=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let s of e.allowCredentials){let o={id:E(s.id),transports:s.transports,type:s.type};r.push(o)}}let a={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:E(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let s=await navigator.credentials.get(a);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?De(s,a):s}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:a}=e;t.abortController?C.assignWebAuthnAbortController(t.abortController):(C.renewWebAuthnAbortController(),t.abortController=C.abortController);let s=await X(r,t),o=s.response;return{assertionResult:{authenticatorData:k(o.authenticatorData),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,signature:k(o.signature),...o.userHandle&&{userHandle:k(o.userHandle)}},session:a}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;C.renewWebAuthnAbortController();let a=await Y(t),s=a.response,o=s.getPublicKey&&s.getPublicKey(),i=s.getPublicKeyAlgorithm&&s.getPublicKeyAlgorithm(),n=s.getAuthenticatorData&&s.getAuthenticatorData(),u=s.getTransports&&s.getTransports();return{creationResult:{attestationObject:k(s.attestationObject),clientDataJSON:k(s.clientDataJSON),credentialId:a.id,...o&&{publicKey:k(o)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var A=async(e,t)=>{try{if(!t.getSessionInfo()){b.logger.debug("No session info available for syncing passkeys.");return}let r=t.getToken({}),a=await e.passkeys.passkeysPasskeysList({authorization:r});await Q(a,t)}catch(r){b.logger.debug(`Error fetching and syncing passkeys: ${r}`)}},Q=async(e,t)=>{try{let r=t.getSessionInfo();if(!r){b.logger.debug("No session info available for syncing passkeys.");return}let{id:a,rpId:s}=r,o=e.map(i=>i.credentialId).filter(Boolean);await ue(s,a,o)}catch(r){b.logger.debug(`Error syncing passkeys: ${r}`)}},M=async(e,t)=>{try{if(!e||!t){b.logger.debug("Credential ID or RP ID is missing.");return}await le(t,e)}catch(r){b.logger.debug(`Error signaling unknown credential: ${r}`)}};var K=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(a=>{Object.defineProperty(e.prototype,a,Object.getOwnPropertyDescriptor(r.prototype,a)||Object.create(null))})})},_=e=>(e||(e=ce()),{id:e,exp:Math.floor(Date.now()/1e3)+60}),P=async(e,t,r)=>{let a=z(L(JSON.stringify({alg:"ES256",jwk:t}))),s=z(L(JSON.stringify(e))),o=`${a}.${s}`,i=await pe(r,o);return`${o}.${i}`};var me=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 ge=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,a=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=a}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:a,keyPath:s,options:o})=>r.createIndex(a,s,o))}},e}async getAllByIndex(e,t){return new Promise((r,a)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);o.onsuccess=()=>{r(o.result)},o.onerror=()=>a(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>a(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,a)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);o.onsuccess=()=>{let i=o.result;i?r(i):a(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},o.onerror=()=>a(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>a(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 a=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();a.onsuccess=()=>{let s=a.result;s?e(s.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},a.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 a=this.openDb();a.onsuccess=()=>{let s=a.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);s.onsuccess=()=>t(),s.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},a.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let a=this.openDb();a.onsuccess=()=>{let s=a.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);s.onsuccess=()=>t(),s.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},a.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ht=1;var yt="lid_c_wtid",ft="lid-wtid-k",Le=class extends ge{constructor(e,t){super(e,ht,t)}async setCheckoutId(){let e=await G(),t=await S(e),r=_(),a=await P(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),a}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await S(e.keyPair),r={id:e.id};return await P(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 S(e.keyPair),r=_(e.id);return await P(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 be=class extends Le{constructor(){super(yt,ft)}},mt=1,Be="app_id_idx",gt="username_idx",bt="loginid-trust-store",kt="LoginID_trust-id",ye="app_id_username_idx",N=class extends ge{appId;constructor(e){super(bt,mt,kt,[{name:gt,keyPath:["username"]},{name:Be,keyPath:["appId"]},{name:ye,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await G(),r=await S(t),a=_(),s=await P(a,r,t.privateKey);return await this.putRecord({id:a.id,appId:this.appId,username:e,keyPair:t}),s}async signWithTrustId(e){let t=await this.getByIndex(ye,[this.appId,e]),r=await S(t.keyPair),a=_(t.id);return await P(a,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(Be,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ye,[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)}}},Fe=e=>`LoginID_${e}_mfa-session`,f=class fe extends me{static persistInfo(t,r){this.setItem(Fe(t),r)}static getInfo(t){return this.getItem(Fe(t))}static updateSession(t,r){let a=fe.getInfo(t);a?a.session=r:a={session:r},fe.persistInfo(t,a)}},Z=(e,t)=>`LoginID_${e}_${t}`,Ue="device-id",ze="rp-id",I=class extends me{static persistDeviceId(e,t){this.setItem(Z(e,Ue),t)}static getDeviceId(e){return this.getItem(Z(e,Ue))||""}static persistRpId(e,t){this.setItem(Z(e,ze),t)}static getRpId(e){return this.getItem(Z(e,ze))}};var Me=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."}})}},Ke=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."}})}},je=class{constructor(e){this.config=e}},We=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},$e=class{#t;#r;#e;#s;#o;#i;#a;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#o=new Promise((t,r)=>{this.#i=t,this.#a=r;let a=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},s=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#a&&this.#a(i))},o=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(o,"isResolved",{get:()=>this.#t}),Object.defineProperty(o,"isRejected",{get:()=>this.#r}),Object.defineProperty(o,"isCancelled",{get:()=>this.#e}),e(a,s,o)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#o.then(e,t)}catch(e){return this.#o.catch(e)}finally(e){return this.#o.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.#a&&this.#a(new We("Request aborted"))}}get isCancelled(){return this.#e}},T=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}},Re=e=>e!=null,j=e=>typeof e=="string",ke=e=>j(e)&&e!=="",we=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]),Ve=e=>e instanceof FormData,Rt=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},wt=e=>{let t=[],r=(s,o)=>{t.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(o))}`)},a=(s,o)=>{Re(o)&&(Array.isArray(o)?o.forEach(i=>{a(s,i)}):typeof o=="object"?Object.entries(o).forEach(([i,n])=>{a(`${s}[${i}]`,n)}):r(s,o))};return Object.entries(e).forEach(([s,o])=>{a(s,o)}),t.length>0?`?${t.join("&")}`:""},It=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,a=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(o,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):o),s=`${e.BASE}${a}`;return t.query?`${s}${wt(t.query)}`:s},At=e=>{if(e.formData){let t=new FormData,r=(a,s)=>{j(s)||we(s)?t.append(a,s):t.append(a,JSON.stringify(s))};return Object.entries(e.formData).filter(([a,s])=>Re(s)).forEach(([a,s])=>{Array.isArray(s)?s.forEach(o=>r(a,o)):r(a,s)}),t}},ee=async(e,t)=>typeof t=="function"?t(e):t,Tt=async(e,t)=>{let[r,a,s,o]=await Promise.all([ee(t,e.TOKEN),ee(t,e.USERNAME),ee(t,e.PASSWORD),ee(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...o,...t.headers}).filter(([n,u])=>Re(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(ke(r)&&(i.Authorization=`Bearer ${r}`),ke(a)&&ke(s)){let n=Rt(`${a}:${s}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:we(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":j(t.body)?i["Content-Type"]="text/plain":Ve(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},vt=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):j(e.body)||we(e.body)||Ve(e.body)?e.body:JSON.stringify(e.body)},Ot=async(e,t,r,a,s,o,i)=>{let n=new AbortController,u={headers:o,body:a??s,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},Et=(e,t)=>{if(t){let r=e.headers.get(t);if(j(r))return r}},St=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)}},Ct=(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 T(e,t,r);if(!t.ok){let a=t.status??"unknown",s=t.statusText??"unknown",o=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new T(e,t,`Generic Error: status: ${a}; status text: ${s}; body: ${o}`)}},Pt=(e,t)=>new $e(async(r,a,s)=>{try{let o=It(e,t),i=At(t),n=vt(t),u=await Tt(e,t);if(!s.isCancelled){let l=await Ot(e,t,o,n,i,u,s),d=await St(l),p=Et(l,t.responseHeader),g={url:o,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};Ct(t,g),r(g.body)}}catch(o){a(o)}}),qt=class extends je{constructor(e){super(e)}request(e){return Pt(this.config,e)}},Je=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."}})}},Ge=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."}})}mfaMfaDiscover({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/discover",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."}})}mfaMfaPayloadUpdate({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/payload",headers:{Authorization:t},body:e,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."}})}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."}})}},He=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."}})}},Ye=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."}})}},Ie=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=qt){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 Je(this.request),this.clientEvents=new Me(this.request),this.mfa=new Ge(this.request),this.passkeys=new Ke(this.request),this.reg=new He(this.request),this.tx=new Ye(this.request)}};var Xe=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),te=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),D=(e,t)=>{let r=e?.next?.map(s=>{let{name:o,label:i,desc:n}=s.action,u={type:o,label:i,...n&&{description:n}};if(s.options){let l=s.options.filter(d=>(o==="otp:sms"||o==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),o==="passkey:reg"||o==="passkey:auth"||o==="passkey:tx"){let d=s.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],a=["passkey:reg","passkey:auth","passkey:tx","otp:sms","otp:email","external"].find(s=>e?.next?.some(o=>o.action.name===s));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...a&&{nextAction:a},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 re=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}},Te=class Ae{static mfaOptionValidator(t,r,a){let{session:s=r?.session,payload:o=""}=a;if(!s)throw new y("A session is required to perform MFA factor.");if(o)return{session:s,payload:o};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:s,payload:u(n)};case"otp:email":return{session:s,payload:u(n,"email:primary")};case"otp:sms":return{session:s,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=w("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(Ae.isPublicKeyCredentialCreationOptions(r)||Ae.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 Qe=class{config;constructor(e){this.config=new re(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||this.retrieveToken("accessToken")||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=w(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub,rpId:e.rpId}}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=w(e),r=new Date(t.exp*1e3).toUTCString(),a=`${this.getJwtCookieName()}=${e}; expires=${r}`;de(a)}getJwtCookie(){return J(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){O(this.getJwtCookieName()),O(this.getIdTokenName()),O(this.getAccessTokenName()),O(this.getRefreshTokenName()),O(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:a,refreshToken:s}=e,o=(i,n)=>{if(!n)return;let u=w(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};o(this.getIdTokenName(),r),o(this.getAccessTokenName(),t),o(this.getRefreshTokenName(),s),o(this.getPayloadSignatureName(),a)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return J(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var m=class{config;service;session;constructor(e){this.config=new re(e),this.service=new Ie({BASE:e.baseUrl}),this.session=new Qe(e)}},W=class extends m{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 v(),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 T&&(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(),f.persistInfo(e,{next:[]})}},xt=new Set(["ERROR_PASSKEY_ABORTED"]),se=class extends m{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof h){if(xt.has(t.code))return{session:""};let a=t.cause,s=`${t.code} - ${t.message} - ${a.name} - ${a.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:s}})}}},ve=class extends m{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),a=I.getDeviceId(r),s=await v(a),o=Xe(e,t),i="";t.txPayload&&(i=await new be().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new N(r).setOrSignWithTrustId(e));let u={deviceInfo:s,user:{username:e,usernameType:o.usernameType,displayName:o.displayName,...t.name&&{name:t.name},...t.phone&&{name:t.phone}},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}),d=te(l,e);return f.persistInfo(r,d),this.session.logout(),D(d)}async performAction(e,t={}){let r=this.config.getAppId(),a=f.getInfo(r),{payload:s,session:o}=Te.mfaOptionValidator(e,a,t);if(e==="passkey:tx"&&t.txPayload){let{txPayload:i,...n}=t,u=await this.service.mfa.mfaMfaPayloadUpdate({authorization:o,requestBody:{payload:i}}),l=a?.username,d=te(u,l);return f.persistInfo(r,d),await this.performAction(e,n)}switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=Te.validatePasskeyPayload(s);if("rpId"in i)return await this.invokeMfaApi(e,r,a?.username,async()=>{let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:o},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:o,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:o,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(e,r,a?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:o});try{return await this.service.mfa.mfaMfaPasskeyReg({authorization:o,requestBody:{creationResult:n.creationResult}})}catch(u){throw M(n.creationResult.credentialId,i.rp.id),u}});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:o,requestBody:{method:e==="otp:email"?"email":"sms",option:s}});return f.updateSession(r,i),D(f.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(e,r,a?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:o,requestBody:{otp:s}}));case"external":return await this.invokeMfaApi(e,r,a?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:o,requestBody:{token:s}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=f.getInfo(e),r=this.session.getTokenSet();return D(t,r)}async invokeMfaApi(e,t,r="",a){try{let s=await a(),o=f.getInfo(t);f.persistInfo(t,{...r&&{username:r},flow:o?.flow,next:[]}),this.session.setTokenSet(s),I.persistDeviceId(t,s.deviceId);let i=f.getInfo(t);return(e==="passkey:auth"||e==="passkey:tx")&&A(this.service,this.session),D(i,s)}catch(s){if(s instanceof T&&s.status===401&&s.body.session){let o=s.body,i=te(o,r);return f.persistInfo(t,i),D(i)}if(s instanceof Error){let o=new se(this.config.getConfig()),i=this.config.getAppId(),n=f.getInfo(i);n?.session&&o.reportError(n.session,s).then(u=>{u?.session&&f.updateSession(i,u.session)})}throw s}}};var Ze=class extends m{constructor(e){super(e)}};K(Ze,[m,ve,W]);var et=Ze;var Oe=class extends m{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t),a=await this.service.passkeys.passkeysPasskeysList({authorization:r});return Q(a,this.session),a}async renamePasskey(t,r,a={}){let s=this.session.getToken(a),o={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:s,id:t,requestBody:o})}async deletePasskey(t,r={}){let a=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:a,id:t}),A(this.service,this.session)}},tt=Oe;var q=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),rt=(e,t)=>({...q(e,"",t),txType:t.txType||"raw",nonce:t.nonce||H()}),B=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,deviceId:e.deviceId,isAuthenticated:t,isFallback:r});var st=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Ee=class extends m{constructor(t){super(t)}async validateOtp(t,r,a={}){let s=q(t,"",a),o={authCode:r,user:{username:t,usernameType:s.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:o}),n=B(i);return C.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",a={}){let s=q(t,"",a),o={user:{username:t,usernameType:s.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:o});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:o});break;default:throw new Error("Invalid message method")}}},ae=Ee;var Se=class extends ae{constructor(t){super(t)}async createPasskey(t,r="",a={}){let s=this.config.getAppId(),o=I.getDeviceId(s),i=await v(o),n=new N(s),u=q(t,r,a);u.authzToken=this.session.getToken(u),u.authzToken&&w(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:s},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...a.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);a.passkeyName&&(g.passkeyName=a.passkeyName);try{let F=await this.service.reg.regRegComplete({requestBody:g}),ot=B(F);return this.session.setJwtCookie(F.jwtAccess),I.persistDeviceId(s,o||F.deviceId),ot}catch(F){throw M(g.creationResult.credentialId,p.registrationRequestOptions.rp.id),F}})}async authenticateWithPasskey(t="",r={}){let a=this.config.getAppId(),s=await v(I.getDeviceId(a)),o=new N(a),i=q(t,"",r),n=await o.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:a},deviceInfo:s,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});A(this.service,this.session);let g=B(p);return this.session.setJwtCookie(g.token),I.persistDeviceId(a,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=st(l);await i.callbacks.onFallback(t,p)}return B({userId:"",jwtAccess:""},!1,!0)}default:throw he}}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 s=await this.authenticateWithPasskey(t,r);r.authzToken=s.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,a={}){let s=rt(t,a),o={username:t,txPayload:r,nonce:s.nonce,txType:s.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:o}),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},p=await this.service.tx.txTxComplete({requestBody:d});return A(this.service,this.session),p})}async invokePasskeyApi(t,r){try{return await r()}catch(a){throw a instanceof Error&&new se(this.config.getConfig()).reportError(t,a),a}}},at=Se;var oe=class extends m{constructor(t){super(t)}};K(oe,[m,at,ae,tt,W]);var Ce=oe;var _t=Ce;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
|
@@ -8,7 +8,7 @@ type DeviceInfo = {
|
|
|
8
8
|
/**
|
|
9
9
|
* Client type.
|
|
10
10
|
*/
|
|
11
|
-
clientType?: "browser" | "other";
|
|
11
|
+
clientType?: "browser" | "webview" | "other";
|
|
12
12
|
/**
|
|
13
13
|
* Client version
|
|
14
14
|
*/
|
|
@@ -326,6 +326,10 @@ interface SessionInfo {
|
|
|
326
326
|
* Current authenticated user's ID.
|
|
327
327
|
*/
|
|
328
328
|
id: string;
|
|
329
|
+
/**
|
|
330
|
+
* Relying party ID used typically used for passkey authentication to confirm the user has signed in under the specific domain.
|
|
331
|
+
*/
|
|
332
|
+
rpId: string;
|
|
329
333
|
}
|
|
330
334
|
interface LoginIDTokenSet {
|
|
331
335
|
/**
|
|
@@ -401,20 +405,6 @@ export declare class AbortError extends Error {
|
|
|
401
405
|
*/
|
|
402
406
|
constructor(message: string);
|
|
403
407
|
}
|
|
404
|
-
type User = {
|
|
405
|
-
/**
|
|
406
|
-
* Display Name
|
|
407
|
-
*/
|
|
408
|
-
displayName?: string;
|
|
409
|
-
/**
|
|
410
|
-
* Username
|
|
411
|
-
*/
|
|
412
|
-
username: string;
|
|
413
|
-
/**
|
|
414
|
-
* Username type
|
|
415
|
-
*/
|
|
416
|
-
usernameType: "email" | "phone" | "other";
|
|
417
|
-
};
|
|
418
408
|
type MfaOption = {
|
|
419
409
|
/**
|
|
420
410
|
* Human readable label
|
|
@@ -479,6 +469,20 @@ type Mfa = {
|
|
|
479
469
|
*/
|
|
480
470
|
refreshToken: string;
|
|
481
471
|
};
|
|
472
|
+
type User = {
|
|
473
|
+
/**
|
|
474
|
+
* Display Name
|
|
475
|
+
*/
|
|
476
|
+
displayName?: string;
|
|
477
|
+
/**
|
|
478
|
+
* Username
|
|
479
|
+
*/
|
|
480
|
+
username: string;
|
|
481
|
+
/**
|
|
482
|
+
* Username type
|
|
483
|
+
*/
|
|
484
|
+
usernameType: "email" | "phone" | "other";
|
|
485
|
+
};
|
|
482
486
|
type UsernameType = User["usernameType"];
|
|
483
487
|
type MfaFactorName = MfaAction["action"]["name"];
|
|
484
488
|
type MfaFlow = Mfa["flow"];
|
|
@@ -544,6 +548,41 @@ interface MfaBeginOptions {
|
|
|
544
548
|
* enabling secure transaction confirmation without revealing end-user identity to the merchant.
|
|
545
549
|
*/
|
|
546
550
|
checkoutId?: string;
|
|
551
|
+
/**
|
|
552
|
+
* A unique identifier used to trace and correlate all events associated with a single MFA interaction.
|
|
553
|
+
*
|
|
554
|
+
* This ID is useful for end-to-end observability, logging, and debugging across distributed systems.
|
|
555
|
+
* It can be generated by the client or left unset—if not provided, a secure random ID will be created automatically by LoginID.
|
|
556
|
+
*
|
|
557
|
+
* Example: `6957cf6e-a86c-44fb-b25a-bd97cb9ff830`
|
|
558
|
+
*/
|
|
559
|
+
traceId?: string;
|
|
560
|
+
/**
|
|
561
|
+
* The user's full name used for identity verification during PasskeyID flows.
|
|
562
|
+
*
|
|
563
|
+
* This value is optional but may improve match accuracy when an identity
|
|
564
|
+
* provider is configured (for example, Silent Network Authentication).
|
|
565
|
+
*
|
|
566
|
+
* The name is used only for identity matching purposes and is not treated
|
|
567
|
+
* as a unique account identifier.
|
|
568
|
+
*
|
|
569
|
+
* Recommended format:
|
|
570
|
+
* - Full legal name when available (e.g., `"Jane Doe"`).
|
|
571
|
+
*/
|
|
572
|
+
name?: string;
|
|
573
|
+
/**
|
|
574
|
+
* The user's phone number used for identity verification during PasskeyID flows.
|
|
575
|
+
*
|
|
576
|
+
* Required when using certain identity providers that rely on phone-based
|
|
577
|
+
* verification (for example, Silent Network Authentication).
|
|
578
|
+
*
|
|
579
|
+
* The phone number should be provided in E.164 international format to ensure
|
|
580
|
+
* consistent normalization across providers.
|
|
581
|
+
*
|
|
582
|
+
* Example:
|
|
583
|
+
* - `"+15551234567"`
|
|
584
|
+
*/
|
|
585
|
+
phone?: string;
|
|
547
586
|
}
|
|
548
587
|
interface MfaPerformActionOptions {
|
|
549
588
|
/**
|
|
@@ -564,6 +603,11 @@ interface MfaPerformActionOptions {
|
|
|
564
603
|
* A human-palatable name for the user account, intended only for display on your passkeys..
|
|
565
604
|
*/
|
|
566
605
|
displayName?: string;
|
|
606
|
+
/**
|
|
607
|
+
* An updated transaction payload generated by the merchant to represent the purchase or operation
|
|
608
|
+
* being confirmed. This updates the initial `txPayload` used in the `beginFlow` method.
|
|
609
|
+
*/
|
|
610
|
+
txPayload?: string;
|
|
567
611
|
}
|
|
568
612
|
interface RemainingFactor {
|
|
569
613
|
/**
|
|
@@ -806,6 +850,7 @@ export type Passkey = {
|
|
|
806
850
|
* Timestamp in RFC3339 format.
|
|
807
851
|
*/
|
|
808
852
|
createdAt: string;
|
|
853
|
+
credentialId?: string;
|
|
809
854
|
/**
|
|
810
855
|
* Credential available on multiple devices
|
|
811
856
|
*/
|
|
@@ -1048,6 +1093,12 @@ type MfaThirdPartyAuthVerifyRequestBody = {
|
|
|
1048
1093
|
*/
|
|
1049
1094
|
token: string;
|
|
1050
1095
|
};
|
|
1096
|
+
type MfaPayloadUpdateRequestBody = {
|
|
1097
|
+
/**
|
|
1098
|
+
* Payload to be signed
|
|
1099
|
+
*/
|
|
1100
|
+
payload: string;
|
|
1101
|
+
};
|
|
1051
1102
|
type MfaOtpRequestResponseBody = {
|
|
1052
1103
|
/**
|
|
1053
1104
|
* An opaque session object to be included with the subsequent API call.
|
|
@@ -1073,17 +1124,43 @@ type MfaPasskeyRegRequestBody = {
|
|
|
1073
1124
|
type MfaOtpVerifyRequestBody = {
|
|
1074
1125
|
otp: string;
|
|
1075
1126
|
};
|
|
1127
|
+
type MfaDiscoverRequestBody = {
|
|
1128
|
+
/**
|
|
1129
|
+
* TrustIDs provided with the request
|
|
1130
|
+
*/
|
|
1131
|
+
trustItems: Record<string, string>;
|
|
1132
|
+
};
|
|
1133
|
+
type MfaUser = {
|
|
1134
|
+
/**
|
|
1135
|
+
* Display Name
|
|
1136
|
+
*/
|
|
1137
|
+
displayName?: string;
|
|
1138
|
+
/**
|
|
1139
|
+
* Full name for SNA evaluation
|
|
1140
|
+
*/
|
|
1141
|
+
name?: string;
|
|
1142
|
+
/**
|
|
1143
|
+
* Phone number for SNA evaluation
|
|
1144
|
+
*/
|
|
1145
|
+
phone?: string;
|
|
1146
|
+
username: string;
|
|
1147
|
+
usernameType: string;
|
|
1148
|
+
};
|
|
1076
1149
|
type MfaBeginRequestBody = {
|
|
1077
1150
|
deviceInfo?: DeviceInfo;
|
|
1078
1151
|
/**
|
|
1079
1152
|
* Payload to be signed
|
|
1080
1153
|
*/
|
|
1081
1154
|
payload?: string;
|
|
1155
|
+
/**
|
|
1156
|
+
* A unique id for tracing all events associated with an interaction. A random ID will be generated by the system if not provided.
|
|
1157
|
+
*/
|
|
1158
|
+
traceId?: string;
|
|
1082
1159
|
/**
|
|
1083
1160
|
* TrustIDs provided with the request
|
|
1084
1161
|
*/
|
|
1085
1162
|
trustItems?: Record<string, string>;
|
|
1086
|
-
user?:
|
|
1163
|
+
user?: MfaUser;
|
|
1087
1164
|
};
|
|
1088
1165
|
declare class MfaService {
|
|
1089
1166
|
readonly httpRequest: BaseHttpRequest;
|
|
@@ -1101,6 +1178,15 @@ declare class MfaService {
|
|
|
1101
1178
|
*/
|
|
1102
1179
|
userAgent?: string;
|
|
1103
1180
|
}): CancelablePromise<MfaNext>;
|
|
1181
|
+
/**
|
|
1182
|
+
* Begin and appropriate flow for the provided username.
|
|
1183
|
+
* Perform discovery if trustID and/or checkoutID are known to the system.
|
|
1184
|
+
* @returns void
|
|
1185
|
+
* @throws ApiError
|
|
1186
|
+
*/
|
|
1187
|
+
mfaMfaDiscover({ requestBody, }: {
|
|
1188
|
+
requestBody: MfaDiscoverRequestBody;
|
|
1189
|
+
}): CancelablePromise<void>;
|
|
1104
1190
|
/**
|
|
1105
1191
|
* Request OTP authentication using one of the available methods.
|
|
1106
1192
|
* Request OTP.
|
|
@@ -1166,6 +1252,19 @@ declare class MfaService {
|
|
|
1166
1252
|
*/
|
|
1167
1253
|
authorization?: string;
|
|
1168
1254
|
}): CancelablePromise<Mfa>;
|
|
1255
|
+
/**
|
|
1256
|
+
* Update the payload to be signed using transaction confirmation.
|
|
1257
|
+
* Update the payload to be signed.
|
|
1258
|
+
* @returns MfaNext OK response.
|
|
1259
|
+
* @throws ApiError
|
|
1260
|
+
*/
|
|
1261
|
+
mfaMfaPayloadUpdate({ requestBody, authorization, }: {
|
|
1262
|
+
requestBody: MfaPayloadUpdateRequestBody;
|
|
1263
|
+
/**
|
|
1264
|
+
* JWT Authorization header
|
|
1265
|
+
*/
|
|
1266
|
+
authorization?: string;
|
|
1267
|
+
}): CancelablePromise<MfaNext>;
|
|
1169
1268
|
/**
|
|
1170
1269
|
* Verify auth token created by a third party via management API.
|
|
1171
1270
|
* Verify authentication token received from a third party.
|
|
@@ -1345,7 +1444,7 @@ declare class SessionManager {
|
|
|
1345
1444
|
/**
|
|
1346
1445
|
* Retrieves the currently authenticated user's session information.
|
|
1347
1446
|
*
|
|
1348
|
-
* @returns {
|
|
1447
|
+
* @returns {SessionInfo | null} The currently authenticated session information, including username, id and rpId.
|
|
1349
1448
|
* It will return null if user is not authenticated
|
|
1350
1449
|
*/
|
|
1351
1450
|
getSessionInfo(): SessionInfo | null;
|
|
@@ -1602,6 +1701,7 @@ declare class MFA extends LoginIDBase {
|
|
|
1602
1701
|
* and sets authentication tokens. If the request results in an MFA challenge (401 error),
|
|
1603
1702
|
* it processes the response and updates the session accordingly.
|
|
1604
1703
|
*
|
|
1704
|
+
* @param {MfaFactorName} factorName - The name of the MFA factor being invoked.
|
|
1605
1705
|
* @param {string} appId - The application ID associated with the MFA session.
|
|
1606
1706
|
* @param {string} [username=""] - The username, if available.
|
|
1607
1707
|
* @param {() => Promise<Mfa>} fn - A function that performs the MFA API request.
|
|
@@ -1676,21 +1776,29 @@ export interface PasskeyManagementOptions {
|
|
|
1676
1776
|
}
|
|
1677
1777
|
/**
|
|
1678
1778
|
* List passkeys options.
|
|
1779
|
+
*
|
|
1780
|
+
* @expand
|
|
1679
1781
|
*/
|
|
1680
1782
|
export interface ListPasskeysOptions extends PasskeyManagementOptions {
|
|
1681
1783
|
}
|
|
1682
1784
|
/**
|
|
1683
1785
|
* Rename passkeys options.
|
|
1786
|
+
*
|
|
1787
|
+
* @expand
|
|
1684
1788
|
*/
|
|
1685
1789
|
export interface RenamePasskeyOptions extends PasskeyManagementOptions {
|
|
1686
1790
|
}
|
|
1687
1791
|
/**
|
|
1688
1792
|
* Delete passkeys options.
|
|
1793
|
+
*
|
|
1794
|
+
* @expand
|
|
1689
1795
|
*/
|
|
1690
1796
|
export interface DeletePasskeyOptions extends PasskeyManagementOptions {
|
|
1691
1797
|
}
|
|
1692
1798
|
/**
|
|
1693
1799
|
* Authenticate with passkeys options.
|
|
1800
|
+
*
|
|
1801
|
+
* @expand
|
|
1694
1802
|
*/
|
|
1695
1803
|
export interface AuthenticateWithPasskeysOptions extends MainPasskeyOptions {
|
|
1696
1804
|
/**
|
|
@@ -1705,11 +1813,15 @@ export interface AuthenticateWithPasskeysOptions extends MainPasskeyOptions {
|
|
|
1705
1813
|
}
|
|
1706
1814
|
/**
|
|
1707
1815
|
* Authenticate with passkey autofill options.
|
|
1816
|
+
*
|
|
1817
|
+
* @expand
|
|
1708
1818
|
*/
|
|
1709
1819
|
export interface AuthenticateWithPasskeyAutofillOptions extends AuthenticateWithPasskeysOptions {
|
|
1710
1820
|
}
|
|
1711
1821
|
/**
|
|
1712
1822
|
* Create passkeys options interface.
|
|
1823
|
+
*
|
|
1824
|
+
* @expand
|
|
1713
1825
|
*/
|
|
1714
1826
|
export interface CreatePasskeyOptions extends MainPasskeyOptions {
|
|
1715
1827
|
/**
|
|
@@ -1728,6 +1840,8 @@ export interface CreatePasskeyOptions extends MainPasskeyOptions {
|
|
|
1728
1840
|
}
|
|
1729
1841
|
/**
|
|
1730
1842
|
* Confirm transaction options.
|
|
1843
|
+
*
|
|
1844
|
+
* @expand
|
|
1731
1845
|
*/
|
|
1732
1846
|
export interface ConfirmTransactionOptions extends MainPasskeyOptions {
|
|
1733
1847
|
/**
|
|
@@ -1741,6 +1855,8 @@ export interface ConfirmTransactionOptions extends MainPasskeyOptions {
|
|
|
1741
1855
|
}
|
|
1742
1856
|
/**
|
|
1743
1857
|
* Request and send OTP options.
|
|
1858
|
+
*
|
|
1859
|
+
* @expand
|
|
1744
1860
|
*/
|
|
1745
1861
|
export interface RequestAndSendOtpOptions {
|
|
1746
1862
|
/**
|
|
@@ -1750,11 +1866,15 @@ export interface RequestAndSendOtpOptions {
|
|
|
1750
1866
|
}
|
|
1751
1867
|
/**
|
|
1752
1868
|
* Request OTP options.
|
|
1869
|
+
*
|
|
1870
|
+
* @expand
|
|
1753
1871
|
*/
|
|
1754
1872
|
export interface RequestOtpOptions extends AuthenticateWithPasskeyAutofillOptions {
|
|
1755
1873
|
}
|
|
1756
1874
|
/**
|
|
1757
1875
|
* Validate OTP options.
|
|
1876
|
+
*
|
|
1877
|
+
* @expand
|
|
1758
1878
|
*/
|
|
1759
1879
|
export interface ValidateOtpOptions extends RequestAndSendOtpOptions {
|
|
1760
1880
|
}
|
|
@@ -1787,7 +1907,7 @@ export interface AuthResult {
|
|
|
1787
1907
|
* An identifier for the device used in the authentication process. This property helps determine if supported authentications can be proceeded,
|
|
1788
1908
|
* allowing future authentications to identify the device correctly.
|
|
1789
1909
|
*/
|
|
1790
|
-
|
|
1910
|
+
deviceId?: string;
|
|
1791
1911
|
/**
|
|
1792
1912
|
* If **`true`**, the authentication process should resort to a fallback method as specified in **`fallbackOptions`**.
|
|
1793
1913
|
*/
|
|
@@ -2134,7 +2254,7 @@ declare class Passkeys extends OTP {
|
|
|
2134
2254
|
* @param {AuthenticateWithPasskeyAutofillOptions} options Additional authentication options.
|
|
2135
2255
|
* @returns {Promise<AuthResult>} Result of the passkey authentication operation.
|
|
2136
2256
|
* @example
|
|
2137
|
-
*
|
|
2257
|
+
* import { isConditionalUIAvailable, LoginIDWebSDK } from "@loginid/websdk3";
|
|
2138
2258
|
*
|
|
2139
2259
|
* // Obtain credentials from LoginID
|
|
2140
2260
|
* const BASE_URL = process.env.BASE_URL;
|
|
@@ -2216,7 +2336,7 @@ declare class Passkeys extends OTP {
|
|
|
2216
2336
|
* or changes to sensitive account information, ensuring that the transaction is being authorized
|
|
2217
2337
|
* by the rightful owner of the passkey.
|
|
2218
2338
|
*
|
|
2219
|
-
* For a more detailed guide click [here](https://docs.loginid.io/
|
|
2339
|
+
* For a more detailed guide click [here](https://docs.loginid.io/user-scenario/authentication/step-up/transaction-confirmation/).
|
|
2220
2340
|
*
|
|
2221
2341
|
* @param {string} username The username of the user confirming the transaction.
|
|
2222
2342
|
* @param {string} txPayload The transaction-specific payload, which could include details
|
package/dist/index.global.js
CHANGED
|
@@ -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:()=>D,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>R,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 D=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}},d=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};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},k=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 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)},$=()=>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}},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 J(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 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: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))})})},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)},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),c=await Rt(l),p=kt(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: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,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}},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 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),_(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 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||$()}),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 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 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 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 R.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 R.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 R.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);})();
|
|
1
|
+
"use strict";var LoginID=(()=>{var ie=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var lt=(e,t)=>{for(var r in t)ie(e,r,{get:t[r],enumerable:!0})},dt=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nt(t))!ut.call(e,s)&&s!==r&&ie(e,s,{get:()=>t[s],enumerable:!(a=it(t,s))||a.enumerable});return e};var ct=e=>dt(ie({},"__esModule",{value:!0}),e);var Nt={};lt(Nt,{AbortError:()=>U,ApiError:()=>T,LoginIDMfa:()=>et,LoginIDWebSDK:()=>Ce,PasskeyError:()=>h,WebAuthnHelper:()=>R,createPasskeyCredential:()=>Y,default:()=>_t,getPasskeyCredential:()=>X,isConditionalUIAvailable:()=>V,isPlatformAuthenticatorAvailable:()=>$});var b=class ne{logLevel;static createDefault(){let t=process.env.NODE_ENV==="production"?4:0;return new ne(t)}static logger=ne.createDefault();constructor(t=2){this.logLevel=t}debug(t){this.logLevel<=0&&console.debug(`[DEBUG] ${t}`)}info(t){this.logLevel<=1&&console.info(`[INFO] ${t}`)}warn(t){this.logLevel<=2&&console.warn(`[WARN] ${t}`)}error(t){this.logLevel<=3&&console.error(`[ERROR] ${t}`)}get level(){return this.logLevel}},v=async e=>{let t=JSON.stringify(await Pe()),r=await qe(),a={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(a.deviceId=e),a},$=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},V=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Pe=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await $(),t=await V();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},ue=async(e,t,r)=>{try{if(!window.PublicKeyCredential){b.logger.debug("PublicKeyCredential is not available.");return}if(!window.PublicKeyCredential.signalAllAcceptedCredentials){b.logger.debug("signalAllAcceptedCredentials is not available.");return}await window.PublicKeyCredential.signalAllAcceptedCredentials({rpId:e,userId:t,allAcceptedCredentialIds:r})}catch(a){b.logger.debug(`Error at signalAllAcceptedCredentials: ${a}`);return}},le=async(e,t)=>{try{if(!window.PublicKeyCredential){b.logger.debug("PublicKeyCredential is not available.");return}if(!window.PublicKeyCredential.signalUnknownCredential){b.logger.debug("signalUnknownCredential is not available.");return}await window.PublicKeyCredential.signalUnknownCredential({rpId:e,credentialId:t})}catch(r){b.logger.debug(`Error at signalUnknownCredential: ${r}`);return}},qe=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},J=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},de=e=>{document.cookie=e},O=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}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}},U=class extends Error{constructor(e){super(e),this.name="AbortError"}};var z=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),L=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],a=0;for(;a<e.length;){let i=e.charCodeAt(a++),n=e.charCodeAt(a++),u=e.charCodeAt(a++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let s=r.join(""),o=e.length%3;return o?s.slice(0,o-3)+"===".slice(o||3):s},xe=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},a=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let s=0,o=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(s=(s<<6)+u,o+=6;o>=8;)i+=a(s>>(o-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)t+=String.fromCharCode(r[s]);let a=L(t);return z(a)},E=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=xe(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++)r[a]=t.charCodeAt(a);return r.buffer},w=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(a=>"%"+("00"+a.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},ce=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let a=0;a<e;a++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},G=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),S=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),pe=async(e,t)=>{let r=new TextEncoder().encode(t),a=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(a)},_e=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},H=()=>window.crypto?.randomUUID?window.crypto.randomUUID():_e(24);var C=class x{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new U("Cancelling current WebAuthn request");x.abortController.abort(t)};static renewWebAuthnAbortController=()=>{x.abortWebAuthnRequest();let t=new AbortController;x.abortController=t};static assignWebAuthnAbortController=t=>{x.abortWebAuthnRequest(),x.abortController=t}},Ne=(e,t)=>{let r=e.name,{publicKey:a}=t;if(r==="ConstraintError"){if(a?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(a?.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 s=a?.rp?.id;if(s!==window.location.hostname)return new h(`The domain of the relying party (${s}) 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},De=(e,t)=>{let r=e.name,{publicKey:a}=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 s=a?.rpId;if(s!==window.location.hostname)return new h(`The domain of the relying party (${s}) 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},pt=new y("User needs to be logged in to perform this operation."),he=new y("No login options available."),Y=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let s of e.excludeCredentials){let o={id:E(s.id),transports:s.transports,type:s.type};t.push(o)}}let r=e.pubKeyCredParams,a={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:E(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:E(e.user.id)}}};try{let s=await navigator.credentials.create(a);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?Ne(s,a):s}},X=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let s of e.allowCredentials){let o={id:E(s.id),transports:s.transports,type:s.type};r.push(o)}}let a={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:E(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let s=await navigator.credentials.get(a);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?De(s,a):s}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:a}=e;t.abortController?C.assignWebAuthnAbortController(t.abortController):(C.renewWebAuthnAbortController(),t.abortController=C.abortController);let s=await X(r,t),o=s.response;return{assertionResult:{authenticatorData:k(o.authenticatorData),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,signature:k(o.signature),...o.userHandle&&{userHandle:k(o.userHandle)}},session:a}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;C.renewWebAuthnAbortController();let a=await Y(t),s=a.response,o=s.getPublicKey&&s.getPublicKey(),i=s.getPublicKeyAlgorithm&&s.getPublicKeyAlgorithm(),n=s.getAuthenticatorData&&s.getAuthenticatorData(),u=s.getTransports&&s.getTransports();return{creationResult:{attestationObject:k(s.attestationObject),clientDataJSON:k(s.clientDataJSON),credentialId:a.id,...o&&{publicKey:k(o)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var A=async(e,t)=>{try{if(!t.getSessionInfo()){b.logger.debug("No session info available for syncing passkeys.");return}let r=t.getToken({}),a=await e.passkeys.passkeysPasskeysList({authorization:r});await Q(a,t)}catch(r){b.logger.debug(`Error fetching and syncing passkeys: ${r}`)}},Q=async(e,t)=>{try{let r=t.getSessionInfo();if(!r){b.logger.debug("No session info available for syncing passkeys.");return}let{id:a,rpId:s}=r,o=e.map(i=>i.credentialId).filter(Boolean);await ue(s,a,o)}catch(r){b.logger.debug(`Error syncing passkeys: ${r}`)}},M=async(e,t)=>{try{if(!e||!t){b.logger.debug("Credential ID or RP ID is missing.");return}await le(t,e)}catch(r){b.logger.debug(`Error signaling unknown credential: ${r}`)}};var K=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(a=>{Object.defineProperty(e.prototype,a,Object.getOwnPropertyDescriptor(r.prototype,a)||Object.create(null))})})},_=e=>(e||(e=ce()),{id:e,exp:Math.floor(Date.now()/1e3)+60}),P=async(e,t,r)=>{let a=z(L(JSON.stringify({alg:"ES256",jwk:t}))),s=z(L(JSON.stringify(e))),o=`${a}.${s}`,i=await pe(r,o);return`${o}.${i}`};var me=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 ge=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,a=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=a}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:a,keyPath:s,options:o})=>r.createIndex(a,s,o))}},e}async getAllByIndex(e,t){return new Promise((r,a)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);o.onsuccess=()=>{r(o.result)},o.onerror=()=>a(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>a(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,a)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);o.onsuccess=()=>{let i=o.result;i?r(i):a(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},o.onerror=()=>a(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>a(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 a=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();a.onsuccess=()=>{let s=a.result;s?e(s.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},a.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 a=this.openDb();a.onsuccess=()=>{let s=a.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);s.onsuccess=()=>t(),s.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},a.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let a=this.openDb();a.onsuccess=()=>{let s=a.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);s.onsuccess=()=>t(),s.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},a.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ht=1;var yt="lid_c_wtid",ft="lid-wtid-k",Le=class extends ge{constructor(e,t){super(e,ht,t)}async setCheckoutId(){let e=await G(),t=await S(e),r=_(),a=await P(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),a}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await S(e.keyPair),r={id:e.id};return await P(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 S(e.keyPair),r=_(e.id);return await P(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 be=class extends Le{constructor(){super(yt,ft)}},mt=1,Be="app_id_idx",gt="username_idx",bt="loginid-trust-store",kt="LoginID_trust-id",ye="app_id_username_idx",N=class extends ge{appId;constructor(e){super(bt,mt,kt,[{name:gt,keyPath:["username"]},{name:Be,keyPath:["appId"]},{name:ye,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await G(),r=await S(t),a=_(),s=await P(a,r,t.privateKey);return await this.putRecord({id:a.id,appId:this.appId,username:e,keyPair:t}),s}async signWithTrustId(e){let t=await this.getByIndex(ye,[this.appId,e]),r=await S(t.keyPair),a=_(t.id);return await P(a,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(Be,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ye,[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)}}},Fe=e=>`LoginID_${e}_mfa-session`,f=class fe extends me{static persistInfo(t,r){this.setItem(Fe(t),r)}static getInfo(t){return this.getItem(Fe(t))}static updateSession(t,r){let a=fe.getInfo(t);a?a.session=r:a={session:r},fe.persistInfo(t,a)}},Z=(e,t)=>`LoginID_${e}_${t}`,Ue="device-id",ze="rp-id",I=class extends me{static persistDeviceId(e,t){this.setItem(Z(e,Ue),t)}static getDeviceId(e){return this.getItem(Z(e,Ue))||""}static persistRpId(e,t){this.setItem(Z(e,ze),t)}static getRpId(e){return this.getItem(Z(e,ze))}};var Me=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."}})}},Ke=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."}})}},je=class{constructor(e){this.config=e}},We=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},$e=class{#t;#r;#e;#s;#o;#i;#a;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#o=new Promise((t,r)=>{this.#i=t,this.#a=r;let a=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},s=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#a&&this.#a(i))},o=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(o,"isResolved",{get:()=>this.#t}),Object.defineProperty(o,"isRejected",{get:()=>this.#r}),Object.defineProperty(o,"isCancelled",{get:()=>this.#e}),e(a,s,o)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#o.then(e,t)}catch(e){return this.#o.catch(e)}finally(e){return this.#o.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.#a&&this.#a(new We("Request aborted"))}}get isCancelled(){return this.#e}},T=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}},Re=e=>e!=null,j=e=>typeof e=="string",ke=e=>j(e)&&e!=="",we=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]),Ve=e=>e instanceof FormData,Rt=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},wt=e=>{let t=[],r=(s,o)=>{t.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(o))}`)},a=(s,o)=>{Re(o)&&(Array.isArray(o)?o.forEach(i=>{a(s,i)}):typeof o=="object"?Object.entries(o).forEach(([i,n])=>{a(`${s}[${i}]`,n)}):r(s,o))};return Object.entries(e).forEach(([s,o])=>{a(s,o)}),t.length>0?`?${t.join("&")}`:""},It=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,a=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(o,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):o),s=`${e.BASE}${a}`;return t.query?`${s}${wt(t.query)}`:s},At=e=>{if(e.formData){let t=new FormData,r=(a,s)=>{j(s)||we(s)?t.append(a,s):t.append(a,JSON.stringify(s))};return Object.entries(e.formData).filter(([a,s])=>Re(s)).forEach(([a,s])=>{Array.isArray(s)?s.forEach(o=>r(a,o)):r(a,s)}),t}},ee=async(e,t)=>typeof t=="function"?t(e):t,Tt=async(e,t)=>{let[r,a,s,o]=await Promise.all([ee(t,e.TOKEN),ee(t,e.USERNAME),ee(t,e.PASSWORD),ee(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...o,...t.headers}).filter(([n,u])=>Re(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(ke(r)&&(i.Authorization=`Bearer ${r}`),ke(a)&&ke(s)){let n=Rt(`${a}:${s}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:we(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":j(t.body)?i["Content-Type"]="text/plain":Ve(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},vt=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):j(e.body)||we(e.body)||Ve(e.body)?e.body:JSON.stringify(e.body)},Ot=async(e,t,r,a,s,o,i)=>{let n=new AbortController,u={headers:o,body:a??s,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},Et=(e,t)=>{if(t){let r=e.headers.get(t);if(j(r))return r}},St=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)}},Ct=(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 T(e,t,r);if(!t.ok){let a=t.status??"unknown",s=t.statusText??"unknown",o=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new T(e,t,`Generic Error: status: ${a}; status text: ${s}; body: ${o}`)}},Pt=(e,t)=>new $e(async(r,a,s)=>{try{let o=It(e,t),i=At(t),n=vt(t),u=await Tt(e,t);if(!s.isCancelled){let l=await Ot(e,t,o,n,i,u,s),d=await St(l),p=Et(l,t.responseHeader),g={url:o,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};Ct(t,g),r(g.body)}}catch(o){a(o)}}),qt=class extends je{constructor(e){super(e)}request(e){return Pt(this.config,e)}},Je=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."}})}},Ge=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."}})}mfaMfaDiscover({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/discover",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."}})}mfaMfaPayloadUpdate({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/payload",headers:{Authorization:t},body:e,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."}})}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."}})}},He=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."}})}},Ye=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."}})}},Ie=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=qt){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 Je(this.request),this.clientEvents=new Me(this.request),this.mfa=new Ge(this.request),this.passkeys=new Ke(this.request),this.reg=new He(this.request),this.tx=new Ye(this.request)}};var Xe=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),te=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),D=(e,t)=>{let r=e?.next?.map(s=>{let{name:o,label:i,desc:n}=s.action,u={type:o,label:i,...n&&{description:n}};if(s.options){let l=s.options.filter(d=>(o==="otp:sms"||o==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),o==="passkey:reg"||o==="passkey:auth"||o==="passkey:tx"){let d=s.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],a=["passkey:reg","passkey:auth","passkey:tx","otp:sms","otp:email","external"].find(s=>e?.next?.some(o=>o.action.name===s));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...a&&{nextAction:a},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 re=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}},Te=class Ae{static mfaOptionValidator(t,r,a){let{session:s=r?.session,payload:o=""}=a;if(!s)throw new y("A session is required to perform MFA factor.");if(o)return{session:s,payload:o};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:s,payload:u(n)};case"otp:email":return{session:s,payload:u(n,"email:primary")};case"otp:sms":return{session:s,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=w("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(Ae.isPublicKeyCredentialCreationOptions(r)||Ae.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 Qe=class{config;constructor(e){this.config=new re(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||this.retrieveToken("accessToken")||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=w(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub,rpId:e.rpId}}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=w(e),r=new Date(t.exp*1e3).toUTCString(),a=`${this.getJwtCookieName()}=${e}; expires=${r}`;de(a)}getJwtCookie(){return J(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){O(this.getJwtCookieName()),O(this.getIdTokenName()),O(this.getAccessTokenName()),O(this.getRefreshTokenName()),O(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:a,refreshToken:s}=e,o=(i,n)=>{if(!n)return;let u=w(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};o(this.getIdTokenName(),r),o(this.getAccessTokenName(),t),o(this.getRefreshTokenName(),s),o(this.getPayloadSignatureName(),a)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return J(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var m=class{config;service;session;constructor(e){this.config=new re(e),this.service=new Ie({BASE:e.baseUrl}),this.session=new Qe(e)}},W=class extends m{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 v(),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 T&&(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(),f.persistInfo(e,{next:[]})}},xt=new Set(["ERROR_PASSKEY_ABORTED"]),se=class extends m{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof h){if(xt.has(t.code))return{session:""};let a=t.cause,s=`${t.code} - ${t.message} - ${a.name} - ${a.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:s}})}}},ve=class extends m{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),a=I.getDeviceId(r),s=await v(a),o=Xe(e,t),i="";t.txPayload&&(i=await new be().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new N(r).setOrSignWithTrustId(e));let u={deviceInfo:s,user:{username:e,usernameType:o.usernameType,displayName:o.displayName,...t.name&&{name:t.name},...t.phone&&{name:t.phone}},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}),d=te(l,e);return f.persistInfo(r,d),this.session.logout(),D(d)}async performAction(e,t={}){let r=this.config.getAppId(),a=f.getInfo(r),{payload:s,session:o}=Te.mfaOptionValidator(e,a,t);if(e==="passkey:tx"&&t.txPayload){let{txPayload:i,...n}=t,u=await this.service.mfa.mfaMfaPayloadUpdate({authorization:o,requestBody:{payload:i}}),l=a?.username,d=te(u,l);return f.persistInfo(r,d),await this.performAction(e,n)}switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=Te.validatePasskeyPayload(s);if("rpId"in i)return await this.invokeMfaApi(e,r,a?.username,async()=>{let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:o},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:o,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:o,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(e,r,a?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:o});try{return await this.service.mfa.mfaMfaPasskeyReg({authorization:o,requestBody:{creationResult:n.creationResult}})}catch(u){throw M(n.creationResult.credentialId,i.rp.id),u}});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:o,requestBody:{method:e==="otp:email"?"email":"sms",option:s}});return f.updateSession(r,i),D(f.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(e,r,a?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:o,requestBody:{otp:s}}));case"external":return await this.invokeMfaApi(e,r,a?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:o,requestBody:{token:s}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=f.getInfo(e),r=this.session.getTokenSet();return D(t,r)}async invokeMfaApi(e,t,r="",a){try{let s=await a(),o=f.getInfo(t);f.persistInfo(t,{...r&&{username:r},flow:o?.flow,next:[]}),this.session.setTokenSet(s),I.persistDeviceId(t,s.deviceId);let i=f.getInfo(t);return(e==="passkey:auth"||e==="passkey:tx")&&A(this.service,this.session),D(i,s)}catch(s){if(s instanceof T&&s.status===401&&s.body.session){let o=s.body,i=te(o,r);return f.persistInfo(t,i),D(i)}if(s instanceof Error){let o=new se(this.config.getConfig()),i=this.config.getAppId(),n=f.getInfo(i);n?.session&&o.reportError(n.session,s).then(u=>{u?.session&&f.updateSession(i,u.session)})}throw s}}};var Ze=class extends m{constructor(e){super(e)}};K(Ze,[m,ve,W]);var et=Ze;var Oe=class extends m{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t),a=await this.service.passkeys.passkeysPasskeysList({authorization:r});return Q(a,this.session),a}async renamePasskey(t,r,a={}){let s=this.session.getToken(a),o={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:s,id:t,requestBody:o})}async deletePasskey(t,r={}){let a=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:a,id:t}),A(this.service,this.session)}},tt=Oe;var q=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),rt=(e,t)=>({...q(e,"",t),txType:t.txType||"raw",nonce:t.nonce||H()}),B=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,deviceId:e.deviceId,isAuthenticated:t,isFallback:r});var st=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Ee=class extends m{constructor(t){super(t)}async validateOtp(t,r,a={}){let s=q(t,"",a),o={authCode:r,user:{username:t,usernameType:s.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:o}),n=B(i);return C.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",a={}){let s=q(t,"",a),o={user:{username:t,usernameType:s.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:o});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:o});break;default:throw new Error("Invalid message method")}}},ae=Ee;var Se=class extends ae{constructor(t){super(t)}async createPasskey(t,r="",a={}){let s=this.config.getAppId(),o=I.getDeviceId(s),i=await v(o),n=new N(s),u=q(t,r,a);u.authzToken=this.session.getToken(u),u.authzToken&&w(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:s},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...a.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);a.passkeyName&&(g.passkeyName=a.passkeyName);try{let F=await this.service.reg.regRegComplete({requestBody:g}),ot=B(F);return this.session.setJwtCookie(F.jwtAccess),I.persistDeviceId(s,o||F.deviceId),ot}catch(F){throw M(g.creationResult.credentialId,p.registrationRequestOptions.rp.id),F}})}async authenticateWithPasskey(t="",r={}){let a=this.config.getAppId(),s=await v(I.getDeviceId(a)),o=new N(a),i=q(t,"",r),n=await o.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:a},deviceInfo:s,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});A(this.service,this.session);let g=B(p);return this.session.setJwtCookie(g.token),I.persistDeviceId(a,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=st(l);await i.callbacks.onFallback(t,p)}return B({userId:"",jwtAccess:""},!1,!0)}default:throw he}}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 s=await this.authenticateWithPasskey(t,r);r.authzToken=s.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,a={}){let s=rt(t,a),o={username:t,txPayload:r,nonce:s.nonce,txType:s.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:o}),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},p=await this.service.tx.txTxComplete({requestBody:d});return A(this.service,this.session),p})}async invokePasskeyApi(t,r){try{return await r()}catch(a){throw a instanceof Error&&new se(this.config.getConfig()).reportError(t,a),a}}},at=Se;var oe=class extends m{constructor(t){super(t)}};K(oe,[m,at,ae,tt,W]);var Ce=oe;var _t=Ce;return ct(Nt);})();
|
|
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}},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 L=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}},d=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},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=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},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)},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: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))})})},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: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,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=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 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=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 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=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 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}},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 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 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 x(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),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=Re;var G=class extends f{constructor(t){super(t)}};F(G,[f,Ve,J,Ke,z]);var Je=G;var po=Je;export{L 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 b=class re{logLevel;static createDefault(){let t=process.env.NODE_ENV==="production"?4:0;return new re(t)}static logger=re.createDefault();constructor(t=2){this.logLevel=t}debug(t){this.logLevel<=0&&console.debug(`[DEBUG] ${t}`)}info(t){this.logLevel<=1&&console.info(`[INFO] ${t}`)}warn(t){this.logLevel<=2&&console.warn(`[WARN] ${t}`)}error(t){this.logLevel<=3&&console.error(`[ERROR] ${t}`)}get level(){return this.logLevel}},T=async e=>{let t=JSON.stringify(await Se()),r=await Ce(),a={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(a.deviceId=e),a},se=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},ae=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Se=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await se(),t=await ae();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},oe=async(e,t,r)=>{try{if(!window.PublicKeyCredential){b.logger.debug("PublicKeyCredential is not available.");return}if(!window.PublicKeyCredential.signalAllAcceptedCredentials){b.logger.debug("signalAllAcceptedCredentials is not available.");return}await window.PublicKeyCredential.signalAllAcceptedCredentials({rpId:e,userId:t,allAcceptedCredentialIds:r})}catch(a){b.logger.debug(`Error at signalAllAcceptedCredentials: ${a}`);return}},ie=async(e,t)=>{try{if(!window.PublicKeyCredential){b.logger.debug("PublicKeyCredential is not available.");return}if(!window.PublicKeyCredential.signalUnknownCredential){b.logger.debug("signalUnknownCredential is not available.");return}await window.PublicKeyCredential.signalUnknownCredential({rpId:e,credentialId:t})}catch(r){b.logger.debug(`Error at signalUnknownCredential: ${r}`);return}},Ce=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},W=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},ne=e=>{document.cookie=e},v=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}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}},$=class extends Error{constructor(e){super(e),this.name="AbortError"}};var U=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),z=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],a=0;for(;a<e.length;){let i=e.charCodeAt(a++),n=e.charCodeAt(a++),u=e.charCodeAt(a++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let s=r.join(""),o=e.length%3;return o?s.slice(0,o-3)+"===".slice(o||3):s},Pe=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},a=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let s=0,o=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(s=(s<<6)+u,o+=6;o>=8;)i+=a(s>>(o-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)t+=String.fromCharCode(r[s]);let a=z(t);return U(a)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Pe(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++)r[a]=t.charCodeAt(a);return r.buffer},R=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(a=>"%"+("00"+a.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},ue=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let a=0;a<e;a++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},V=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),E=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),le=async(e,t)=>{let r=new TextEncoder().encode(t),a=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(a)},qe=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},J=()=>window.crypto?.randomUUID?window.crypto.randomUUID():qe(24);var S=class x{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new $("Cancelling current WebAuthn request");x.abortController.abort(t)};static renewWebAuthnAbortController=()=>{x.abortWebAuthnRequest();let t=new AbortController;x.abortController=t};static assignWebAuthnAbortController=t=>{x.abortWebAuthnRequest(),x.abortController=t}},xe=(e,t)=>{let r=e.name,{publicKey:a}=t;if(r==="ConstraintError"){if(a?.authenticatorSelection?.requireResidentKey===!0)return new y("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(a?.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 s=a?.rp?.id;if(s!==window.location.hostname)return new y(`The domain of the relying party (${s}) 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},_e=(e,t)=>{let r=e.name,{publicKey:a}=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 s=a?.rpId;if(s!==window.location.hostname)return new y(`The domain of the relying party (${s}) 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},at=new h("User needs to be logged in to perform this operation."),de=new h("No login options available."),ce=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let s of e.excludeCredentials){let o={id:O(s.id),transports:s.transports,type:s.type};t.push(o)}}let r=e.pubKeyCredParams,a={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 s=await navigator.credentials.create(a);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?xe(s,a):s}},pe=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let s of e.allowCredentials){let o={id:O(s.id),transports:s.transports,type:s.type};r.push(o)}}let a={...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 s=await navigator.credentials.get(a);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?_e(s,a):s}},w=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:a}=e;t.abortController?S.assignWebAuthnAbortController(t.abortController):(S.renewWebAuthnAbortController(),t.abortController=S.abortController);let s=await pe(r,t),o=s.response;return{assertionResult:{authenticatorData:k(o.authenticatorData),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,signature:k(o.signature),...o.userHandle&&{userHandle:k(o.userHandle)}},session:a}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;S.renewWebAuthnAbortController();let a=await ce(t),s=a.response,o=s.getPublicKey&&s.getPublicKey(),i=s.getPublicKeyAlgorithm&&s.getPublicKeyAlgorithm(),n=s.getAuthenticatorData&&s.getAuthenticatorData(),u=s.getTransports&&s.getTransports();return{creationResult:{attestationObject:k(s.attestationObject),clientDataJSON:k(s.clientDataJSON),credentialId:a.id,...o&&{publicKey:k(o)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var A=async(e,t)=>{try{if(!t.getSessionInfo()){b.logger.debug("No session info available for syncing passkeys.");return}let r=t.getToken({}),a=await e.passkeys.passkeysPasskeysList({authorization:r});await G(a,t)}catch(r){b.logger.debug(`Error fetching and syncing passkeys: ${r}`)}},G=async(e,t)=>{try{let r=t.getSessionInfo();if(!r){b.logger.debug("No session info available for syncing passkeys.");return}let{id:a,rpId:s}=r,o=e.map(i=>i.credentialId).filter(Boolean);await oe(s,a,o)}catch(r){b.logger.debug(`Error syncing passkeys: ${r}`)}},L=async(e,t)=>{try{if(!e||!t){b.logger.debug("Credential ID or RP ID is missing.");return}await ie(t,e)}catch(r){b.logger.debug(`Error signaling unknown credential: ${r}`)}};var M=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(a=>{Object.defineProperty(e.prototype,a,Object.getOwnPropertyDescriptor(r.prototype,a)||Object.create(null))})})},_=e=>(e||(e=ue()),{id:e,exp:Math.floor(Date.now()/1e3)+60}),C=async(e,t,r)=>{let a=U(z(JSON.stringify({alg:"ES256",jwk:t}))),s=U(z(JSON.stringify(e))),o=`${a}.${s}`,i=await le(r,o);return`${o}.${i}`};var fe=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 me=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,a=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=a}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:a,keyPath:s,options:o})=>r.createIndex(a,s,o))}},e}async getAllByIndex(e,t){return new Promise((r,a)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);o.onsuccess=()=>{r(o.result)},o.onerror=()=>a(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>a(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,a)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);o.onsuccess=()=>{let i=o.result;i?r(i):a(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},o.onerror=()=>a(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>a(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 a=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();a.onsuccess=()=>{let s=a.result;s?e(s.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},a.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 a=this.openDb();a.onsuccess=()=>{let s=a.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);s.onsuccess=()=>t(),s.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},a.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let a=this.openDb();a.onsuccess=()=>{let s=a.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);s.onsuccess=()=>t(),s.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},a.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var it="lid_c_wtid",nt="lid-wtid-k",Ue=class extends me{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await V(),t=await E(e),r=_(),a=await C(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),a}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await E(e.keyPair),r={id:e.id};return await C(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 E(e.keyPair),r=_(e.id);return await C(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 ge=class extends Ue{constructor(){super(it,nt)}},ut=1,Ne="app_id_idx",lt="username_idx",dt="loginid-trust-store",ct="LoginID_trust-id",he="app_id_username_idx",N=class extends me{appId;constructor(e){super(dt,ut,ct,[{name:lt,keyPath:["username"]},{name:Ne,keyPath:["appId"]},{name:he,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await V(),r=await E(t),a=_(),s=await C(a,r,t.privateKey);return await this.putRecord({id:a.id,appId:this.appId,username:e,keyPair:t}),s}async signWithTrustId(e){let t=await this.getByIndex(he,[this.appId,e]),r=await E(t.keyPair),a=_(t.id);return await C(a,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(Ne,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(he,[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)}}},De=e=>`LoginID_${e}_mfa-session`,f=class ye extends fe{static persistInfo(t,r){this.setItem(De(t),r)}static getInfo(t){return this.getItem(De(t))}static updateSession(t,r){let a=ye.getInfo(t);a?a.session=r:a={session:r},ye.persistInfo(t,a)}},H=(e,t)=>`LoginID_${e}_${t}`,Be="device-id",Fe="rp-id",I=class extends fe{static persistDeviceId(e,t){this.setItem(H(e,Be),t)}static getDeviceId(e){return this.getItem(H(e,Be))||""}static persistRpId(e,t){this.setItem(H(e,Fe),t)}static getRpId(e){return this.getItem(H(e,Fe))}};var ze=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."}})}},Le=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."}})}},Me=class{constructor(e){this.config=e}},Ke=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},je=class{#t;#r;#e;#s;#o;#i;#a;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#o=new Promise((t,r)=>{this.#i=t,this.#a=r;let a=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},s=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#a&&this.#a(i))},o=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(o,"isResolved",{get:()=>this.#t}),Object.defineProperty(o,"isRejected",{get:()=>this.#r}),Object.defineProperty(o,"isCancelled",{get:()=>this.#e}),e(a,s,o)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#o.then(e,t)}catch(e){return this.#o.catch(e)}finally(e){return this.#o.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.#a&&this.#a(new Ke("Request aborted"))}}get isCancelled(){return this.#e}},P=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}},ke=e=>e!=null,K=e=>typeof e=="string",be=e=>K(e)&&e!=="",Re=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]),We=e=>e instanceof FormData,pt=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},ht=e=>{let t=[],r=(s,o)=>{t.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(o))}`)},a=(s,o)=>{ke(o)&&(Array.isArray(o)?o.forEach(i=>{a(s,i)}):typeof o=="object"?Object.entries(o).forEach(([i,n])=>{a(`${s}[${i}]`,n)}):r(s,o))};return Object.entries(e).forEach(([s,o])=>{a(s,o)}),t.length>0?`?${t.join("&")}`:""},yt=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,a=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(o,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):o),s=`${e.BASE}${a}`;return t.query?`${s}${ht(t.query)}`:s},ft=e=>{if(e.formData){let t=new FormData,r=(a,s)=>{K(s)||Re(s)?t.append(a,s):t.append(a,JSON.stringify(s))};return Object.entries(e.formData).filter(([a,s])=>ke(s)).forEach(([a,s])=>{Array.isArray(s)?s.forEach(o=>r(a,o)):r(a,s)}),t}},Y=async(e,t)=>typeof t=="function"?t(e):t,mt=async(e,t)=>{let[r,a,s,o]=await Promise.all([Y(t,e.TOKEN),Y(t,e.USERNAME),Y(t,e.PASSWORD),Y(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...o,...t.headers}).filter(([n,u])=>ke(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(be(r)&&(i.Authorization=`Bearer ${r}`),be(a)&&be(s)){let n=pt(`${a}:${s}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:Re(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":K(t.body)?i["Content-Type"]="text/plain":We(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},gt=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):K(e.body)||Re(e.body)||We(e.body)?e.body:JSON.stringify(e.body)},bt=async(e,t,r,a,s,o,i)=>{let n=new AbortController,u={headers:o,body:a??s,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(K(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)}},wt=(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 P(e,t,r);if(!t.ok){let a=t.status??"unknown",s=t.statusText??"unknown",o=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new P(e,t,`Generic Error: status: ${a}; status text: ${s}; body: ${o}`)}},It=(e,t)=>new je(async(r,a,s)=>{try{let o=yt(e,t),i=ft(t),n=gt(t),u=await mt(e,t);if(!s.isCancelled){let l=await bt(e,t,o,n,i,u,s),d=await Rt(l),p=kt(l,t.responseHeader),g={url:o,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};wt(t,g),r(g.body)}}catch(o){a(o)}}),At=class extends Me{constructor(e){super(e)}request(e){return It(this.config,e)}},$e=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."}})}},Ve=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."}})}mfaMfaDiscover({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/discover",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."}})}mfaMfaPayloadUpdate({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/payload",headers:{Authorization:t},body:e,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."}})}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."}})}},Je=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."}})}},Ge=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."}})}},we=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 $e(this.request),this.clientEvents=new ze(this.request),this.mfa=new Ve(this.request),this.passkeys=new Le(this.request),this.reg=new Je(this.request),this.tx=new Ge(this.request)}};var He=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),X=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),D=(e,t)=>{let r=e?.next?.map(s=>{let{name:o,label:i,desc:n}=s.action,u={type:o,label:i,...n&&{description:n}};if(s.options){let l=s.options.filter(d=>(o==="otp:sms"||o==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),o==="passkey:reg"||o==="passkey:auth"||o==="passkey:tx"){let d=s.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],a=["passkey:reg","passkey:auth","passkey:tx","otp:sms","otp:email","external"].find(s=>e?.next?.some(o=>o.action.name===s));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...a&&{nextAction:a},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 Q=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}},Ae=class Ie{static mfaOptionValidator(t,r,a){let{session:s=r?.session,payload:o=""}=a;if(!s)throw new h("A session is required to perform MFA factor.");if(o)return{session:s,payload:o};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:s,payload:u(n)};case"otp:email":return{session:s,payload:u(n,"email:primary")};case"otp:sms":return{session:s,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(Ie.isPublicKeyCredentialCreationOptions(r)||Ie.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 Ye=class{config;constructor(e){this.config=new Q(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||this.retrieveToken("accessToken")||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=R(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub,rpId:e.rpId}}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(),a=`${this.getJwtCookieName()}=${e}; expires=${r}`;ne(a)}getJwtCookie(){return W(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){v(this.getJwtCookieName()),v(this.getIdTokenName()),v(this.getAccessTokenName()),v(this.getRefreshTokenName()),v(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:a,refreshToken:s}=e,o=(i,n)=>{if(!n)return;let u=R(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};o(this.getIdTokenName(),r),o(this.getAccessTokenName(),t),o(this.getRefreshTokenName(),s),o(this.getPayloadSignatureName(),a)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return W(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var m=class{config;service;session;constructor(e){this.config=new Q(e),this.service=new we({BASE:e.baseUrl}),this.session=new Ye(e)}},j=class extends m{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 T(),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 P&&(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(),f.persistInfo(e,{next:[]})}},Tt=new Set(["ERROR_PASSKEY_ABORTED"]),Z=class extends m{constructor(e){super(e)}async reportError(e,t){let{disableAnalytics:r}=this.config.getConfig();if(r)return{session:""};if(t instanceof y){if(Tt.has(t.code))return{session:""};let a=t.cause,s=`${t.code} - ${t.message} - ${a.name} - ${a.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:s}})}}},Te=class extends m{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),a=I.getDeviceId(r),s=await T(a),o=He(e,t),i="";t.txPayload&&(i=await new ge().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new N(r).setOrSignWithTrustId(e));let u={deviceInfo:s,user:{username:e,usernameType:o.usernameType,displayName:o.displayName,...t.name&&{name:t.name},...t.phone&&{name:t.phone}},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}),d=X(l,e);return f.persistInfo(r,d),this.session.logout(),D(d)}async performAction(e,t={}){let r=this.config.getAppId(),a=f.getInfo(r),{payload:s,session:o}=Ae.mfaOptionValidator(e,a,t);if(e==="passkey:tx"&&t.txPayload){let{txPayload:i,...n}=t,u=await this.service.mfa.mfaMfaPayloadUpdate({authorization:o,requestBody:{payload:i}}),l=a?.username,d=X(u,l);return f.persistInfo(r,d),await this.performAction(e,n)}switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=Ae.validatePasskeyPayload(s);if("rpId"in i)return await this.invokeMfaApi(e,r,a?.username,async()=>{let n=await w.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:o},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:o,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:o,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(e,r,a?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await w.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:o});try{return await this.service.mfa.mfaMfaPasskeyReg({authorization:o,requestBody:{creationResult:n.creationResult}})}catch(u){throw L(n.creationResult.credentialId,i.rp.id),u}});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:o,requestBody:{method:e==="otp:email"?"email":"sms",option:s}});return f.updateSession(r,i),D(f.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(e,r,a?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:o,requestBody:{otp:s}}));case"external":return await this.invokeMfaApi(e,r,a?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:o,requestBody:{token:s}}))}throw new h(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=f.getInfo(e),r=this.session.getTokenSet();return D(t,r)}async invokeMfaApi(e,t,r="",a){try{let s=await a(),o=f.getInfo(t);f.persistInfo(t,{...r&&{username:r},flow:o?.flow,next:[]}),this.session.setTokenSet(s),I.persistDeviceId(t,s.deviceId);let i=f.getInfo(t);return(e==="passkey:auth"||e==="passkey:tx")&&A(this.service,this.session),D(i,s)}catch(s){if(s instanceof P&&s.status===401&&s.body.session){let o=s.body,i=X(o,r);return f.persistInfo(t,i),D(i)}if(s instanceof Error){let o=new Z(this.config.getConfig()),i=this.config.getAppId(),n=f.getInfo(i);n?.session&&o.reportError(n.session,s).then(u=>{u?.session&&f.updateSession(i,u.session)})}throw s}}};var Xe=class extends m{constructor(e){super(e)}};M(Xe,[m,Te,j]);var vt=Xe;var ve=class extends m{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t),a=await this.service.passkeys.passkeysPasskeysList({authorization:r});return G(a,this.session),a}async renamePasskey(t,r,a={}){let s=this.session.getToken(a),o={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:s,id:t,requestBody:o})}async deletePasskey(t,r={}){let a=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:a,id:t}),A(this.service,this.session)}},Qe=ve;var q=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Ze=(e,t)=>({...q(e,"",t),txType:t.txType||"raw",nonce:t.nonce||J()}),B=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,deviceId:e.deviceId,isAuthenticated:t,isFallback:r});var et=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Oe=class extends m{constructor(t){super(t)}async validateOtp(t,r,a={}){let s=q(t,"",a),o={authCode:r,user:{username:t,usernameType:s.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:o}),n=B(i);return S.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",a={}){let s=q(t,"",a),o={user:{username:t,usernameType:s.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:o});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:o});break;default:throw new Error("Invalid message method")}}},ee=Oe;var Ee=class extends ee{constructor(t){super(t)}async createPasskey(t,r="",a={}){let s=this.config.getAppId(),o=I.getDeviceId(s),i=await T(o),n=new N(s),u=q(t,r,a);u.authzToken=this.session.getToken(u),u.authzToken&&R(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:s},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...a.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 w.createNavigatorCredential(p);a.passkeyName&&(g.passkeyName=a.passkeyName);try{let F=await this.service.reg.regRegComplete({requestBody:g}),st=B(F);return this.session.setJwtCookie(F.jwtAccess),I.persistDeviceId(s,o||F.deviceId),st}catch(F){throw L(g.creationResult.credentialId,p.registrationRequestOptions.rp.id),F}})}async authenticateWithPasskey(t="",r={}){let a=this.config.getAppId(),s=await T(I.getDeviceId(a)),o=new N(a),i=q(t,"",r),n=await o.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:a},deviceInfo:s,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 w.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:d});A(this.service,this.session);let g=B(p);return this.session.setJwtCookie(g.token),I.persistDeviceId(a,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=et(l);await i.callbacks.onFallback(t,p)}return B({userId:"",jwtAccess:""},!1,!0)}default:throw de}}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 s=await this.authenticateWithPasskey(t,r);r.authzToken=s.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,a={}){let s=Ze(t,a),o={username:t,txPayload:r,nonce:s.nonce,txType:s.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:o}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await w.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature},p=await this.service.tx.txTxComplete({requestBody:d});return A(this.service,this.session),p})}async invokePasskeyApi(t,r){try{return await r()}catch(a){throw a instanceof Error&&new Z(this.config.getConfig()).reportError(t,a),a}}},tt=Ee;var te=class extends m{constructor(t){super(t)}};M(te,[m,tt,ee,Qe,j]);var rt=te;var xa=rt;export{$ as AbortError,P as ApiError,vt as LoginIDMfa,rt as LoginIDWebSDK,y as PasskeyError,w as WebAuthnHelper,ce as createPasskeyCredential,xa as default,pe as getPasskeyCredential,ae as isConditionalUIAvailable,se 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
|
+
"version": "3.5.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",
|