@loginid/websdk3 3.2.2 → 3.2.4

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.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 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=>(e||(e=Y()),{id:e,exp:Math.floor(Date.now()/1e3)+60}),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),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);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`,m=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 f=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 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={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(),m.persistInfo(e,{next:[]})}},he=class extends f{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 m.persistInfo(r,l),this.session.logout(),P(l)}async performAction(e,t={}){let r=this.config.getAppId(),o=m.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 m.updateSession(r,i),P(m.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=m.getInfo(e),r=this.session.getTokenSet();return P(t,r)}async invokeMfaApi(e,t="",r){try{let o=await r(),s=m.getInfo(e);m.persistInfo(e,{...t&&{username:t},flow:s?.flow,next:[]}),this.session.setTokenSet(o),I.persistDeviceId(e,o.deviceId);let a=m.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 m.persistInfo(e,a),P(a)}throw o}}};var Ue=class extends f{constructor(e){super(e)}};U(Ue,[f,he,z]);var ct=Ue;var ye=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,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 fe=class extends f{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=fe;var me=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=me;var V=class extends f{constructor(t){super(t)}};U(V,[f,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};
2
2
  //# sourceMappingURL=index.js.map