@loginid/websdk3 3.1.1 → 3.2.3
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/README.md +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2118 -1804
- package/dist/index.global.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +5 -4
- package/dist/index.d.cts +0 -1927
package/README.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var M=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var ge=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},Me=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ze(e))!Ve.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(s=Je(e,o))||s.enumerable});return t};var $e=t=>Me(M({},"__esModule",{value:!0}),t);var lt={};ge(lt,{AbortError:()=>F,ApiError:()=>m,LoginIDAPI:()=>me,LoginIDWebSDK:()=>fe,PasskeyError:()=>d,WebAuthnHelper:()=>L,createPasskeyCredential:()=>I,default:()=>ct,getPasskeyCredential:()=>P,isConditionalUIAvailable:()=>Se,isPlatformAuthenticatorAvailable:()=>Ee});module.exports=$e(lt);var $=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=$;var G=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},Y=G;var Re=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new d("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new d("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new d("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new d("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new d("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},be=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new d("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new d("Passkey authentication has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="SecurityError"){let o=s?.rpId;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},Rt=new Y("User needs to be logged in to perform this operation."),Ce=new Y("No login options available.");var K=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),U=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),u=t.charCodeAt(s++),p=i<<16|a<<8|u;r.push(e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},Ge=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let a=0;a<64;a++)r[e.charAt(a)]=a;let o=0,n=0,i="";for(let a of t){let u=r[a];if(u!==void 0)for(o=(o<<6)+u,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},c=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=U(e);return K(s)},A=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Ge(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},Ae=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),Ie=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},B=t=>{try{let r=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(r).split("").map(o=>"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(e){console.error(e)}},Pe=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},Te=t=>{document.cookie=t},Oe=t=>{document.cookie=`${t}=; expires=${new Date}`},qe=(t=25)=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r="";for(let s=0;s<t;s++)r+=e.charAt(Math.floor(Math.random()*e.length));return r},xe=async()=>await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),Q=async t=>await window.crypto.subtle.exportKey("jwk",t.publicKey),ke=async(t,e)=>{let s=new TextEncoder().encode(e),o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,s);return c(o)};var I=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:A(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:A(t.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?Re(o,s):o}},P=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:A(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortController&&{signal:e.abortController.signal},publicKey:{allowCredentials:r,challenge:A(t.challenge),extensions:t.extensions,rpId:t.rpId,timeout:t.timeout,userVerification:t.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?be(o,s):o}};var D=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e};async function Ee(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Se(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}var L=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await P(s,r),i=n.response;return{assertionResult:{authenticatorData:c(i.authenticatorData),clientDataJSON:c(i.clientDataJSON),credentialId:n.id,signature:c(i.signature),...i.userHandle&&{userHandle:c(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await I(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:c(n.attestationObject),clientDataJSON:c(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:c(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:c(u)},...p&&{transports:p}},session:s}}};var X=class extends Error{constructor(e){super(e),this.name="AbortError"}},F=X;var T=class{constructor(e){this.config=e}};var m=class extends Error{url;status;statusText;body;request;constructor(e,r,s){super(s),this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}};var v=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},O=class{#t;#r;#e;#o;#n;#i;#s;constructor(e){this.#t=!1,this.#r=!1,this.#e=!1,this.#o=[],this.#n=new Promise((r,s)=>{this.#i=r,this.#s=s;let o=a=>{this.#t||this.#r||this.#e||(this.#t=!0,this.#i&&this.#i(a))},n=a=>{this.#t||this.#r||this.#e||(this.#r=!0,this.#s&&this.#s(a))},i=a=>{this.#t||this.#r||this.#e||this.#o.push(a)};return Object.defineProperty(i,"isResolved",{get:()=>this.#t}),Object.defineProperty(i,"isRejected",{get:()=>this.#r}),Object.defineProperty(i,"isCancelled",{get:()=>this.#e}),e(o,n,i)})}get[Symbol.toStringTag](){return"Cancellable Promise"}then(e,r){return this.#n.then(e,r)}catch(e){return this.#n.catch(e)}finally(e){return this.#n.finally(e)}cancel(){if(!(this.#t||this.#r||this.#e)){if(this.#e=!0,this.#o.length)try{for(let e of this.#o)e()}catch(e){console.warn("Cancellation threw an error",e);return}this.#o.length=0,this.#s&&this.#s(new v("Request aborted"))}}get isCancelled(){return this.#e}};var ee=t=>t!=null,_=t=>typeof t=="string",Z=t=>_(t)&&t!=="",te=t=>typeof t=="object"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.arrayBuffer=="function"&&typeof t.constructor=="function"&&typeof t.constructor.name=="string"&&/^(Blob|File)$/.test(t.constructor.name)&&/^(Blob|File)$/.test(t[Symbol.toStringTag]),we=t=>t instanceof FormData,Ye=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Qe=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{ee(n)&&(Array.isArray(n)?n.forEach(i=>{s(o,i)}):typeof n=="object"?Object.entries(n).forEach(([i,a])=>{s(`${o}[${i}]`,a)}):r(o,n))};return Object.entries(t).forEach(([o,n])=>{s(o,n)}),e.length>0?`?${e.join("&")}`:""},Xe=(t,e)=>{let r=t.ENCODE_PATH||encodeURI,s=e.url.replace("{api-version}",t.VERSION).replace(/{(.*?)}/g,(n,i)=>e.path?.hasOwnProperty(i)?r(String(e.path[i])):n),o=`${t.BASE}${s}`;return e.query?`${o}${Qe(e.query)}`:o},Ze=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{_(o)||te(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>ee(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},W=async(t,e)=>typeof e=="function"?e(t):e,et=async(t,e)=>{let[r,s,o,n]=await Promise.all([W(e,t.TOKEN),W(e,t.USERNAME),W(e,t.PASSWORD),W(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>ee(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(Z(r)&&(i.Authorization=`Bearer ${r}`),Z(s)&&Z(o)){let a=Ye(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:te(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":_(e.body)?i["Content-Type"]="text/plain":we(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},tt=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):_(t.body)||te(t.body)||we(t.body)?t.body:JSON.stringify(t.body)},rt=async(t,e,r,s,o,n,i)=>{let a=new AbortController,u={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(u.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,u)},ot=(t,e)=>{if(e){let r=t.headers.get(e);if(_(r))return r}},st=async t=>{if(t.status!==204)try{let e=t.headers.get("Content-Type");if(e)return["application/json","application/problem+json"].some(o=>e.toLowerCase().startsWith(o))?await t.json():await t.text()}catch(e){console.error(e)}},nt=(t,e)=>{let s={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...t.errors}[e.status];if(s)throw new m(t,e,s);if(!e.ok){let o=e.status??"unknown",n=e.statusText??"unknown",i=(()=>{try{return JSON.stringify(e.body,null,2)}catch{return}})();throw new m(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},Be=(t,e)=>new O(async(r,s,o)=>{try{let n=Xe(t,e),i=Ze(e),a=tt(e),u=await et(t,e);if(!o.isCancelled){let p=await rt(t,e,n,a,i,u,o),l=await st(p),y=ot(p,e.responseHeader),R={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:y??l};nt(e,R),r(R.body)}}catch(n){s(n)}});var H=class extends T{constructor(e){super(e)}request(e){return Be(this.config,e)}};var q=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:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/init",headers:{"User-Agent":r},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."}})}};var x=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:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:r},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:r,authorization:s}){return this.httpRequest.request({method:"PUT",url:"/fido2/v2/passkeys/{id}",path:{id:e},headers:{Authorization:s},body:r,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:r}){return this.httpRequest.request({method:"GET",url:"/fido2/v2/passkeys/aaguid/{aaguid}",path:{aaguid:e},headers:{Authorization:r},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."}})}};var k=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:r,authorization:s}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r,Authorization:s},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."}})}};var 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."}})}};var S=class{auth;passkeys;reg;tx;request;constructor(e,r=H){this.request=new r({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 q(this.request),this.passkeys=new x(this.request),this.reg=new k(this.request),this.tx=new E(this.request)}};var re=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https?:\/\/([^.]+)\./,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},j=re;var oe=class{config;constructor(e){this.config=new j(e)}getToken(e){if(e.authzToken)return e.authzToken;{let r=this.getJwtCookie();return r||""}}getSessionInfo(){if(!this.isLoggedIn())return null;let e=B(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=B(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;Te(o)}getJwtCookie(){return Pe(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}logout(){Oe(this.getJwtCookieName())}},De=oe;var se=class{config;service;session;constructor(e){this.config=new j(e),this.service=new S({BASE:e.baseUrl}),this.session=new De(e)}},f=se;var ne=class extends f{constructor(e){super(e)}async listPasskeys(e={}){let r=this.session.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.session.getToken(s),n={name:r};await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n})}async deletePasskey(e,r={}){let s=this.session.getToken(r);await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e})}},ve=ne;var g=(t,e,r)=>({...r,authzToken:e||r.authzToken||"",usernameType:r.usernameType||"other",displayName:r.displayName||t,callbacks:r.callbacks||{}}),_e=(t,e)=>({...g(t,"",e),txType:e.txType||"raw",nonce:e.nonce||Ae()}),w=(t,e=!0,r=!1)=>({userId:t.userId,token:t.jwtAccess,passkeyId:t.passkeyId,isAuthenticated:e,isFallback:r});var ie=class t{static abortController=new AbortController;static abortWebAuthnRequest=()=>{let e=new F("Cancelling current WebAuthn request");t.abortController.abort(e)};static renewWebAuthnAbortController=()=>{t.abortWebAuthnRequest();let e=new AbortController;t.abortController=e};static assignWebAuthnAbortController=e=>{t.abortWebAuthnRequest(),t.abortController=e}},b=ie;var Ne=t=>`LoginID_${t}_device-id`,C=class{static persistDeviceId(e,r){r&&localStorage.setItem(Ne(e),r)}static getDeviceId(e){return localStorage.getItem(Ne(e))||""}};var ae=(t,e,r)=>(r||(r=qe()),{id:r,username:e,aud:t}),ue=async(t,e,r)=>{let o=K(U(JSON.stringify({alg:"ES256",jwk:e}))),n=K(U(JSON.stringify(t))),i=`${o}.${n}`,a=await ke(r,i);return`${i}.${a}`};var pe=class extends Error{code;constructor(e,r){super(e),this.name="StorageError",this.code=r}},h=pe;var ce=class{dbName;dbVersion;storeKey;indexes;constructor(e,r,s,o=[]){this.dbName=e,this.dbVersion=r,this.storeKey=s,this.indexes=o}openDb(){let e=indexedDB.open(this.dbName,this.dbVersion);return e.onupgradeneeded=()=>{let r=e.result;if(!r.objectStoreNames.contains(this.storeKey)){let s=r.createObjectStore(this.storeKey,{keyPath:"id"});this.indexes.forEach(({name:o,keyPath:n,options:i})=>s.createIndex(o,n,i))}},e}async getAllByIndex(e,r){return new Promise((s,o)=>{let n=this.openDb();n.onsuccess=()=>{let l=n.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).getAll(r);l.onsuccess=()=>{s(l.result)},l.onerror=()=>o(new h(`Failed to fetch records from index ${e}.`,"ERROR_STORAGE_FAILED"))},n.onerror=()=>o(new h("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async getByIndex(e,r){return new Promise((s,o)=>{let n=this.openDb();n.onsuccess=()=>{let l=n.result.transaction(this.storeKey,"readonly").objectStore(this.storeKey).index(e).get(r);l.onsuccess=()=>{let y=l.result;y?s(y):o(new h(`No record found for ${r} in index ${e}.`,"ERROR_STORAGE_NOT_FOUND"))},l.onerror=()=>o(new h(`Failed to fetch record from index ${e}.`,"ERROR_STORAGE_FAILED"))},n.onerror=()=>o(new h("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}async putRecord(e){return new Promise((r,s)=>{let o=this.openDb();o.onsuccess=()=>{let u=o.result.transaction(this.storeKey,"readwrite").objectStore(this.storeKey).put(e);u.onsuccess=()=>r(),u.onerror=()=>s(new h("Failed to save record.","ERROR_STORAGE_FAILED"))},o.onerror=()=>s(new h("Failed to open the database.","ERROR_STORAGE_FAILED_TO_OPEN"))})}},Ke=ce;var it=1,Ue="app_id_idx",at="username_idx",ut="loginid-trust-store",pt="LoginID_trust-id",le="app_id_username_idx",N=class extends Ke{appId;constructor(e){super(ut,it,pt,[{name:at,keyPath:["username"]},{name:Ue,keyPath:["appId"]},{name:le,keyPath:["appId","username"]}]),this.appId=e}async setTrustId(e){let r=await xe(),s=await Q(r),o=ae(this.appId,e),n=await ue(o,s,r.privateKey);return await this.putRecord({id:o.id,appId:this.appId,username:e,keyPair:r}),n}async signWithTrustId(e){let r=await this.getByIndex(le,[this.appId,e]),s=await Q(r.keyPair),o=ae(this.appId,e,r.id);return await ue(o,s,r.keyPair.privateKey)}async setOrSignWithTrustId(e){try{return e?await this.signWithTrustId(e):""}catch(r){return r instanceof h&&r.code==="ERROR_STORAGE_NOT_FOUND"?await this.setTrustId(e):(console.log("IndexDB error: "+r),"")}}async getAllTrustIds(){try{return await this.getAllByIndex(Ue,[this.appId])}catch(e){return console.error("Error retrieving Trust IDs:",e),[]}}async findByUsername(e){try{return await this.getByIndex(le,[this.appId,e])}catch(r){return console.error("Error retrieving Trust ID Record:",r),null}}};var Le=t=>[...t.crossAuthMethods,...t.fallbackMethods];var de=class extends f{constructor(e){super(e)}async validateOtp(e,r,s={}){let o=g(e,"",s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n}),a=w(i);return b.renewWebAuthnAbortController(),this.session.setJwtCookie(a.token),a}async requestAndSendOtp(e,r="email",s={}){let o=g(e,"",s),n={user:{username:e,usernameType:o.usernameType}};switch(r){case"email":await this.service.auth.authAuthCodeRequestEmail({requestBody:n});break;case"sms":await this.service.auth.authAuthCodeRequestSms({requestBody:n});break;default:throw new Error("Invalid message method")}}},J=de;var ye=class extends J{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;b.renewWebAuthnAbortController();let o=await I(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),p=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:c(n.attestationObject),clientDataJSON:c(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:c(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:c(u)},...p&&{transports:p}},session:s}}async createPasskey(e,r="",s={}){let o=this.config.getAppId(),n=C.getDeviceId(o),i=D(n),a=new N(o),u=g(e,r,s);u.authzToken=this.session.getToken(u),u.authzToken&&B(u.authzToken).username!==e&&(u.authzToken="");let p=await a.setOrSignWithTrustId(e),l={app:{id:o},deviceInfo:i,user:{username:e,usernameType:u.usernameType,displayName:u.displayName},...p&&{trustInfo:p}},y=await this.service.reg.regRegInit({requestBody:l,...u.authzToken&&{authorization:u.authzToken}}),R=await this.createNavigatorCredential(y),V=await this.service.reg.regRegComplete({requestBody:R}),je=w(V);return this.session.setJwtCookie(V.jwtAccess),C.persistDeviceId(o,n||V.deviceId),je}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortController?b.assignWebAuthnAbortController(r.abortController):(b.renewWebAuthnAbortController(),r.abortController=b.abortController);let n=await P(s,r),i=n.response;return{assertionResult:{authenticatorData:c(i.authenticatorData),clientDataJSON:c(i.clientDataJSON),credentialId:n.id,signature:c(i.signature),...i.userHandle&&{userHandle:c(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=D(C.getDeviceId(s)),n=new N(s),i=g(e,"",r),a=await n.setOrSignWithTrustId(r.autoFill?"":e),u={app:{id:s},deviceInfo:o,user:{username:e,usernameType:i.usernameType},...a&&{trustInfo:a}},p=await this.service.auth.authAuthInit({requestBody:u});switch(p.action){case"proceed":{let l=await this.getNavigatorCredential(p,r),y=await this.service.auth.authAuthComplete({requestBody:l}),R=w(y);return this.session.setJwtCookie(R.token),C.persistDeviceId(s,y.deviceId),i?.callbacks?.onSuccess&&await i.callbacks.onSuccess(R),R}case"crossAuth":case"fallback":{if(i?.callbacks?.onFallback){let y=Le(p);await i.callbacks.onFallback(e,y)}return w({userId:"",jwtAccess:""},!1,!0)}default:throw Ce}}async authenticateWithPasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async requestOtp(e,r={}){if(r.authzToken=this.session.getToken(r),!r.authzToken){let o=await this.authenticateWithPasskey(e,r);r.authzToken=o.token}return await this.service.auth.authAuthCodeRequest({authorization:r.authzToken})}async confirmTransaction(e,r,s={}){let o=_e(e,s),n={username:e,txPayload:r,nonce:o.nonce,txType:o.txType},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),u={action:"proceed",crossAuthMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),l={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature};return await this.service.tx.txTxComplete({requestBody:l})}},Fe=ye;var me={};ge(me,{ApiError:()=>m,AuthService:()=>q,BaseHttpRequest:()=>T,CancelError:()=>v,CancelablePromise:()=>O,LoginIDService:()=>S,OpenAPI:()=>We,PasskeysService:()=>x,RegService:()=>k,TxService:()=>E});var We={BASE:"https://api.loginid.io/fido2/v2",VERSION:"2.0",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var he=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 r=g("","",{}),s={app:{id:this.config.getAppId()},deviceInfo:D(),user:{username:"",usernameType:r.usernameType}};await this.service.auth.authAuthInit({requestBody:s})}catch(r){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.",r instanceof m&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getSessionInfo(){return this.session.getSessionInfo()}logout(){this.session.logout()}},He=he;var z=class extends f{constructor(e){super(e)}};Ie(z,[f,Fe,J,ve,He]);var fe=z;var ct=fe;0&&(module.exports={AbortError,ApiError,LoginIDAPI,LoginIDWebSDK,PasskeyError,WebAuthnHelper,createPasskeyCredential,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
|
|
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});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|