@loginid/websdk3 3.2.2 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var X=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var Ye=(e,t)=>{for(var r in t)X(e,r,{get:t[r],enumerable:!0})},Xe=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of He(t))!Ge.call(e,s)&&s!==r&&X(e,s,{get:()=>t[s],enumerable:!(o=Ve(t,s))||o.enumerable});return e};var Qe=e=>Xe(X({},"__esModule",{value:!0}),e);var bt={};Ye(bt,{AbortError:()=>D,ApiError:()=>w,LoginIDMfa:()=>Le,LoginIDWebSDK:()=>be,PasskeyError:()=>y,WebAuthnHelper:()=>R,createPasskeyCredential:()=>K,default:()=>Rt,getPasskeyCredential:()=>W,isConditionalUIAvailable:()=>Z,isPlatformAuthenticatorAvailable:()=>Q});module.exports=Qe(bt);var A=e=>{let t={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return e&&(t.deviceId=e),t},Q=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},Z=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},L=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},ee=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var D=class extends Error{constructor(e){super(e),this.name="AbortError"}},h=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},y=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var N=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],o=0;for(;o<e.length;){let i=e.charCodeAt(o++),n=e.charCodeAt(o++),u=e.charCodeAt(o++),d=i<<16|n<<8|u;r.push(t[d>>18&63]+t[d>>12&63]+t[d>>6&63]+t[d&63])}let s=r.join(""),a=e.length%3;return a?s.slice(0,a-3)+"===".slice(a||3):s},Ie=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},o=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let s=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(s=(s<<6)+u,a+=6;a>=8;)i+=o(s>>(a-=8)&255)}return i},g=e=>{let t="",r=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)t+=String.fromCharCode(r[s]);let o=B(t);return N(o)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Ie(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},te=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let o=0;o<e;o++)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"]),S=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),re=async(e,t)=>{let r=new TextEncoder().encode(t),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return g(o)},we=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},F=()=>window.crypto?.randomUUID?window.crypto.randomUUID():we(24);var v=class q{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new D("Cancelling current WebAuthn request");q.abortController.abort(t)};static renewWebAuthnAbortController=()=>{q.abortWebAuthnRequest();let t=new AbortController;q.abortController=t};static assignWebAuthnAbortController=t=>{q.abortWebAuthnRequest(),q.abortController=t}},Ae=(e,t)=>{let r=e.name,{publicKey:o}=t;if(r==="ConstraintError"){if(o?.authenticatorSelection?.requireResidentKey===!0)return new y("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(o?.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_SEE_CAUSE_FIELD",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=o?.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},Te=(e,t)=>{let r=e.name,{publicKey:o}=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_SEE_CAUSE_FIELD",e);if(r==="SecurityError"){let s=o?.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},Ze=new h("User needs to be logged in to perform this operation."),se=new h("No login options available."),K=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let s of e.excludeCredentials){let a={id:O(s.id),transports:s.transports,type:s.type};t.push(a)}}let r=e.pubKeyCredParams,o={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(o);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?Ae(s,o):s}},W=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let s of e.allowCredentials){let a={id:O(s.id),transports:s.transports,type:s.type};r.push(a)}}let o={...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(o);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?Te(s,o):s}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:o}=e;t.abortController?v.assignWebAuthnAbortController(t.abortController):(v.renewWebAuthnAbortController(),t.abortController=v.abortController);let s=await W(r,t),a=s.response;return{assertionResult:{authenticatorData:g(a.authenticatorData),clientDataJSON:g(a.clientDataJSON),credentialId:s.id,signature:g(a.signature),...a.userHandle&&{userHandle:g(a.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;v.renewWebAuthnAbortController();let o=await K(t),s=o.response,a=s.getPublicKey&&s.getPublicKey(),i=s.getPublicKeyAlgorithm&&s.getPublicKeyAlgorithm(),n=s.getAuthenticatorData&&s.getAuthenticatorData(),u=s.getTransports&&s.getTransports();return{creationResult:{attestationObject:g(s.attestationObject),clientDataJSON:g(s.clientDataJSON),credentialId:o.id,...a&&{publicKey:g(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:g(n)},...u&&{transports:u}},session:r}}};var Oe=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."}})}},Se=class{constructor(e){this.config=e}},ve=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Ee=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 o=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.#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(o,s,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 ve("Request aborted"))}}get isCancelled(){return this.#e}},w=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}},ae=e=>e!=null,U=e=>typeof e=="string",oe=e=>U(e)&&e!=="",ie=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]),Ce=e=>e instanceof FormData,et=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},tt=e=>{let t=[],r=(s,a)=>{t.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(a))}`)},o=(s,a)=>{ae(a)&&(Array.isArray(a)?a.forEach(i=>{o(s,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{o(`${s}[${i}]`,n)}):r(s,a))};return Object.entries(e).forEach(([s,a])=>{o(s,a)}),t.length>0?`?${t.join("&")}`:""},rt=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,o=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),s=`${e.BASE}${o}`;return t.query?`${s}${tt(t.query)}`:s},st=e=>{if(e.formData){let t=new FormData,r=(o,s)=>{U(s)||ie(s)?t.append(o,s):t.append(o,JSON.stringify(s))};return Object.entries(e.formData).filter(([o,s])=>ae(s)).forEach(([o,s])=>{Array.isArray(s)?s.forEach(a=>r(o,a)):r(o,s)}),t}},$=async(e,t)=>typeof t=="function"?t(e):t,ot=async(e,t)=>{let[r,o,s,a]=await Promise.all([$(t,e.TOKEN),$(t,e.USERNAME),$(t,e.PASSWORD),$(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>ae(u)).reduce((n,[u,d])=>({...n,[u]:String(d)}),{});if(oe(r)&&(i.Authorization=`Bearer ${r}`),oe(o)&&oe(s)){let n=et(`${o}:${s}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:ie(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":U(t.body)?i["Content-Type"]="text/plain":Ce(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},at=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):U(e.body)||ie(e.body)||Ce(e.body)?e.body:JSON.stringify(e.body)},it=async(e,t,r,o,s,a,i)=>{let n=new AbortController,u={headers:a,body:o??s,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},nt=(e,t)=>{if(t){let r=e.headers.get(t);if(U(r))return r}},ut=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)}},dt=(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 w(e,t,r);if(!t.ok){let o=t.status??"unknown",s=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new w(e,t,`Generic Error: status: ${o}; status text: ${s}; body: ${a}`)}},lt=(e,t)=>new Ee(async(r,o,s)=>{try{let a=rt(e,t),i=st(t),n=at(t),u=await ot(e,t);if(!s.isCancelled){let d=await it(e,t,a,n,i,u,s),l=await ut(d),p=nt(d,t.responseHeader),k={url:a,ok:d.ok,status:d.status,statusText:d.statusText,body:p??l};dt(t,k),r(k.body)}}catch(a){o(a)}}),ct=class extends Se{constructor(e){super(e)}request(e){return lt(this.config,e)}},qe=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."}})}},Pe=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."}})}mfaMfaError({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/error",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."}})}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."}})}},xe=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."}})}},_e=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."}})}},ne=class{auth;mfa;passkeys;reg;tx;request;constructor(e,t=ct){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 qe(this.request),this.mfa=new Pe(this.request),this.passkeys=new Oe(this.request),this.reg=new xe(this.request),this.tx=new _e(this.request)}};var De=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ue=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),P=(e,t)=>{let r=e?.next?.map(s=>{let{name:a,label:i,desc:n}=s.action,u={type:a,label:i,...n&&{description:n}};if(s.options){let d=s.options.filter(l=>(a==="otp:sms"||a==="otp:email")&&l.label).map(l=>l.label).filter(Boolean);if(d.length&&(u.options=d),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let l=s.options.find(p=>p.value);l&&(u.value=l.value)}}return u})||[],o=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(s=>e?.next?.some(a=>a.action.name===s));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...o&&{nextAction:o},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 J=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.")}},le=class de{static mfaOptionValidator(t,r,o){let{session:s=r?.session,payload:a=""}=o;if(!s)throw new h("A session is required to perform MFA factor.");if(a)return{session:s,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(d=>d.action.name===t);if(!n)throw new h(`No matching factor found for ${t}.`);let u=(d,l)=>{if(!d.options?.length)throw new h(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return d.options[0].value;let p;if(l?p=d.options.find(k=>k.name===l)?.label:p=d.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=b("."+t);if(!r)throw new h("Invalid payload for passkeys.");if(de.isPublicKeyCredentialCreationOptions(r)||de.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 Ne=class{config;constructor(e){this.config=new J(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(),o=`${this.getJwtCookieName()}=${e}; expires=${r}`;ee(o)}getJwtCookie(){return L(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:o,refreshToken:s}=e,a=(i,n)=>{if(!n)return;let u=b(n),d=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${d};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),s),a(this.getPayloadSignatureName(),o)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return L(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var z=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(o=>{Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))})})},V=(e,t,r)=>(r||(r=te()),{id:r,username:t,aud:e}),E=async(e,t,r)=>{let o=N(B(JSON.stringify({alg:"ES256",jwk:t}))),s=N(B(JSON.stringify(e))),a=`${o}.${s}`,i=await re(r,a);return`${a}.${i}`};var he=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 Be=e=>`LoginID_${e}_device-id`,I=class extends he{static persistDeviceId(e,t){this.setItem(Be(e),t)}static getDeviceId(e){return this.getItem(Be(e))||""}},ye=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,o=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=o}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:o,keyPath:s,options:a})=>r.createIndex(o,s,a))}},e}async getAllByIndex(e,t){return new Promise((r,o)=>{let s=this.openDb();s.onsuccess=()=>{let a=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>o(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>o(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,o)=>{let s=this.openDb();s.onsuccess=()=>{let a=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):o(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>o(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>o(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 o=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();o.onsuccess=()=>{let s=o.result;s?e(s.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},o.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 o=this.openDb();o.onsuccess=()=>{let s=o.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"))},o.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let o=this.openDb();o.onsuccess=()=>{let s=o.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"))},o.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},pt=1;var ht="lid_c_wtid",yt="lid-wtid-k",ze=class extends ye{constructor(e,t){super(e,pt,t)}async setCheckoutId(){let e=await j(),t=await S(e),r={id:F()},o=await E(r,t,e.privateKey);return await this.putRecord({id:r.id,keyPair:e}),o}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await S(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await S(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}};var me=class extends ze{constructor(){super(ht,yt)}},mt=1,Fe="app_id_idx",ft="username_idx",gt="loginid-trust-store",kt="LoginID_trust-id",ce="app_id_username_idx",x=class extends ye{appId;constructor(e){super(gt,mt,kt,[{name:ft,keyPath:["username"]},{name:Fe,keyPath:["appId"]},{name:ce,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await j(),r=await S(t),o=V(this.appId,e),s=await E(o,r,t.privateKey);return await this.putRecord({id:o.id,appId:this.appId,username:e,keyPair:t}),s}async signWithTrustId(e){let t=await this.getByIndex(ce,[this.appId,e]),r=await S(t.keyPair),o=V(this.appId,e,t.id);return await E(o,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(Fe,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ce,[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)}}},Ue=e=>`LoginID_${e}_mfa-session`,f=class pe extends he{static persistInfo(t,r){this.setItem(Ue(t),r)}static getInfo(t){return this.getItem(Ue(t))}static updateSession(t,r){let o=pe.getInfo(t);o?o.session=r:o={session:r},pe.persistInfo(t,o)}};var m=class{config;service;session;constructor(e){this.config=new J(e),this.service=new ne({BASE:e.baseUrl}),this.session=new Ne(e)}},M=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={app:{id:this.config.getAppId()},deviceInfo:A(),user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:t})}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 w&&(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:[]})}},fe=class extends m{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),o=I.getDeviceId(r),s=A(o),a=De(e,t),i="";t.txPayload&&(i=await new me().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new x(r).setOrSignWithTrustId(e));let u={deviceInfo:s,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}},d=await this.service.mfa.mfaMfaBegin({requestBody:u}),l=ue(d,e);return f.persistInfo(r,l),this.session.logout(),P(l)}async performAction(e,t={}){let r=this.config.getAppId(),o=f.getInfo(r),{payload:s,session:a}=le.mfaOptionValidator(e,o,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=le.validatePasskeyPayload(s);if("rpId"in i){let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}})):await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}}))}if("rp"in i){let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.invokeMfaApi(r,o?.username,async()=>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:s}});return f.updateSession(r,i),P(f.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:s}}));case"external":return await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,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 P(t,r)}async invokeMfaApi(e,t="",r){try{let o=await r(),s=f.getInfo(e);f.persistInfo(e,{...t&&{username:t},flow:s?.flow,next:[]}),this.session.setTokenSet(o),I.persistDeviceId(e,o.deviceId);let a=f.getInfo(e);return P(a,o)}catch(o){if(o instanceof w&&o.status===401&&o.body.session){let s=o.body,a=ue(s,t);return f.persistInfo(e,a),P(a)}throw o}}};var Me=class extends m{constructor(e){super(e)}};z(Me,[m,fe,M]);var Le=Me;var ge=class extends m{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,o={}){let s=this.session.getToken(o),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:s,id:t,requestBody:a})}async deletePasskey(t,r={}){let o=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:o,id:t})}},je=ge;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Ke=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||F()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var We=e=>[...e.crossAuthMethods,...e.fallbackMethods];var ke=class extends m{constructor(t){super(t)}async validateOtp(t,r,o={}){let s=C(t,"",o),a={authCode:r,user:{username:t,usernameType:s.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return v.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",o={}){let s=C(t,"",o),a={user:{username:t,usernameType:s.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")}}},H=ke;var Re=class extends H{constructor(t){super(t)}async createPasskey(t,r="",o={}){let s=this.config.getAppId(),a=I.getDeviceId(s),i=A(a),n=new x(s),u=C(t,r,o);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let d=await n.setOrSignWithTrustId(t),l={app:{id:s},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},...d&&{trustItems:{auth:d}}},p=await this.service.reg.regRegInit({requestBody:l,...u.authzToken&&{authorization:u.authzToken}}),k=await R.createNavigatorCredential(p),Y=await this.service.reg.regRegComplete({requestBody:k}),Je=_(Y);return this.session.setJwtCookie(Y.jwtAccess),I.persistDeviceId(s,a||Y.deviceId),Je}async authenticateWithPasskey(t="",r={}){let o=this.config.getAppId(),s=A(I.getDeviceId(o)),a=new x(o),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:o},deviceInfo:s,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},d=await this.service.auth.authAuthInit({requestBody:u});switch(d.action){case"proceed":{let l=await R.getNavigatorCredential(d,r),p=await this.service.auth.authAuthComplete({requestBody:l}),k=_(p);return this.session.setJwtCookie(k.token),I.persistDeviceId(o,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(k),k}case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=We(d);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw se}}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,o={}){let s=Ke(t,o),a={username:t,txPayload:r,nonce:s.nonce,txType:s.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n},{assertionResult:d}=await R.getNavigatorCredential(u),l={authenticatorData:d.authenticatorData,clientData:d.clientDataJSON,keyHandle:d.credentialId,session:n,signature:d.signature};return await this.service.tx.txTxComplete({requestBody:l})}},$e=Re;var G=class extends m{constructor(t){super(t)}};z(G,[m,$e,H,je,M]);var be=G;var Rt=be;0&&(module.exports={AbortError,ApiError,LoginIDMfa,LoginIDWebSDK,PasskeyError,WebAuthnHelper,createPasskeyCredential,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
1
+ "use strict";var ee=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var r in t)ee(e,r,{get:t[r],enumerable:!0})},tt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qe(t))!Ze.call(e,o)&&o!==r&&ee(e,o,{get:()=>t[o],enumerable:!(s=Xe(t,o))||s.enumerable});return e};var rt=e=>tt(ee({},"__esModule",{value:!0}),e);var Tt={};et(Tt,{AbortError:()=>N,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>R,createPasskeyCredential:()=>$,default:()=>It,getPasskeyCredential:()=>V,isConditionalUIAvailable:()=>j,isPlatformAuthenticatorAvailable:()=>M});module.exports=rt(Tt);var I=async e=>{let t=JSON.stringify(await Ae()),r=await Ie(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},M=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},j=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Ae=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await M(),t=await j();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},Ie=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},K=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},te=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var N=class extends Error{constructor(e){super(e),this.name="AbortError"}},y=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},h=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var D=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Te=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=B(t);return D(s)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Te(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},re=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},W=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),v=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),se=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(s)},Oe=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},F=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Oe(24);var E=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new N("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},ve=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new h("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new h("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new h("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new h("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Ee=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new h("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new h("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},st=new y("User needs to be logged in to perform this operation."),oe=new y("No login options available."),$=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:O(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:O(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?ve(o,s):o}},V=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:O(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ee(o,s):o}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?E.assignWebAuthnAbortController(t.abortController):(E.renewWebAuthnAbortController(),t.abortController=E.abortController);let o=await V(r,t),a=o.response;return{assertionResult:{authenticatorData:k(a.authenticatorData),clientDataJSON:k(a.clientDataJSON),credentialId:o.id,signature:k(a.signature),...a.userHandle&&{userHandle:k(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;E.renewWebAuthnAbortController();let s=await $(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:k(o.attestationObject),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:k(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var U=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},J=(e,t,r)=>(r||(r=re()),{id:r,username:t,aud:e}),S=async(e,t,r)=>{let s=D(B(JSON.stringify({alg:"ES256",jwk:t}))),o=D(B(JSON.stringify(e))),a=`${s}.${o}`,i=await se(r,a);return`${a}.${i}`};var ne=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var Se=e=>`LoginID_${e}_device-id`,w=class extends ne{static persistDeviceId(e,t){this.setItem(Se(e),t)}static getDeviceId(e){return this.getItem(Se(e))||""}},ue=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new c("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var at="lid_c_wtid",it="lid-wtid-k",qe=class extends ue{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await W(),t=await v(e),r={id:F()},s=await S(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new c("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new c("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var le=class extends qe{constructor(){super(at,it)}},nt=1,Ce="app_id_idx",ut="username_idx",lt="loginid-trust-store",dt="LoginID_trust-id",ae="app_id_username_idx",q=class extends ue{appId;constructor(e){super(lt,nt,dt,[{name:ut,keyPath:["username"]},{name:Ce,keyPath:["appId"]},{name:ae,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await W(),r=await v(t),s=J(this.appId,e),o=await S(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(ae,[this.appId,e]),r=await v(t.keyPair),s=J(this.appId,e,t.id);return await S(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof c&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ce,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ae,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Pe=e=>`LoginID_${e}_mfa-session`,m=class ie extends ne{static persistInfo(t,r){this.setItem(Pe(t),r)}static getInfo(t){return this.getItem(Pe(t))}static updateSession(t,r){let s=ie.getInfo(t);s?s.session=r:s={session:r},ie.persistInfo(t,s)}};var xe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},_e=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Ne=class{constructor(e){this.config=e}},De=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Be=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new De("Request aborted"))}}get isCancelled(){return this.#e}},A=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},ce=e=>e!=null,z=e=>typeof e=="string",de=e=>z(e)&&e!=="",pe=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof FormData,ct=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},pt=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{ce(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},ht=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${pt(t.query)}`:o},yt=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{z(o)||pe(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>ce(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},G=async(e,t)=>typeof t=="function"?t(e):t,mt=async(e,t)=>{let[r,s,o,a]=await Promise.all([G(t,e.TOKEN),G(t,e.USERNAME),G(t,e.PASSWORD),G(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>ce(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(de(r)&&(i.Authorization=`Bearer ${r}`),de(s)&&de(o)){let n=ct(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:pe(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":z(t.body)?i["Content-Type"]="text/plain":Fe(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ft=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):z(e.body)||pe(e.body)||Fe(e.body)?e.body:JSON.stringify(e.body)},gt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},kt=(e,t)=>{if(t){let r=e.headers.get(t);if(z(r))return r}},Rt=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},bt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new A(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new A(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},wt=(e,t)=>new Be(async(r,s,o)=>{try{let a=ht(e,t),i=yt(t),n=ft(t),u=await mt(e,t);if(!o.isCancelled){let l=await gt(e,t,a,n,i,u,o),d=await Rt(l),p=kt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};bt(t,g),r(g.body)}}catch(a){s(a)}}),At=class extends Ne{constructor(e){super(e)}request(e){return wt(this.config,e)}},Ue=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Le=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},Me=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},he=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=At){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Ue(this.request),this.clientEvents=new xe(this.request),this.mfa=new ze(this.request),this.passkeys=new _e(this.request),this.reg=new Le(this.request),this.tx=new Me(this.request)}};var je=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ye=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),x=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(d=>(a==="otp:sms"||a==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let d=o.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],s=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var H=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},fe=class me{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new y("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new y("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new y(`No matching factor found for ${t}.`);let u=(l,d)=>{if(!l.options?.length)throw new y(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(d?p=l.options.find(g=>g.name===d)?.label:p=l.options[0]?.label,!p)throw new y(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new y("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new y("Payload is required for passkeys.");let r=b("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(me.isPublicKeyCredentialCreationOptions(r)||me.isPublicKeyCredentialRequestOptions(r))return r;throw new y("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Ke=class{config;constructor(e){this.config=new H(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=b(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=b(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;te(s)}getJwtCookie(){return K(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){T(this.getJwtCookieName()),T(this.getIdTokenName()),T(this.getAccessTokenName()),T(this.getRefreshTokenName()),T(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=b(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return K(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new H(e),this.service=new he({BASE:e.baseUrl}),this.session=new Ke(e)}},L=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await I(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof A&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},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){let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},ge=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await I(s),a=je(e,t),i="";t.txPayload&&(i=await new le().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new q(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),d=ye(l,e);return m.persistInfo(r,d),this.session.logout(),x(d)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=fe.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=fe.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),x(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return x(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return x(a,s)}catch(s){if(s instanceof A&&s.status===401&&s.body.session){let o=s.body,a=ye(o,t);return m.persistInfo(e,a),x(a)}if(s instanceof Error){let o=new Y(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var We=class extends f{constructor(e){super(e)}};U(We,[f,ge,L]);var $e=We;var ke=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ve=ke;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Je=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||F()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var Ge=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Re=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return E.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},X=Re;var be=class extends X{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await I(a),n=new q(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:d,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await R.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let Z=await this.service.reg.regRegComplete({requestBody:g}),Ye=_(Z);return this.session.setJwtCookie(Z.jwtAccess),w.persistDeviceId(o,a||Z.deviceId),Ye})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await I(w.getDeviceId(s)),a=new q(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let d=await R.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:d}),g=_(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=Ge(l);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw oe}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=Je(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await R.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:d})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new Y(this.config.getConfig()).reportError(t,s),s}}},He=be;var Q=class extends f{constructor(t){super(t)}};U(Q,[f,He,X,Ve,L]);var we=Q;var It=we;0&&(module.exports={AbortError,ApiError,LoginIDMfa,LoginIDWebSDK,PasskeyError,WebAuthnHelper,createPasskeyCredential,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.ts CHANGED
@@ -17,6 +17,10 @@ type DeviceInfo = {
17
17
  * An unique device identifier
18
18
  */
19
19
  deviceId?: string;
20
+ /**
21
+ * Whether the client browser has access to bluetooth.
22
+ */
23
+ hasBluetooth?: boolean;
20
24
  /**
21
25
  * Last use timestamp in rfc3339 format
22
26
  */
@@ -41,6 +45,10 @@ type DeviceInfo = {
41
45
  * Screen width in pixels
42
46
  */
43
47
  screenWidth?: number;
48
+ /**
49
+ * JSON string containing client webauthn capabilities.
50
+ */
51
+ webauthnCapabilities?: string;
44
52
  };
45
53
  /**
46
54
  * Checks if platform authenticator available
@@ -278,6 +286,10 @@ type CreationResult = {
278
286
  };
279
287
  type RegCompleteRequestBody = {
280
288
  creationResult: CreationResult;
289
+ /**
290
+ * Passkey name that will be shown to the user in passkey list.
291
+ */
292
+ passkeyName?: string;
281
293
  /**
282
294
  * An opaque object containing session data.
283
295
  */
@@ -334,7 +346,7 @@ interface LoginIDTokenSet {
334
346
  */
335
347
  payloadSignature?: string;
336
348
  }
337
- type PasskeyErrorCode = "ERROR_PASSKEY_ABORTED" | "ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED" | "ERROR_USER_VERIFICATION_UNSUPPORTED" | "ERROR_PASSKEY_EXISTS" | "ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD" | "ERROR_ALGORITHMS_UNSUPPORTED" | "ERROR_DOMAIN_MISMATCH" | "ERROR_AUTHENTICATOR_UNKNOWN_ERROR";
349
+ type PasskeyErrorCode = "ERROR_PASSKEY_ABORTED" | "ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED" | "ERROR_USER_VERIFICATION_UNSUPPORTED" | "ERROR_PASSKEY_EXISTS" | "ERROR_GENERAL_ERROR" | "ERROR_ALGORITHMS_UNSUPPORTED" | "ERROR_DOMAIN_MISMATCH" | "ERROR_AUTHENTICATOR_UNKNOWN_ERROR";
338
350
  /**
339
351
  * Error class for passkey-related errors.
340
352
  */
@@ -479,6 +491,10 @@ interface LoginIDConfig {
479
491
  * The optional app ID for specific application.
480
492
  */
481
493
  appId?: string;
494
+ /**
495
+ * If true, disables sending analytics/events to LoginID. Defaults to false.
496
+ */
497
+ disableAnalytics?: boolean;
482
498
  }
483
499
  interface LoginIDMfaConfig {
484
500
  /**
@@ -544,6 +560,10 @@ interface MfaPerformActionOptions {
544
560
  * Enables passkey support in browser autofill suggestions (conditional UI), if supported.
545
561
  */
546
562
  autoFill?: boolean;
563
+ /**
564
+ * A human-palatable name for the user account, intended only for display on your passkeys..
565
+ */
566
+ displayName?: string;
547
567
  }
548
568
  interface RemainingFactor {
549
569
  /**
@@ -666,6 +686,11 @@ declare class LoginIDConfigValidator {
666
686
  * @throws {Error} If the app ID is not found in the configuration or the base URL, throws an error.
667
687
  */
668
688
  getAppId(): string;
689
+ /**
690
+ * Retrieves the original LoginID configuration object.
691
+ * @returns {LoginIDConfig} The configuration object.
692
+ */
693
+ getConfig(): LoginIDConfig;
669
694
  }
670
695
  type MfaNext = {
671
696
  /**
@@ -686,18 +711,15 @@ type MfaNext = {
686
711
  */
687
712
  session?: string;
688
713
  };
689
- type ApiRequestOptions = {
690
- readonly method: "GET" | "PUT" | "POST" | "DELETE" | "OPTIONS" | "HEAD" | "PATCH";
691
- readonly url: string;
692
- readonly path?: Record<string, any>;
693
- readonly cookies?: Record<string, any>;
694
- readonly headers?: Record<string, any>;
695
- readonly query?: Record<string, any>;
696
- readonly formData?: Record<string, any>;
697
- readonly body?: any;
698
- readonly mediaType?: string;
699
- readonly responseHeader?: string;
700
- readonly errors?: Record<number, string>;
714
+ type SubmitRequestBody = {
715
+ /**
716
+ * Client side event.
717
+ */
718
+ event: string;
719
+ /**
720
+ * Whether the event is a result of an error.
721
+ */
722
+ isError?: boolean;
701
723
  };
702
724
  interface OnCancel {
703
725
  readonly isResolved: boolean;
@@ -715,6 +737,19 @@ declare class CancelablePromise<T> implements Promise<T> {
715
737
  cancel(): void;
716
738
  get isCancelled(): boolean;
717
739
  }
740
+ type ApiRequestOptions = {
741
+ readonly method: "GET" | "PUT" | "POST" | "DELETE" | "OPTIONS" | "HEAD" | "PATCH";
742
+ readonly url: string;
743
+ readonly path?: Record<string, any>;
744
+ readonly cookies?: Record<string, any>;
745
+ readonly headers?: Record<string, any>;
746
+ readonly query?: Record<string, any>;
747
+ readonly formData?: Record<string, any>;
748
+ readonly body?: any;
749
+ readonly mediaType?: string;
750
+ readonly responseHeader?: string;
751
+ readonly errors?: Record<number, string>;
752
+ };
718
753
  type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
719
754
  type Headers = Record<string, string>;
720
755
  type OpenAPIConfig = {
@@ -733,6 +768,29 @@ declare abstract class BaseHttpRequest {
733
768
  constructor(config: OpenAPIConfig);
734
769
  abstract request<T>(options: ApiRequestOptions): CancelablePromise<T>;
735
770
  }
771
+ type Session = {
772
+ /**
773
+ * An opaque "session" object that shall be used with any subsequent calls.
774
+ */
775
+ session?: string;
776
+ };
777
+ declare class ClientEventsService {
778
+ readonly httpRequest: BaseHttpRequest;
779
+ constructor(httpRequest: BaseHttpRequest);
780
+ /**
781
+ * Report a client side event.
782
+ * Report a client event. It does not change state of the flow.
783
+ * @returns Session OK response.
784
+ * @throws ApiError
785
+ */
786
+ clientEventsSubmit({ requestBody, authorization, }: {
787
+ requestBody: SubmitRequestBody;
788
+ /**
789
+ * JWT Authorization header
790
+ */
791
+ authorization?: string;
792
+ }): CancelablePromise<Session>;
793
+ }
736
794
  type PasskeyRenameRequestBody = {
737
795
  /**
738
796
  * Internal passkey identifier
@@ -1027,12 +1085,6 @@ type MfaBeginRequestBody = {
1027
1085
  trustItems?: Record<string, string>;
1028
1086
  user?: User;
1029
1087
  };
1030
- type MfaErrorRequestBody = {
1031
- /**
1032
- * Client side error code.
1033
- */
1034
- error: string;
1035
- };
1036
1088
  declare class MfaService {
1037
1089
  readonly httpRequest: BaseHttpRequest;
1038
1090
  constructor(httpRequest: BaseHttpRequest);
@@ -1049,19 +1101,6 @@ declare class MfaService {
1049
1101
  */
1050
1102
  userAgent?: string;
1051
1103
  }): CancelablePromise<MfaNext>;
1052
- /**
1053
- * Verify auth token created by a third party via management API.
1054
- * Report a client error. It does not change state of the flow.
1055
- * @returns void
1056
- * @throws ApiError
1057
- */
1058
- mfaMfaError({ requestBody, authorization, }: {
1059
- requestBody: MfaErrorRequestBody;
1060
- /**
1061
- * JWT Authorization header
1062
- */
1063
- authorization?: string;
1064
- }): CancelablePromise<void>;
1065
1104
  /**
1066
1105
  * Request OTP authentication using one of the available methods.
1067
1106
  * Request OTP.
@@ -1277,6 +1316,7 @@ declare class TxService {
1277
1316
  type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest;
1278
1317
  declare class LoginIDService {
1279
1318
  readonly auth: AuthService;
1319
+ readonly clientEvents: ClientEventsService;
1280
1320
  readonly mfa: MfaService;
1281
1321
  readonly passkeys: PasskeysService;
1282
1322
  readonly reg: RegService;
@@ -1514,7 +1554,6 @@ declare class MFA extends LoginIDBase {
1514
1554
  * Initializes a new MFA instance with the provided configuration.
1515
1555
  *
1516
1556
  * @param {LoginIDMfaConfig} config Configuration object for LoginID services.
1517
- *
1518
1557
  */
1519
1558
  constructor(config: LoginIDMfaConfig);
1520
1559
  /**
@@ -1677,6 +1716,15 @@ export interface CreatePasskeyOptions extends MainPasskeyOptions {
1677
1716
  * A human-palatable name for the user account, intended only for display on your passkeys and modals.
1678
1717
  */
1679
1718
  displayName?: string;
1719
+ /**
1720
+ * A custom label or nickname for the passkey itself, used to help users distinguish between multiple passkeys.
1721
+ * If not provided, a default name may be auto-generated based on the device and/or user-agent.
1722
+ */
1723
+ passkeyName?: string;
1724
+ /**
1725
+ * Indicates that the credential should be a cross-platform FIDO credential (e.g., a hardware security key or a hybrid passkey).
1726
+ */
1727
+ crossPlatform?: boolean;
1680
1728
  }
1681
1729
  /**
1682
1730
  * Confirm transaction options.
@@ -2227,6 +2275,16 @@ declare class Passkeys extends OTP {
2227
2275
  * ```
2228
2276
  */
2229
2277
  confirmTransaction(username: string, txPayload: string, options?: ConfirmTransactionOptions): Promise<TxComplete>;
2278
+ /**
2279
+ * Internal helper method that executes a provided asynchronous function related to passkey flows
2280
+ * and reports any errors to the LoginID event tracking service if an exception occurs.
2281
+ *
2282
+ * @template T The return type of the asynchronous function passed in.
2283
+ * @param {string} session The current encrypted session associated with the operation being performed.
2284
+ * @param {() => Promise<T>} fn The asynchronous function to invoke.
2285
+ * @returns {Promise<T>} The result of the invoked function if it succeeds.
2286
+ */
2287
+ private invokePasskeyApi;
2230
2288
  }
2231
2289
  export interface LoginIDWebSDK extends Passkeys, OTP, PasskeyManager, Utils {
2232
2290
  }
@@ -1,2 +1,2 @@
1
- "use strict";var LoginID=(()=>{var X=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var Ye=(e,t)=>{for(var r in t)X(e,r,{get:t[r],enumerable:!0})},Xe=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of He(t))!Ge.call(e,s)&&s!==r&&X(e,s,{get:()=>t[s],enumerable:!(o=Ve(t,s))||o.enumerable});return e};var Qe=e=>Xe(X({},"__esModule",{value:!0}),e);var bt={};Ye(bt,{AbortError:()=>D,ApiError:()=>w,LoginIDMfa:()=>Le,LoginIDWebSDK:()=>be,PasskeyError:()=>y,WebAuthnHelper:()=>R,createPasskeyCredential:()=>K,default:()=>Rt,getPasskeyCredential:()=>W,isConditionalUIAvailable:()=>Z,isPlatformAuthenticatorAvailable:()=>Q});var A=e=>{let t={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return e&&(t.deviceId=e),t},Q=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},Z=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},L=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},ee=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var D=class extends Error{constructor(e){super(e),this.name="AbortError"}},h=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},y=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var N=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],o=0;for(;o<e.length;){let i=e.charCodeAt(o++),n=e.charCodeAt(o++),u=e.charCodeAt(o++),d=i<<16|n<<8|u;r.push(t[d>>18&63]+t[d>>12&63]+t[d>>6&63]+t[d&63])}let s=r.join(""),a=e.length%3;return a?s.slice(0,a-3)+"===".slice(a||3):s},Ie=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},o=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let s=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(s=(s<<6)+u,a+=6;a>=8;)i+=o(s>>(a-=8)&255)}return i},g=e=>{let t="",r=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)t+=String.fromCharCode(r[s]);let o=B(t);return N(o)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Ie(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},te=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let o=0;o<e;o++)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"]),S=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),re=async(e,t)=>{let r=new TextEncoder().encode(t),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return g(o)},we=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},F=()=>window.crypto?.randomUUID?window.crypto.randomUUID():we(24);var v=class q{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new D("Cancelling current WebAuthn request");q.abortController.abort(t)};static renewWebAuthnAbortController=()=>{q.abortWebAuthnRequest();let t=new AbortController;q.abortController=t};static assignWebAuthnAbortController=t=>{q.abortWebAuthnRequest(),q.abortController=t}},Ae=(e,t)=>{let r=e.name,{publicKey:o}=t;if(r==="ConstraintError"){if(o?.authenticatorSelection?.requireResidentKey===!0)return new y("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(o?.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_SEE_CAUSE_FIELD",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=o?.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},Te=(e,t)=>{let r=e.name,{publicKey:o}=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_SEE_CAUSE_FIELD",e);if(r==="SecurityError"){let s=o?.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},Ze=new h("User needs to be logged in to perform this operation."),se=new h("No login options available."),K=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let s of e.excludeCredentials){let a={id:O(s.id),transports:s.transports,type:s.type};t.push(a)}}let r=e.pubKeyCredParams,o={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(o);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?Ae(s,o):s}},W=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let s of e.allowCredentials){let a={id:O(s.id),transports:s.transports,type:s.type};r.push(a)}}let o={...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(o);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?Te(s,o):s}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:o}=e;t.abortController?v.assignWebAuthnAbortController(t.abortController):(v.renewWebAuthnAbortController(),t.abortController=v.abortController);let s=await W(r,t),a=s.response;return{assertionResult:{authenticatorData:g(a.authenticatorData),clientDataJSON:g(a.clientDataJSON),credentialId:s.id,signature:g(a.signature),...a.userHandle&&{userHandle:g(a.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;v.renewWebAuthnAbortController();let o=await K(t),s=o.response,a=s.getPublicKey&&s.getPublicKey(),i=s.getPublicKeyAlgorithm&&s.getPublicKeyAlgorithm(),n=s.getAuthenticatorData&&s.getAuthenticatorData(),u=s.getTransports&&s.getTransports();return{creationResult:{attestationObject:g(s.attestationObject),clientDataJSON:g(s.clientDataJSON),credentialId:o.id,...a&&{publicKey:g(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:g(n)},...u&&{transports:u}},session:r}}};var Oe=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."}})}},Se=class{constructor(e){this.config=e}},ve=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Ee=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 o=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.#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(o,s,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 ve("Request aborted"))}}get isCancelled(){return this.#e}},w=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}},ae=e=>e!=null,U=e=>typeof e=="string",oe=e=>U(e)&&e!=="",ie=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]),Ce=e=>e instanceof FormData,et=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},tt=e=>{let t=[],r=(s,a)=>{t.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(a))}`)},o=(s,a)=>{ae(a)&&(Array.isArray(a)?a.forEach(i=>{o(s,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{o(`${s}[${i}]`,n)}):r(s,a))};return Object.entries(e).forEach(([s,a])=>{o(s,a)}),t.length>0?`?${t.join("&")}`:""},rt=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,o=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),s=`${e.BASE}${o}`;return t.query?`${s}${tt(t.query)}`:s},st=e=>{if(e.formData){let t=new FormData,r=(o,s)=>{U(s)||ie(s)?t.append(o,s):t.append(o,JSON.stringify(s))};return Object.entries(e.formData).filter(([o,s])=>ae(s)).forEach(([o,s])=>{Array.isArray(s)?s.forEach(a=>r(o,a)):r(o,s)}),t}},$=async(e,t)=>typeof t=="function"?t(e):t,ot=async(e,t)=>{let[r,o,s,a]=await Promise.all([$(t,e.TOKEN),$(t,e.USERNAME),$(t,e.PASSWORD),$(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>ae(u)).reduce((n,[u,d])=>({...n,[u]:String(d)}),{});if(oe(r)&&(i.Authorization=`Bearer ${r}`),oe(o)&&oe(s)){let n=et(`${o}:${s}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:ie(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":U(t.body)?i["Content-Type"]="text/plain":Ce(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},at=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):U(e.body)||ie(e.body)||Ce(e.body)?e.body:JSON.stringify(e.body)},it=async(e,t,r,o,s,a,i)=>{let n=new AbortController,u={headers:a,body:o??s,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},nt=(e,t)=>{if(t){let r=e.headers.get(t);if(U(r))return r}},ut=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)}},dt=(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 w(e,t,r);if(!t.ok){let o=t.status??"unknown",s=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new w(e,t,`Generic Error: status: ${o}; status text: ${s}; body: ${a}`)}},lt=(e,t)=>new Ee(async(r,o,s)=>{try{let a=rt(e,t),i=st(t),n=at(t),u=await ot(e,t);if(!s.isCancelled){let d=await it(e,t,a,n,i,u,s),l=await ut(d),p=nt(d,t.responseHeader),k={url:a,ok:d.ok,status:d.status,statusText:d.statusText,body:p??l};dt(t,k),r(k.body)}}catch(a){o(a)}}),ct=class extends Se{constructor(e){super(e)}request(e){return lt(this.config,e)}},qe=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."}})}},Pe=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."}})}mfaMfaError({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/error",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."}})}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."}})}},xe=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."}})}},_e=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."}})}},ne=class{auth;mfa;passkeys;reg;tx;request;constructor(e,t=ct){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 qe(this.request),this.mfa=new Pe(this.request),this.passkeys=new Oe(this.request),this.reg=new xe(this.request),this.tx=new _e(this.request)}};var De=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ue=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),P=(e,t)=>{let r=e?.next?.map(s=>{let{name:a,label:i,desc:n}=s.action,u={type:a,label:i,...n&&{description:n}};if(s.options){let d=s.options.filter(l=>(a==="otp:sms"||a==="otp:email")&&l.label).map(l=>l.label).filter(Boolean);if(d.length&&(u.options=d),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let l=s.options.find(p=>p.value);l&&(u.value=l.value)}}return u})||[],o=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(s=>e?.next?.some(a=>a.action.name===s));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...o&&{nextAction:o},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 J=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.")}},le=class de{static mfaOptionValidator(t,r,o){let{session:s=r?.session,payload:a=""}=o;if(!s)throw new h("A session is required to perform MFA factor.");if(a)return{session:s,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(d=>d.action.name===t);if(!n)throw new h(`No matching factor found for ${t}.`);let u=(d,l)=>{if(!d.options?.length)throw new h(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return d.options[0].value;let p;if(l?p=d.options.find(k=>k.name===l)?.label:p=d.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=b("."+t);if(!r)throw new h("Invalid payload for passkeys.");if(de.isPublicKeyCredentialCreationOptions(r)||de.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 Ne=class{config;constructor(e){this.config=new J(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(),o=`${this.getJwtCookieName()}=${e}; expires=${r}`;ee(o)}getJwtCookie(){return L(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:o,refreshToken:s}=e,a=(i,n)=>{if(!n)return;let u=b(n),d=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${d};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),s),a(this.getPayloadSignatureName(),o)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return L(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var z=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(o=>{Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))})})},V=(e,t,r)=>(r||(r=te()),{id:r,username:t,aud:e}),E=async(e,t,r)=>{let o=N(B(JSON.stringify({alg:"ES256",jwk:t}))),s=N(B(JSON.stringify(e))),a=`${o}.${s}`,i=await re(r,a);return`${a}.${i}`};var he=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 Be=e=>`LoginID_${e}_device-id`,I=class extends he{static persistDeviceId(e,t){this.setItem(Be(e),t)}static getDeviceId(e){return this.getItem(Be(e))||""}},ye=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,o=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=o}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:o,keyPath:s,options:a})=>r.createIndex(o,s,a))}},e}async getAllByIndex(e,t){return new Promise((r,o)=>{let s=this.openDb();s.onsuccess=()=>{let a=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>o(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>o(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,o)=>{let s=this.openDb();s.onsuccess=()=>{let a=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):o(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>o(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>o(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 o=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();o.onsuccess=()=>{let s=o.result;s?e(s.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},o.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 o=this.openDb();o.onsuccess=()=>{let s=o.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"))},o.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let o=this.openDb();o.onsuccess=()=>{let s=o.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"))},o.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},pt=1;var ht="lid_c_wtid",yt="lid-wtid-k",ze=class extends ye{constructor(e,t){super(e,pt,t)}async setCheckoutId(){let e=await j(),t=await S(e),r={id:F()},o=await E(r,t,e.privateKey);return await this.putRecord({id:r.id,keyPair:e}),o}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await S(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await S(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}};var me=class extends ze{constructor(){super(ht,yt)}},mt=1,Fe="app_id_idx",ft="username_idx",gt="loginid-trust-store",kt="LoginID_trust-id",ce="app_id_username_idx",x=class extends ye{appId;constructor(e){super(gt,mt,kt,[{name:ft,keyPath:["username"]},{name:Fe,keyPath:["appId"]},{name:ce,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await j(),r=await S(t),o=V(this.appId,e),s=await E(o,r,t.privateKey);return await this.putRecord({id:o.id,appId:this.appId,username:e,keyPair:t}),s}async signWithTrustId(e){let t=await this.getByIndex(ce,[this.appId,e]),r=await S(t.keyPair),o=V(this.appId,e,t.id);return await E(o,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(Fe,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ce,[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)}}},Ue=e=>`LoginID_${e}_mfa-session`,f=class pe extends he{static persistInfo(t,r){this.setItem(Ue(t),r)}static getInfo(t){return this.getItem(Ue(t))}static updateSession(t,r){let o=pe.getInfo(t);o?o.session=r:o={session:r},pe.persistInfo(t,o)}};var m=class{config;service;session;constructor(e){this.config=new J(e),this.service=new ne({BASE:e.baseUrl}),this.session=new Ne(e)}},M=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={app:{id:this.config.getAppId()},deviceInfo:A(),user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:t})}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 w&&(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:[]})}},fe=class extends m{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),o=I.getDeviceId(r),s=A(o),a=De(e,t),i="";t.txPayload&&(i=await new me().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new x(r).setOrSignWithTrustId(e));let u={deviceInfo:s,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}},d=await this.service.mfa.mfaMfaBegin({requestBody:u}),l=ue(d,e);return f.persistInfo(r,l),this.session.logout(),P(l)}async performAction(e,t={}){let r=this.config.getAppId(),o=f.getInfo(r),{payload:s,session:a}=le.mfaOptionValidator(e,o,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=le.validatePasskeyPayload(s);if("rpId"in i){let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}})):await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}}))}if("rp"in i){let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.invokeMfaApi(r,o?.username,async()=>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:s}});return f.updateSession(r,i),P(f.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:s}}));case"external":return await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,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 P(t,r)}async invokeMfaApi(e,t="",r){try{let o=await r(),s=f.getInfo(e);f.persistInfo(e,{...t&&{username:t},flow:s?.flow,next:[]}),this.session.setTokenSet(o),I.persistDeviceId(e,o.deviceId);let a=f.getInfo(e);return P(a,o)}catch(o){if(o instanceof w&&o.status===401&&o.body.session){let s=o.body,a=ue(s,t);return f.persistInfo(e,a),P(a)}throw o}}};var Me=class extends m{constructor(e){super(e)}};z(Me,[m,fe,M]);var Le=Me;var ge=class extends m{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,o={}){let s=this.session.getToken(o),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:s,id:t,requestBody:a})}async deletePasskey(t,r={}){let o=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:o,id:t})}},je=ge;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Ke=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||F()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var We=e=>[...e.crossAuthMethods,...e.fallbackMethods];var ke=class extends m{constructor(t){super(t)}async validateOtp(t,r,o={}){let s=C(t,"",o),a={authCode:r,user:{username:t,usernameType:s.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return v.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",o={}){let s=C(t,"",o),a={user:{username:t,usernameType:s.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")}}},H=ke;var Re=class extends H{constructor(t){super(t)}async createPasskey(t,r="",o={}){let s=this.config.getAppId(),a=I.getDeviceId(s),i=A(a),n=new x(s),u=C(t,r,o);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let d=await n.setOrSignWithTrustId(t),l={app:{id:s},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},...d&&{trustItems:{auth:d}}},p=await this.service.reg.regRegInit({requestBody:l,...u.authzToken&&{authorization:u.authzToken}}),k=await R.createNavigatorCredential(p),Y=await this.service.reg.regRegComplete({requestBody:k}),Je=_(Y);return this.session.setJwtCookie(Y.jwtAccess),I.persistDeviceId(s,a||Y.deviceId),Je}async authenticateWithPasskey(t="",r={}){let o=this.config.getAppId(),s=A(I.getDeviceId(o)),a=new x(o),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:o},deviceInfo:s,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},d=await this.service.auth.authAuthInit({requestBody:u});switch(d.action){case"proceed":{let l=await R.getNavigatorCredential(d,r),p=await this.service.auth.authAuthComplete({requestBody:l}),k=_(p);return this.session.setJwtCookie(k.token),I.persistDeviceId(o,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(k),k}case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=We(d);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw se}}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,o={}){let s=Ke(t,o),a={username:t,txPayload:r,nonce:s.nonce,txType:s.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n},{assertionResult:d}=await R.getNavigatorCredential(u),l={authenticatorData:d.authenticatorData,clientData:d.clientDataJSON,keyHandle:d.credentialId,session:n,signature:d.signature};return await this.service.tx.txTxComplete({requestBody:l})}},$e=Re;var G=class extends m{constructor(t){super(t)}};z(G,[m,$e,H,je,M]);var be=G;var Rt=be;return Qe(bt);})();
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 Tt={};et(Tt,{AbortError:()=>N,ApiError:()=>A,LoginIDMfa:()=>$e,LoginIDWebSDK:()=>we,PasskeyError:()=>h,WebAuthnHelper:()=>R,createPasskeyCredential:()=>$,default:()=>It,getPasskeyCredential:()=>V,isConditionalUIAvailable:()=>j,isPlatformAuthenticatorAvailable:()=>M});var I=async e=>{let t=JSON.stringify(await Ae()),r=await Ie(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},M=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},j=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},Ae=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await M(),t=await j();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},Ie=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},K=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},te=e=>{document.cookie=e},T=e=>{document.cookie=`${e}=; expires=${new Date}`};var N=class extends Error{constructor(e){super(e),this.name="AbortError"}},y=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},h=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var D=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),B=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Te=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=B(t);return D(s)},O=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Te(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},b=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},re=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},W=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),v=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),se=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(s)},Oe=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},F=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Oe(24);var E=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new N("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},ve=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new h("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new h("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new h("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new h("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new h("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Ee=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new h("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new h("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new h(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new h("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},st=new y("User needs to be logged in to perform this operation."),oe=new y("No login options available."),$=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:O(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:O(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?ve(o,s):o}},V=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:O(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:O(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Ee(o,s):o}},R=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?E.assignWebAuthnAbortController(t.abortController):(E.renewWebAuthnAbortController(),t.abortController=E.abortController);let o=await V(r,t),a=o.response;return{assertionResult:{authenticatorData:k(a.authenticatorData),clientDataJSON:k(a.clientDataJSON),credentialId:o.id,signature:k(a.signature),...a.userHandle&&{userHandle:k(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;E.renewWebAuthnAbortController();let s=await $(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:k(o.attestationObject),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:k(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var U=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},J=(e,t,r)=>(r||(r=re()),{id:r,username:t,aud:e}),S=async(e,t,r)=>{let s=D(B(JSON.stringify({alg:"ES256",jwk:t}))),o=D(B(JSON.stringify(e))),a=`${s}.${o}`,i=await se(r,a);return`${a}.${i}`};var ne=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var Se=e=>`LoginID_${e}_device-id`,w=class extends ne{static persistDeviceId(e,t){this.setItem(Se(e),t)}static getDeviceId(e){return this.getItem(Se(e))||""}},ue=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new c("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var at="lid_c_wtid",it="lid-wtid-k",qe=class extends ue{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await W(),t=await v(e),r={id:F()},s=await S(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await v(e.keyPair),r={id:e.id};return await S(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new c("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new c("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var le=class extends qe{constructor(){super(at,it)}},nt=1,Ce="app_id_idx",ut="username_idx",lt="loginid-trust-store",dt="LoginID_trust-id",ae="app_id_username_idx",q=class extends ue{appId;constructor(e){super(lt,nt,dt,[{name:ut,keyPath:["username"]},{name:Ce,keyPath:["appId"]},{name:ae,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await W(),r=await v(t),s=J(this.appId,e),o=await S(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(ae,[this.appId,e]),r=await v(t.keyPair),s=J(this.appId,e,t.id);return await S(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof c&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ce,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(ae,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Pe=e=>`LoginID_${e}_mfa-session`,m=class ie extends ne{static persistInfo(t,r){this.setItem(Pe(t),r)}static getInfo(t){return this.getItem(Pe(t))}static updateSession(t,r){let s=ie.getInfo(t);s?s.session=r:s={session:r},ie.persistInfo(t,s)}};var xe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},_e=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Ne=class{constructor(e){this.config=e}},De=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Be=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new De("Request aborted"))}}get isCancelled(){return this.#e}},A=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},ce=e=>e!=null,z=e=>typeof e=="string",de=e=>z(e)&&e!=="",pe=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),Fe=e=>e instanceof FormData,ct=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},pt=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{ce(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},ht=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${pt(t.query)}`:o},yt=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{z(o)||pe(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>ce(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},G=async(e,t)=>typeof t=="function"?t(e):t,mt=async(e,t)=>{let[r,s,o,a]=await Promise.all([G(t,e.TOKEN),G(t,e.USERNAME),G(t,e.PASSWORD),G(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>ce(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(de(r)&&(i.Authorization=`Bearer ${r}`),de(s)&&de(o)){let n=ct(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:pe(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":z(t.body)?i["Content-Type"]="text/plain":Fe(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ft=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):z(e.body)||pe(e.body)||Fe(e.body)?e.body:JSON.stringify(e.body)},gt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},kt=(e,t)=>{if(t){let r=e.headers.get(t);if(z(r))return r}},Rt=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},bt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new A(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new A(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},wt=(e,t)=>new Be(async(r,s,o)=>{try{let a=ht(e,t),i=yt(t),n=ft(t),u=await mt(e,t);if(!o.isCancelled){let l=await gt(e,t,a,n,i,u,o),d=await Rt(l),p=kt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};bt(t,g),r(g.body)}}catch(a){s(a)}}),At=class extends Ne{constructor(e){super(e)}request(e){return wt(this.config,e)}},Ue=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Le=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},Me=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},he=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=At){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Ue(this.request),this.clientEvents=new xe(this.request),this.mfa=new ze(this.request),this.passkeys=new _e(this.request),this.reg=new Le(this.request),this.tx=new Me(this.request)}};var je=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ye=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),x=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(d=>(a==="otp:sms"||a==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let d=o.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],s=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var H=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},fe=class me{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new y("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new y("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new y(`No matching factor found for ${t}.`);let u=(l,d)=>{if(!l.options?.length)throw new y(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(d?p=l.options.find(g=>g.name===d)?.label:p=l.options[0]?.label,!p)throw new y(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new y("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new y("Payload is required for passkeys.");let r=b("."+t);if(!r)throw new y("Invalid payload for passkeys.");if(me.isPublicKeyCredentialCreationOptions(r)||me.isPublicKeyCredentialRequestOptions(r))return r;throw new y("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Ke=class{config;constructor(e){this.config=new H(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=b(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=b(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;te(s)}getJwtCookie(){return K(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){T(this.getJwtCookieName()),T(this.getIdTokenName()),T(this.getAccessTokenName()),T(this.getRefreshTokenName()),T(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=b(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return K(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new H(e),this.service=new he({BASE:e.baseUrl}),this.session=new Ke(e)}},L=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await I(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof A&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},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){let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},ge=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await I(s),a=je(e,t),i="";t.txPayload&&(i=await new le().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new q(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),d=ye(l,e);return m.persistInfo(r,d),this.session.logout(),x(d)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=fe.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=fe.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await R.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await R.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),x(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new y(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return x(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return x(a,s)}catch(s){if(s instanceof A&&s.status===401&&s.body.session){let o=s.body,a=ye(o,t);return m.persistInfo(e,a),x(a)}if(s instanceof Error){let o=new Y(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var We=class extends f{constructor(e){super(e)}};U(We,[f,ge,L]);var $e=We;var ke=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ve=ke;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Je=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||F()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var Ge=e=>[...e.crossAuthMethods,...e.fallbackMethods];var Re=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return E.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},X=Re;var be=class extends X{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await I(a),n=new q(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&b(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:d,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await R.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let Z=await this.service.reg.regRegComplete({requestBody:g}),Ye=_(Z);return this.session.setJwtCookie(Z.jwtAccess),w.persistDeviceId(o,a||Z.deviceId),Ye})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await I(w.getDeviceId(s)),a=new q(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let d=await R.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:d}),g=_(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=Ge(l);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw oe}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=Je(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await R.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:d})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new Y(this.config.getConfig()).reportError(t,s),s}}},He=be;var Q=class extends f{constructor(t){super(t)}};U(Q,[f,He,X,Ve,L]);var we=Q;var It=we;return rt(Tt);})();
2
2
  //# sourceMappingURL=index.global.js.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var w=e=>{let t={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return e&&(t.deviceId=e),t},ge=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},ke=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},M=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},G=e=>{document.cookie=e},A=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}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var D=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),N=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],o=0;for(;o<e.length;){let i=e.charCodeAt(o++),n=e.charCodeAt(o++),u=e.charCodeAt(o++),d=i<<16|n<<8|u;r.push(t[d>>18&63]+t[d>>12&63]+t[d>>6&63]+t[d&63])}let s=r.join(""),a=e.length%3;return a?s.slice(0,a-3)+"===".slice(a||3):s},Re=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},o=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let s=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(s=(s<<6)+u,a+=6;a>=8;)i+=o(s>>(a-=8)&255)}return i},g=e=>{let t="",r=new Uint8Array(e);for(let s=0;s<r.byteLength;s++)t+=String.fromCharCode(r[s]);let o=N(t);return D(o)},T=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Re(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r.buffer},R=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},Y=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let o=0;o<e;o++)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),X=async(e,t)=>{let r=new TextEncoder().encode(t),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return g(o)},be=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},B=()=>window.crypto?.randomUUID?window.crypto.randomUUID():be(24);var S=class q{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new L("Cancelling current WebAuthn request");q.abortController.abort(t)};static renewWebAuthnAbortController=()=>{q.abortWebAuthnRequest();let t=new AbortController;q.abortController=t};static assignWebAuthnAbortController=t=>{q.abortWebAuthnRequest(),q.abortController=t}},Ie=(e,t)=>{let r=e.name,{publicKey:o}=t;if(r==="ConstraintError"){if(o?.authenticatorSelection?.requireResidentKey===!0)return new y("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(o?.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_SEE_CAUSE_FIELD",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=o?.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},we=(e,t)=>{let r=e.name,{publicKey:o}=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_SEE_CAUSE_FIELD",e);if(r==="SecurityError"){let s=o?.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},$e=new h("User needs to be logged in to perform this operation."),Q=new h("No login options available."),Z=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let s of e.excludeCredentials){let a={id:T(s.id),transports:s.transports,type:s.type};t.push(a)}}let r=e.pubKeyCredParams,o={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 s=await navigator.credentials.create(o);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?Ie(s,o):s}},ee=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let s of e.allowCredentials){let a={id:T(s.id),transports:s.transports,type:s.type};r.push(a)}}let o={...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 s=await navigator.credentials.get(o);if(s===null)throw new Error("Failed to create the passkey credential.");return s}catch(s){throw s instanceof Error?we(s,o):s}},b=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:o}=e;t.abortController?S.assignWebAuthnAbortController(t.abortController):(S.renewWebAuthnAbortController(),t.abortController=S.abortController);let s=await ee(r,t),a=s.response;return{assertionResult:{authenticatorData:g(a.authenticatorData),clientDataJSON:g(a.clientDataJSON),credentialId:s.id,signature:g(a.signature),...a.userHandle&&{userHandle:g(a.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;S.renewWebAuthnAbortController();let o=await Z(t),s=o.response,a=s.getPublicKey&&s.getPublicKey(),i=s.getPublicKeyAlgorithm&&s.getPublicKeyAlgorithm(),n=s.getAuthenticatorData&&s.getAuthenticatorData(),u=s.getTransports&&s.getTransports();return{creationResult:{attestationObject:g(s.attestationObject),clientDataJSON:g(s.clientDataJSON),credentialId:o.id,...a&&{publicKey:g(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:g(n)},...u&&{transports:u}},session:r}}};var Ae=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."}})}},Te=class{constructor(e){this.config=e}},Oe=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Se=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 o=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.#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(o,s,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 Oe("Request aborted"))}}get isCancelled(){return this.#e}},v=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,F=e=>typeof e=="string",te=e=>F(e)&&e!=="",se=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,Je=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},Ve=e=>{let t=[],r=(s,a)=>{t.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(a))}`)},o=(s,a)=>{re(a)&&(Array.isArray(a)?a.forEach(i=>{o(s,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{o(`${s}[${i}]`,n)}):r(s,a))};return Object.entries(e).forEach(([s,a])=>{o(s,a)}),t.length>0?`?${t.join("&")}`:""},He=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,o=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),s=`${e.BASE}${o}`;return t.query?`${s}${Ve(t.query)}`:s},Ge=e=>{if(e.formData){let t=new FormData,r=(o,s)=>{F(s)||se(s)?t.append(o,s):t.append(o,JSON.stringify(s))};return Object.entries(e.formData).filter(([o,s])=>re(s)).forEach(([o,s])=>{Array.isArray(s)?s.forEach(a=>r(o,a)):r(o,s)}),t}},K=async(e,t)=>typeof t=="function"?t(e):t,Ye=async(e,t)=>{let[r,o,s,a]=await Promise.all([K(t,e.TOKEN),K(t,e.USERNAME),K(t,e.PASSWORD),K(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>re(u)).reduce((n,[u,d])=>({...n,[u]:String(d)}),{});if(te(r)&&(i.Authorization=`Bearer ${r}`),te(o)&&te(s)){let n=Je(`${o}:${s}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:se(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":F(t.body)?i["Content-Type"]="text/plain":ve(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},Xe=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):F(e.body)||se(e.body)||ve(e.body)?e.body:JSON.stringify(e.body)},Qe=async(e,t,r,o,s,a,i)=>{let n=new AbortController,u={headers:a,body:o??s,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},Ze=(e,t)=>{if(t){let r=e.headers.get(t);if(F(r))return r}},et=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)}},tt=(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 v(e,t,r);if(!t.ok){let o=t.status??"unknown",s=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new v(e,t,`Generic Error: status: ${o}; status text: ${s}; body: ${a}`)}},rt=(e,t)=>new Se(async(r,o,s)=>{try{let a=He(e,t),i=Ge(t),n=Xe(t),u=await Ye(e,t);if(!s.isCancelled){let d=await Qe(e,t,a,n,i,u,s),l=await et(d),p=Ze(d,t.responseHeader),k={url:a,ok:d.ok,status:d.status,statusText:d.statusText,body:p??l};tt(t,k),r(k.body)}}catch(a){o(a)}}),st=class extends Te{constructor(e){super(e)}request(e){return rt(this.config,e)}},Ee=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."}})}},Ce=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."}})}mfaMfaError({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/error",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."}})}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."}})}},qe=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."}})}},Pe=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."}})}},oe=class{auth;mfa;passkeys;reg;tx;request;constructor(e,t=st){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 Ee(this.request),this.mfa=new Ce(this.request),this.passkeys=new Ae(this.request),this.reg=new qe(this.request),this.tx=new Pe(this.request)}};var xe=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),ae=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),P=(e,t)=>{let r=e?.next?.map(s=>{let{name:a,label:i,desc:n}=s.action,u={type:a,label:i,...n&&{description:n}};if(s.options){let d=s.options.filter(l=>(a==="otp:sms"||a==="otp:email")&&l.label).map(l=>l.label).filter(Boolean);if(d.length&&(u.options=d),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let l=s.options.find(p=>p.value);l&&(u.value=l.value)}}return u})||[],o=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(s=>e?.next?.some(a=>a.action.name===s));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...o&&{nextAction:o},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 W=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.")}},ne=class ie{static mfaOptionValidator(t,r,o){let{session:s=r?.session,payload:a=""}=o;if(!s)throw new h("A session is required to perform MFA factor.");if(a)return{session:s,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(d=>d.action.name===t);if(!n)throw new h(`No matching factor found for ${t}.`);let u=(d,l)=>{if(!d.options?.length)throw new h(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return d.options[0].value;let p;if(l?p=d.options.find(k=>k.name===l)?.label:p=d.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 _e=class{config;constructor(e){this.config=new W(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(),o=`${this.getJwtCookieName()}=${e}; expires=${r}`;G(o)}getJwtCookie(){return M(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){A(this.getJwtCookieName()),A(this.getIdTokenName()),A(this.getAccessTokenName()),A(this.getRefreshTokenName()),A(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:o,refreshToken:s}=e,a=(i,n)=>{if(!n)return;let u=R(n),d=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${d};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),s),a(this.getPayloadSignatureName(),o)}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 U=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(o=>{Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))})})},$=(e,t,r)=>(r||(r=Y()),{id:r,username:t,aud:e}),E=async(e,t,r)=>{let o=D(N(JSON.stringify({alg:"ES256",jwk:t}))),s=D(N(JSON.stringify(e))),a=`${o}.${s}`,i=await X(r,a);return`${a}.${i}`};var le=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 De=e=>`LoginID_${e}_device-id`,I=class extends le{static persistDeviceId(e,t){this.setItem(De(e),t)}static getDeviceId(e){return this.getItem(De(e))||""}},ce=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,o=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=o}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:o,keyPath:s,options:a})=>r.createIndex(o,s,a))}},e}async getAllByIndex(e,t){return new Promise((r,o)=>{let s=this.openDb();s.onsuccess=()=>{let a=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>o(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>o(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,o)=>{let s=this.openDb();s.onsuccess=()=>{let a=s.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):o(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>o(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},s.onerror=()=>o(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 o=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();o.onsuccess=()=>{let s=o.result;s?e(s.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},o.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 o=this.openDb();o.onsuccess=()=>{let s=o.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"))},o.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let o=this.openDb();o.onsuccess=()=>{let s=o.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"))},o.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},ot=1;var at="lid_c_wtid",it="lid-wtid-k",Fe=class extends ce{constructor(e,t){super(e,ot,t)}async setCheckoutId(){let e=await j(),t=await O(e),r={id:B()},o=await E(r,t,e.privateKey);return await this.putRecord({id:r.id,keyPair:e}),o}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await O(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await O(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}};var pe=class extends Fe{constructor(){super(at,it)}},nt=1,Ne="app_id_idx",ut="username_idx",dt="loginid-trust-store",lt="LoginID_trust-id",ue="app_id_username_idx",x=class extends ce{appId;constructor(e){super(dt,nt,lt,[{name:ut,keyPath:["username"]},{name:Ne,keyPath:["appId"]},{name:ue,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await j(),r=await O(t),o=$(this.appId,e),s=await E(o,r,t.privateKey);return await this.putRecord({id:o.id,appId:this.appId,username:e,keyPair:t}),s}async signWithTrustId(e){let t=await this.getByIndex(ue,[this.appId,e]),r=await O(t.keyPair),o=$(this.appId,e,t.id);return await E(o,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(ue,[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)}}},Be=e=>`LoginID_${e}_mfa-session`,f=class de extends le{static persistInfo(t,r){this.setItem(Be(t),r)}static getInfo(t){return this.getItem(Be(t))}static updateSession(t,r){let o=de.getInfo(t);o?o.session=r:o={session:r},de.persistInfo(t,o)}};var m=class{config;service;session;constructor(e){this.config=new W(e),this.service=new oe({BASE:e.baseUrl}),this.session=new _e(e)}},z=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={app:{id:this.config.getAppId()},deviceInfo:w(),user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:t})}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 v&&(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:[]})}},he=class extends m{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),o=I.getDeviceId(r),s=w(o),a=xe(e,t),i="";t.txPayload&&(i=await new pe().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new x(r).setOrSignWithTrustId(e));let u={deviceInfo:s,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}},d=await this.service.mfa.mfaMfaBegin({requestBody:u}),l=ae(d,e);return f.persistInfo(r,l),this.session.logout(),P(l)}async performAction(e,t={}){let r=this.config.getAppId(),o=f.getInfo(r),{payload:s,session:a}=ne.mfaOptionValidator(e,o,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=ne.validatePasskeyPayload(s);if("rpId"in i){let n=await b.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}})):await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}}))}if("rp"in i){let n=await b.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.invokeMfaApi(r,o?.username,async()=>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:s}});return f.updateSession(r,i),P(f.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:s}}));case"external":return await this.invokeMfaApi(r,o?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,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 P(t,r)}async invokeMfaApi(e,t="",r){try{let o=await r(),s=f.getInfo(e);f.persistInfo(e,{...t&&{username:t},flow:s?.flow,next:[]}),this.session.setTokenSet(o),I.persistDeviceId(e,o.deviceId);let a=f.getInfo(e);return P(a,o)}catch(o){if(o instanceof v&&o.status===401&&o.body.session){let s=o.body,a=ae(s,t);return f.persistInfo(e,a),P(a)}throw o}}};var Ue=class extends m{constructor(e){super(e)}};U(Ue,[m,he,z]);var ct=Ue;var ye=class extends m{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,o={}){let s=this.session.getToken(o),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:s,id:t,requestBody:a})}async deletePasskey(t,r={}){let o=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:o,id:t})}},ze=ye;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),Me=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||B()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var Le=e=>[...e.crossAuthMethods,...e.fallbackMethods];var me=class extends m{constructor(t){super(t)}async validateOtp(t,r,o={}){let s=C(t,"",o),a={authCode:r,user:{username:t,usernameType:s.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return S.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",o={}){let s=C(t,"",o),a={user:{username:t,usernameType:s.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=me;var fe=class extends J{constructor(t){super(t)}async createPasskey(t,r="",o={}){let s=this.config.getAppId(),a=I.getDeviceId(s),i=w(a),n=new x(s),u=C(t,r,o);u.authzToken=this.session.getToken(u),u.authzToken&&R(u.authzToken).username!==t&&(u.authzToken="");let d=await n.setOrSignWithTrustId(t),l={app:{id:s},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},...d&&{trustItems:{auth:d}}},p=await this.service.reg.regRegInit({requestBody:l,...u.authzToken&&{authorization:u.authzToken}}),k=await b.createNavigatorCredential(p),H=await this.service.reg.regRegComplete({requestBody:k}),We=_(H);return this.session.setJwtCookie(H.jwtAccess),I.persistDeviceId(s,a||H.deviceId),We}async authenticateWithPasskey(t="",r={}){let o=this.config.getAppId(),s=w(I.getDeviceId(o)),a=new x(o),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:o},deviceInfo:s,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},d=await this.service.auth.authAuthInit({requestBody:u});switch(d.action){case"proceed":{let l=await b.getNavigatorCredential(d,r),p=await this.service.auth.authAuthComplete({requestBody:l}),k=_(p);return this.session.setJwtCookie(k.token),I.persistDeviceId(o,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(k),k}case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=Le(d);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw Q}}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,o={}){let s=Me(t,o),a={username:t,txPayload:r,nonce:s.nonce,txType:s.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n},{assertionResult:d}=await b.getNavigatorCredential(u),l={authenticatorData:d.authenticatorData,clientData:d.clientDataJSON,keyHandle:d.credentialId,session:n,signature:d.signature};return await this.service.tx.txTxComplete({requestBody:l})}},je=fe;var V=class extends m{constructor(t){super(t)}};U(V,[m,je,J,ze,z]);var Ke=V;var Js=Ke;export{L as AbortError,v as ApiError,ct as LoginIDMfa,Ke as LoginIDWebSDK,y as PasskeyError,b as WebAuthnHelper,Z as createPasskeyCredential,Js as default,ee as getPasskeyCredential,ke as isConditionalUIAvailable,ge as isPlatformAuthenticatorAvailable};
1
+ var A=async e=>{let t=JSON.stringify(await be()),r=await we(),s={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:"",hasBluetooth:r,webauthnCapabilities:t};return e&&(s.deviceId=e),s},Y=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}},X=async()=>{try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}},be=async()=>{try{if(!window.PublicKeyCredential)return{};if(!window.PublicKeyCredential.getClientCapabilities){let e=await Y(),t=await X();return{userVerifyingPlatformAuthenticator:e,conditionalGet:t}}return await window.PublicKeyCredential.getClientCapabilities()}catch{return{}}},we=async()=>{try{return navigator.bluetooth?await navigator.bluetooth.getAvailability():!1}catch{return!1}},L=e=>{let t=`; ${document.cookie}`.split(`; ${e}=`);if(t&&t.length===2)return t.pop().split(";").shift()},Q=e=>{document.cookie=e},I=e=>{document.cookie=`${e}=; expires=${new Date}`};var M=class extends Error{constructor(e){super(e),this.name="AbortError"}},h=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},y=class extends Error{code;constructor(e,t,r){super(e),this.code=t,this.cause=r}},c=class extends Error{code;constructor(e,t){super(e),this.name="StorageError",this.code=t}};var N=e=>e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),D=e=>{if(!e)return e;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<e.length;){let i=e.charCodeAt(s++),n=e.charCodeAt(s++),u=e.charCodeAt(s++),l=i<<16|n<<8|u;r.push(t[l>>18&63]+t[l>>12&63]+t[l>>6&63]+t[l&63])}let o=r.join(""),a=e.length%3;return a?o.slice(0,a-3)+"===".slice(a||3):o},Ae=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let n=0;n<64;n++)r[t.charAt(n)]=n;let o=0,a=0,i="";for(let n of e){let u=r[n];if(u!==void 0)for(o=(o<<6)+u,a+=6;a>=8;)i+=s(o>>(a-=8)&255)}return i},k=e=>{let t="",r=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)t+=String.fromCharCode(r[o]);let s=D(t);return N(s)},T=e=>{e=e.replace(/-/g,"+").replace(/_/g,"/");let t=Ae(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r.buffer},R=e=>{try{let t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(r)}catch(t){console.error(t)}},Z=(e=25)=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<e;s++)r+=t.charAt(Math.floor(Math.random()*t.length));return r},j=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),O=async e=>await window.crypto.subtle.exportKey("jwk",e.publicKey),ee=async(e,t)=>{let r=new TextEncoder().encode(t),s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e,r);return k(s)},Ie=(e=12)=>{let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,r=>r.toString(36)).join("").slice(0,e)},B=()=>window.crypto?.randomUUID?window.crypto.randomUUID():Ie(24);var v=class P{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let t=new M("Cancelling current WebAuthn request");P.abortController.abort(t)};static renewWebAuthnAbortController=()=>{P.abortWebAuthnRequest();let t=new AbortController;P.abortController=t};static assignWebAuthnAbortController=t=>{P.abortWebAuthnRequest(),P.abortController=t}},Te=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new y("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",e);if(s?.authenticatorSelection?.userVerification==="required")return new y("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",e)}if(r==="InvalidStateError")return new y("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",e);if(r==="NotAllowedError")return new y("Passkey creation has failed","ERROR_GENERAL_ERROR",e);if(r==="NotSupportedError")return new y("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",e);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new y(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new y("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},Oe=(e,t)=>{let r=e.name,{publicKey:s}=t;if(r==="AbortError"&&t.signal instanceof AbortSignal)return new y("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",e);if(r==="NotAllowedError")return new y("Passkey authentication has failed","ERROR_GENERAL_ERROR",e);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new y(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",e)}return r==="UnknownError"?new y("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",e):e},He=new h("User needs to be logged in to perform this operation."),te=new h("No login options available."),re=async e=>{let t;if(e.excludeCredentials!==void 0){t=[];for(let o of e.excludeCredentials){let a={id:T(o.id),transports:o.transports,type:o.type};t.push(a)}}let r=e.pubKeyCredParams,s={publicKey:{attestation:e.attestation,authenticatorSelection:{...e.authenticatorSelection},challenge:T(e.challenge),excludeCredentials:t,extensions:e.extensions,pubKeyCredParams:r,rp:e.rp,timeout:e.timeout,user:{...e.user,id:T(e.user.id)}}};try{let o=await navigator.credentials.create(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Te(o,s):o}},se=async(e,t={})=>{let r;if(e.allowCredentials!==void 0){r=[];for(let o of e.allowCredentials){let a={id:T(o.id),transports:o.transports,type:o.type};r.push(a)}}let s={...t.autoFill&&{mediation:"conditional"},...t.abortController&&{signal:t.abortController.signal},publicKey:{allowCredentials:r,challenge:T(e.challenge),extensions:e.extensions,rpId:e.rpId,timeout:e.timeout,userVerification:e.userVerification}};try{let o=await navigator.credentials.get(s);if(o===null)throw new Error("Failed to create the passkey credential.");return o}catch(o){throw o instanceof Error?Oe(o,s):o}},b=class{static async getNavigatorCredential(e,t={}){let{assertionOptions:r,session:s}=e;t.abortController?v.assignWebAuthnAbortController(t.abortController):(v.renewWebAuthnAbortController(),t.abortController=v.abortController);let o=await se(r,t),a=o.response;return{assertionResult:{authenticatorData:k(a.authenticatorData),clientDataJSON:k(a.clientDataJSON),credentialId:o.id,signature:k(a.signature),...a.userHandle&&{userHandle:k(a.userHandle)}},session:s}}static async createNavigatorCredential(e){let{registrationRequestOptions:t,session:r}=e;v.renewWebAuthnAbortController();let s=await re(t),o=s.response,a=o.getPublicKey&&o.getPublicKey(),i=o.getPublicKeyAlgorithm&&o.getPublicKeyAlgorithm(),n=o.getAuthenticatorData&&o.getAuthenticatorData(),u=o.getTransports&&o.getTransports();return{creationResult:{attestationObject:k(o.attestationObject),clientDataJSON:k(o.clientDataJSON),credentialId:s.id,...a&&{publicKey:k(a)},...i&&{publicKeyAlgorithm:i},...n&&{authenticatorData:k(n)},...u&&{transports:u}},session:r}}};var F=(e,t)=>{t.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(e.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},K=(e,t,r)=>(r||(r=Z()),{id:r,username:t,aud:e}),E=async(e,t,r)=>{let s=N(D(JSON.stringify({alg:"ES256",jwk:t}))),o=N(D(JSON.stringify(e))),a=`${s}.${o}`,i=await ee(r,a);return`${a}.${i}`};var ie=class{static setItem(e,t){if(t!==void 0){let r=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,r)}}static getItem(e){let t=localStorage.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}}};var ve=e=>`LoginID_${e}_device-id`,w=class extends ie{static persistDeviceId(e,t){this.setItem(ve(e),t)}static getDeviceId(e){return this.getItem(ve(e))||""}},ne=class{dbName;dbVersion;storeKey;indexes;constructor(e,t,r,s=[]){this.dbName=e,this.dbVersion=t,this.storeKey=r,this.indexes=s}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let t=e.result;if(!t.objectStoreNames.contains(this.storeKey)){let r=t.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:s,keyPath:o,options:a})=>r.createIndex(s,o,a))}},e}async getAllByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(t);a.onsuccess=()=>{r(a.result)},a.onerror=()=>s(new c(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,t){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let a=o.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(t);a.onsuccess=()=>{let i=a.result;i?r(i):s(new c(`No record found for ${t} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},a.onerror=()=>s(new c(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getFirstRecord(){return new Promise((e,t)=>{let r=this.openDb();r.onsuccess=()=>{let s=r.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).openCursor();s.onsuccess=()=>{let o=s.result;o?e(o.value):t(new c("No records found in the store.","ERROR_STORAGE_NOT_FOUND"))},s.onerror=()=>t(new c("Failed to fetch first record.","ERROR_STORAGE_FAILED"))},r.onerror=()=>t(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to save record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async deleteRecord(e){return new Promise((t,r)=>{let s=this.openDb();s.onsuccess=()=>{let o=s.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(new c("Failed to delete record.","ERROR_STORAGE_FAILED"))},s.onerror=()=>r(new c("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},Ye=1;var Xe="lid_c_wtid",Qe="lid-wtid-k",Ce=class extends ne{constructor(e,t){super(e,Ye,t)}async setCheckoutId(){let e=await j(),t=await O(e),r={id:B()},s=await E(r,t,e.privateKey);return await this.putRecord({id:r.id,valid:!1,keyPair:e}),s}async getCheckoutId(){try{let e=await this.getFirstRecord(),t=await O(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return null;throw e}}async signWithCheckoutId(){let e=await this.getFirstRecord(),t=await O(e.keyPair),r={id:e.id};return await E(r,t,e.keyPair.privateKey)}async setOrSignWithCheckoutId(){try{return await this.signWithCheckoutId()}catch(e){return e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND"?await this.setCheckoutId():(console.log("IndexDB error: "+e),"")}}async markCheckoutIdAsValid(){try{let e=await this.getFirstRecord();e.valid=!0,await this.putRecord(e)}catch{throw new c("Failed to mark checkout ID as valid.","ERROR_STORAGE_UPDATE_FAILED")}}async isCheckoutIdValid(){try{let e=await this.getFirstRecord();return e&&e.valid===!0}catch(e){if(e instanceof c&&e.code==="ERROR_STORAGE_NOT_FOUND")return!1;throw new c("Failed to check checkout ID validity.","ERROR_STORAGE_FAILED")}}};var ue=class extends Ce{constructor(){super(Xe,Qe)}},Ze=1,Ee="app_id_idx",et="username_idx",tt="loginid-trust-store",rt="LoginID_trust-id",oe="app_id_username_idx",q=class extends ne{appId;constructor(e){super(tt,Ze,rt,[{name:et,keyPath:["username"]},{name:Ee,keyPath:["appId"]},{name:oe,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let t=await j(),r=await O(t),s=K(this.appId,e),o=await E(s,r,t.privateKey);return await this.putRecord({id:s.id,appId:this.appId,username:e,keyPair:t}),o}async signWithTrustId(e){let t=await this.getByIndex(oe,[this.appId,e]),r=await O(t.keyPair),s=K(this.appId,e,t.id);return await E(s,r,t.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(t){return t instanceof c&&t.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+t),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ee,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(oe,[this.appId,e])}catch(t){return console.error("Error retrieving Trust ID Record:",t),null}}async deleteAllExcept(e){try{let t=(await this.getAllTrustIds()).filter(r=>r.username!==e).map(r=>this.deleteRecord(r.id));await Promise.all(t)}catch(t){console.error("Error deleting Trust IDs:",t)}}},Se=e=>`LoginID_${e}_mfa-session`,m=class ae extends ie{static persistInfo(t,r){this.setItem(Se(t),r)}static getInfo(t){return this.getItem(Se(t))}static updateSession(t,r){let s=ae.getInfo(t);s?s.session=r:s={session:r},ae.persistInfo(t,s)}};var Pe=class{constructor(e){this.httpRequest=e}clientEventsSubmit({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/client-events/submit",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},qe=class{constructor(e){this.httpRequest=e}passkeysPasskeysList({authorization:e}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:t}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysPasskeyRename({id:e,requestBody:t,authorization:r}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},body:t,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}passkeysAaguidMetadata({aaguid:e,authorization:t}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:t},errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},xe=class{constructor(e){this.config=e}},_e=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},Ne=class{#t;#r;#e;#s;#a;#i;#o;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#s=[],this.#a=new Promise((t,r)=>{this.#i=t,this.#o=r;let s=i=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(i))},o=i=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#o&&this.#o(i))},a=i=>{this.#t||this.#r||this.#e||this.#s.push(i)};return Object.defineProperty(a,"isResolved",{get:()=>this.#t}),Object.defineProperty(a,"isRejected",{get:()=>this.#r}),Object.defineProperty(a,"isCancelled",{get:()=>this.#e}),e(s,o,a)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,t){return this.#a.then(e,t)}catch(e){return this.#a.catch(e)}finally(e){return this.#a.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#s.length)try{for(let e of this.#s)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#s.length=0,this.#o&&this.#o(new _e("Request aborted"))}}get isCancelled(){return this.#e}},S=class extends Error{url;status;statusText;body;request;constructor(e,t,r){super(r),this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}},de=e=>e!=null,U=e=>typeof e=="string",le=e=>U(e)&&e!=="",ce=e=>typeof e=="object"&&typeof e.type=="string"&&typeof e.stream=="function"&&typeof e.arrayBuffer=="function"&&typeof e.constructor=="function"&&typeof e.constructor.name=="string"&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),De=e=>e instanceof FormData,st=e=>{try{return btoa(e)}catch{return Buffer.from(e).toString("base64")}},ot=e=>{let t=[],r=(o,a)=>{t.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(a))}`)},s=(o,a)=>{de(a)&&(Array.isArray(a)?a.forEach(i=>{s(o,i)}):typeof a=="object"?Object.entries(a).forEach(([i,n])=>{s(`${o}[${i}]`,n)}):r(o,a))};return Object.entries(e).forEach(([o,a])=>{s(o,a)}),t.length>0?`?${t.join("&")}`:""},at=(e,t)=>{let r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(a,i)=>t.path?.hasOwnProperty(i)?r(String(t.path[i])):a),o=`${e.BASE}${s}`;return t.query?`${o}${ot(t.query)}`:o},it=e=>{if(e.formData){let t=new FormData,r=(s,o)=>{U(o)||ce(o)?t.append(s,o):t.append(s,JSON.stringify(o))};return Object.entries(e.formData).filter(([s,o])=>de(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(a=>r(s,a)):r(s,o)}),t}},W=async(e,t)=>typeof t=="function"?t(e):t,nt=async(e,t)=>{let[r,s,o,a]=await Promise.all([W(t,e.TOKEN),W(t,e.USERNAME),W(t,e.PASSWORD),W(t,e.HEADERS)]),i=Object.entries({Accept:"application/json",...a,...t.headers}).filter(([n,u])=>de(u)).reduce((n,[u,l])=>({...n,[u]:String(l)}),{});if(le(r)&&(i.Authorization=`Bearer ${r}`),le(s)&&le(o)){let n=st(`${s}:${o}`);i.Authorization=`Basic ${n}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:ce(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":U(t.body)?i["Content-Type"]="text/plain":De(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},ut=e=>{if(e.body!==void 0)return e.mediaType?.includes("/json")?JSON.stringify(e.body):U(e.body)||ce(e.body)||De(e.body)?e.body:JSON.stringify(e.body)},lt=async(e,t,r,s,o,a,i)=>{let n=new AbortController,u={headers:a,body:s??o,method:t.method,signal:n.signal};return e.WITH_CREDENTIALS&&(u.credentials=e.CREDENTIALS),i(()=>n.abort()),await fetch(r,u)},dt=(e,t)=>{if(t){let r=e.headers.get(t);if(U(r))return r}},ct=async e=>{if(e.status!==204)try{let t=e.headers.get("Content-Type");if(t)return["application/json","application/problem+json"].some(r=>t.toLowerCase().startsWith(r))?await e.json():await e.text()}catch(t){console.error(t)}},pt=(e,t)=>{let r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new S(e,t,r);if(!t.ok){let s=t.status??"unknown",o=t.statusText??"unknown",a=(()=>{try{return JSON.stringify(t.body,null,2)}catch{return}})();throw new S(e,t,`Generic Error: status: ${s}; status text: ${o}; body: ${a}`)}},ht=(e,t)=>new Ne(async(r,s,o)=>{try{let a=at(e,t),i=it(t),n=ut(t),u=await nt(e,t);if(!o.isCancelled){let l=await lt(e,t,a,n,i,u,o),d=await ct(l),p=dt(l,t.responseHeader),g={url:a,ok:l.ok,status:l.status,statusText:l.statusText,body:p??d};pt(t,g),r(g.body)}}catch(a){s(a)}}),yt=class extends xe{constructor(e){super(e)}request(e){return ht(this.config,e)}},Be=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"forbidden: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthInit({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequest({authorization:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp",headers:{Authorization:e},errors:{401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestEmail({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/email",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeRequestSms({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/sms",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}authAuthCodeVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/otp/verify",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},Fe=class{constructor(e){this.httpRequest=e}mfaMfaBegin({requestBody:e,userAgent:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/begin",headers:{"User-Agent":t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpRequest({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/request",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaOtpVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/otp/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyAuth({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/auth",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyReg({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/reg",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaPasskeyTx({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/passkey/tx",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}mfaMfaThirdPartyAuthVerify({requestBody:e,authorization:t}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mfa/third-party/verify",headers:{Authorization:t},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"additional_auth_required: Unauthorized response.",500:"internal_error: Internal Server Error response."}})}},Ue=class{constructor(e){this.httpRequest=e}regRegComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}regRegInit({requestBody:e,userAgent:t,authorization:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":t,Authorization:r},body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",401:"unauthorized: Unauthorized response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}},ze=class{constructor(e){this.httpRequest=e}txTxComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/complete",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",403:"forbidden: Forbidden response.",500:"internal_error: Internal Server Error response."}})}txTxInit({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/tx/init",body:e,mediaType:"application/json",errors:{400:"bad_request: Bad Request response.",404:"not_found: Not Found response.",500:"internal_error: Internal Server Error response."}})}},pe=class{auth;clientEvents;mfa;passkeys;reg;tx;request;constructor(e,t=yt){this.request=new t({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new Be(this.request),this.clientEvents=new Pe(this.request),this.mfa=new Fe(this.request),this.passkeys=new qe(this.request),this.reg=new Ue(this.request),this.tx=new ze(this.request)}};var Le=(e,t)=>({...t,usernameType:t.usernameType||"other",displayName:t.displayName||e}),he=(e,t)=>({username:t,flow:e.flow,session:e.session,next:e.next}),x=(e,t)=>{let r=e?.next?.map(o=>{let{name:a,label:i,desc:n}=o.action,u={type:a,label:i,...n&&{description:n}};if(o.options){let l=o.options.filter(d=>(a==="otp:sms"||a==="otp:email")&&d.label).map(d=>d.label).filter(Boolean);if(l.length&&(u.options=l),a==="passkey:reg"||a==="passkey:auth"||a==="passkey:tx"){let d=o.options.find(p=>p.value);d&&(u.value=d.value)}}return u})||[],s=["passkey:auth","passkey:tx","otp:sms","otp:email","external","passkey:reg"].find(o=>e?.next?.some(a=>a.action.name===o));return{username:e?.username,...e?.username&&{username:e.username},flow:e?.flow,...e?.flow&&{flow:e.flow},remainingFactors:r,...s&&{nextAction:s},isComplete:!!t?.accessToken||!!t?.payloadSignature,...e?.session&&{session:e.session},...t?.idToken&&{idToken:t?.idToken},...t?.accessToken&&{accessToken:t?.accessToken},...t?.refreshToken&&{refreshToken:t?.refreshToken},...t?.payloadSignature&&{payloadSignature:t?.payloadSignature}}};var $=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,t=this.config.baseUrl.match(e);if(t)return t[1];throw new Error("Invalid LoginID base URL. App ID not found.")}getConfig(){return this.config}},me=class ye{static mfaOptionValidator(t,r,s){let{session:o=r?.session,payload:a=""}=s;if(!o)throw new h("A session is required to perform MFA factor.");if(a)return{session:o,payload:a};let i=new Set(["passkey:reg","passkey:auth","passkey:tx","otp:email","otp:sms"]);if(!r?.next||!i.has(t))throw new h("Payload is required to perform MFA factor.");let n=r.next.find(l=>l.action.name===t);if(!n)throw new h(`No matching factor found for ${t}.`);let u=(l,d)=>{if(!l.options?.length)throw new h(`Payload is required for ${t}.`);if(new Set(["passkey:reg","passkey:auth","passkey:tx"]).has(t))return l.options[0].value;let p;if(d?p=l.options.find(g=>g.name===d)?.label:p=l.options[0]?.label,!p)throw new h(`Contact is not found for ${t}.`);return p};switch(t){case"passkey:reg":case"passkey:auth":case"passkey:tx":return{session:o,payload:u(n)};case"otp:email":return{session:o,payload:u(n,"email:primary")};case"otp:sms":return{session:o,payload:u(n)}}throw new h("Payload is required to perform MFA factor.")}static validatePasskeyPayload(t){if(!t)throw new h("Payload is required for passkeys.");let r=R("."+t);if(!r)throw new h("Invalid payload for passkeys.");if(ye.isPublicKeyCredentialCreationOptions(r)||ye.isPublicKeyCredentialRequestOptions(r))return r;throw new h("Invalid payload for passkey.")}static isPublicKeyCredentialCreationOptions(t){return!!(t.rp?.id&&t.challenge&&t.pubKeyCredParams&&t.user?.id)}static isPublicKeyCredentialRequestOptions(t){return!!(t.rpId&&t.challenge&&t.allowCredentials&&t.userVerification)}};var Me=class{config;constructor(e){this.config=new $(e)}getToken(e){return e.authzToken?e.authzToken:this.getJwtCookie()||""}getSessionInfo(){if(!this.isLoggedIn())return null;let e=R(this.getJwtCookie()||this.retrieveToken("accessToken")||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}getIdTokenName(){return`LoginID_${this.config.getAppId()}_id_token`}getAccessTokenName(){return`LoginID_${this.config.getAppId()}_access_token`}getRefreshTokenName(){return`LoginID_${this.config.getAppId()}_refresh_token`}getPayloadSignatureName(){return`LoginID_${this.config.getAppId()}_payload_signature`}setJwtCookie(e){let t=R(e),r=new Date(t.exp*1e3).toUTCString(),s=`${this.getJwtCookieName()}=${e}; expires=${r}`;Q(s)}getJwtCookie(){return L(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()||!!this.retrieveToken("accessToken")}logout(){I(this.getJwtCookieName()),I(this.getIdTokenName()),I(this.getAccessTokenName()),I(this.getRefreshTokenName()),I(this.getPayloadSignatureName())}setTokenSet(e){let{accessToken:t,idToken:r,payloadSignature:s,refreshToken:o}=e,a=(i,n)=>{if(!n)return;let u=R(n),l=u?.exp?new Date(u.exp*1e3).toUTCString():"";document.cookie=`${i}=${n}; Expires=${l};`};a(this.getIdTokenName(),r),a(this.getAccessTokenName(),t),a(this.getRefreshTokenName(),o),a(this.getPayloadSignatureName(),s)}retrieveToken(e){let t={idToken:this.getIdTokenName(),accessToken:this.getAccessTokenName(),refreshToken:this.getRefreshTokenName(),payloadSignature:this.getPayloadSignatureName()}[e];return L(t)||""}getTokenSet(){return{idToken:this.retrieveToken("idToken"),accessToken:this.retrieveToken("accessToken"),refreshToken:this.retrieveToken("refreshToken"),payloadSignature:this.retrieveToken("payloadSignature")}}};var f=class{config;service;session;constructor(e){this.config=new $(e),this.service=new pe({BASE:e.baseUrl}),this.session=new Me(e)}},z=class extends f{constructor(e){super(e)}async verifyConfigSettings(){let e={isValid:!0};try{this.config.getAppId()}catch{return e.isValid=!1,e.solution="Please verify that your base URL is correct.",e.code="invalid_app_id",e.message="Invalid app ID",e}try{let t=await A(),r={app:{id:this.config.getAppId()},deviceInfo:t,user:{username:"",usernameType:"other"}};await this.service.auth.authAuthInit({requestBody:r})}catch(t){return e.isValid=!1,e.solution="Verify that your application exists and the base URL is correct.",e.code="unknown_error",e.message="Unknown error.",t instanceof S&&(e.code=t.body.msgCode||"unknown_error",e.message=t.body.msg||t.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){let e=this.config.getAppId();this.session.logout(),m.persistInfo(e,{next:[]})}},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){let s=t.cause,o=`${t.code} - ${t.message} - ${s.name} - ${s.message}`;return await this.service.clientEvents.clientEventsSubmit({authorization:e,requestBody:{isError:!0,event:o}})}}},fe=class extends f{constructor(e){super(e)}async beginFlow(e,t={}){let r=this.config.getAppId(),s=w.getDeviceId(r),o=await A(s),a=Le(e,t),i="";t.txPayload&&(i=await new ue().setOrSignWithCheckoutId());let n="";!t.checkoutId&&!i&&(n=await new q(r).setOrSignWithTrustId(e));let u={deviceInfo:o,user:{username:e,usernameType:a.usernameType,displayName:a.displayName},trustItems:{...n&&{auth:n},...i&&{wallet:i},...t.checkoutId&&{merchant:t.checkoutId}},...t.txPayload&&{payload:t.txPayload}},l=await this.service.mfa.mfaMfaBegin({requestBody:u}),d=he(l,e);return m.persistInfo(r,d),this.session.logout(),x(d)}async performAction(e,t={}){let r=this.config.getAppId(),s=m.getInfo(r),{payload:o,session:a}=me.mfaOptionValidator(e,s,t);switch(e){case"passkey:reg":case"passkey:auth":case"passkey:tx":{let i=me.validatePasskeyPayload(o);if("rpId"in i)return await this.invokeMfaApi(r,s?.username,async()=>{let n=await b.getNavigatorCredential({action:"proceed",assertionOptions:i,crossAuthMethods:[],fallbackMethods:[],session:a},{...t.autoFill&&{autoFill:t.autoFill}});return e==="passkey:tx"?await this.service.mfa.mfaMfaPasskeyTx({authorization:a,requestBody:{assertionResult:n.assertionResult}}):await this.service.mfa.mfaMfaPasskeyAuth({authorization:a,requestBody:{assertionResult:n.assertionResult}})});if("rp"in i)return await this.invokeMfaApi(r,s?.username,async()=>{t.displayName&&(i.user.displayName=t.displayName);let n=await b.createNavigatorCredential({action:"proceed",registrationRequestOptions:i,session:a});return await this.service.mfa.mfaMfaPasskeyReg({authorization:a,requestBody:{creationResult:n.creationResult}})});break}case"otp:email":case"otp:sms":{let{session:i}=await this.service.mfa.mfaMfaOtpRequest({authorization:a,requestBody:{method:e==="otp:email"?"email":"sms",option:o}});return m.updateSession(r,i),x(m.getInfo(r))}case"otp:verify":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaOtpVerify({authorization:a,requestBody:{otp:o}}));case"external":return await this.invokeMfaApi(r,s?.username,async()=>await this.service.mfa.mfaMfaThirdPartyAuthVerify({authorization:a,requestBody:{token:o}}))}throw new h(`MFA factor ${e} is not supported in the current MFA flow.`)}getMfaSessionDetails(){let e=this.config.getAppId(),t=m.getInfo(e),r=this.session.getTokenSet();return x(t,r)}async invokeMfaApi(e,t="",r){try{let s=await r(),o=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:o?.flow,next:[]}),this.session.setTokenSet(s),w.persistDeviceId(e,s.deviceId);let a=m.getInfo(e);return x(a,s)}catch(s){if(s instanceof S&&s.status===401&&s.body.session){let o=s.body,a=he(o,t);return m.persistInfo(e,a),x(a)}if(s instanceof Error){let o=new V(this.config.getConfig()),a=this.config.getAppId(),i=m.getInfo(a);i?.session&&o.reportError(i.session,s).then(n=>{n?.session&&m.updateSession(a,n.session)})}throw s}}};var je=class extends f{constructor(e){super(e)}};F(je,[f,fe,z]);var mt=je;var ge=class extends f{constructor(t){super(t)}async listPasskeys(t={}){let r=this.session.getToken(t);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(t,r,s={}){let o=this.session.getToken(s),a={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:t,requestBody:a})}async deletePasskey(t,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:t})}},Ke=ge;var C=(e,t,r)=>({...r,authzToken:t||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||e,callbacks:r.callbacks||{}}),We=(e,t)=>({...C(e,"",t),txType:t.txType||"raw",nonce:t.nonce||B()}),_=(e,t=!0,r=!1)=>({userId:e.userId,token:e.jwtAccess,passkeyId:e.passkeyId,isAuthenticated:t,isFallback:r});var $e=e=>[...e.crossAuthMethods,...e.fallbackMethods];var ke=class extends f{constructor(t){super(t)}async validateOtp(t,r,s={}){let o=C(t,"",s),a={authCode:r,user:{username:t,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:a}),n=_(i);return v.renewWebAuthnAbortController(),this.session.setJwtCookie(n.token),n}async requestAndSendOtp(t,r="email",s={}){let o=C(t,"",s),a={user:{username:t,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:a});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:a});break;default:throw new Error("Invalid message method")}}},J=ke;var Re=class extends J{constructor(t){super(t)}async createPasskey(t,r="",s={}){let o=this.config.getAppId(),a=w.getDeviceId(o),i=await A(a),n=new q(o),u=C(t,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&R(u.authzToken).username!==t&&(u.authzToken="");let l=await n.setOrSignWithTrustId(t),d={app:{id:o},deviceInfo:i,user:{username:t,usernameType:u.usernameType,displayName:u.displayName},passkeyOptions:{...s.crossPlatform&&{securityKey:!0}},...l&&{trustItems:{auth:l}}},p=await this.service.reg.regRegInit({requestBody:d,...u.authzToken&&{authorization:u.authzToken}});return await this.invokePasskeyApi(p.session,async()=>{let g=await b.createNavigatorCredential(p);s.passkeyName&&(g.passkeyName=s.passkeyName);let H=await this.service.reg.regRegComplete({requestBody:g}),Ge=_(H);return this.session.setJwtCookie(H.jwtAccess),w.persistDeviceId(o,a||H.deviceId),Ge})}async authenticateWithPasskey(t="",r={}){let s=this.config.getAppId(),o=await A(w.getDeviceId(s)),a=new q(s),i=C(t,"",r),n=await a.setOrSignWithTrustId(r.autoFill?"":t),u={app:{id:s},deviceInfo:o,user:{username:t,usernameType:i.usernameType},...n&&{trustItems:{auth:n}}},l=await this.service.auth.authAuthInit({requestBody:u});switch(l.action){case"proceed":return await this.invokePasskeyApi(l.session,async()=>{let d=await b.getNavigatorCredential(l,r),p=await this.service.auth.authAuthComplete({requestBody:d}),g=_(p);return this.session.setJwtCookie(g.token),w.persistDeviceId(s,p.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(g),g});case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let p=$e(l);await i.callbacks.onFallback(t,p)}return _({userId:"",jwtAccess:""},!1,!0)}default:throw te}}async authenticateWithPasskeyAutofill(t={}){return t.autoFill=!0,await this.authenticateWithPasskey("",t)}async requestOtp(t,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(t,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(t,r,s={}){let o=We(t,s),a={username:t,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:n}=await this.service.tx.txTxInit({requestBody:a}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:n};return await this.invokePasskeyApi(u.session,async()=>{let{assertionResult:l}=await b.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:n,signature:l.signature};return await this.service.tx.txTxComplete({requestBody:d})})}async invokePasskeyApi(t,r){try{return await r()}catch(s){throw s instanceof Error&&new V(this.config.getConfig()).reportError(t,s),s}}},Ve=Re;var G=class extends f{constructor(t){super(t)}};F(G,[f,Ve,J,Ke,z]);var Je=G;var co=Je;export{M as AbortError,S as ApiError,mt as LoginIDMfa,Je as LoginIDWebSDK,y as PasskeyError,b as WebAuthnHelper,re as createPasskeyCredential,co as default,se as getPasskeyCredential,X as isConditionalUIAvailable,Y as isPlatformAuthenticatorAvailable};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loginid/websdk3",
3
- "version": "3.2.2",
3
+ "version": "3.3.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -46,7 +46,7 @@
46
46
  "path": "./node_modules/cz-conventional-changelog"
47
47
  }
48
48
  },
49
- "dependencies": {
49
+ "devDependencies": {
50
50
  "@loginid/core": "*"
51
51
  }
52
52
  }