@loginid/websdk3 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,13 +19,15 @@ npm install @loginid/websdk3
19
19
 
20
20
  ## How to Use
21
21
 
22
- - visit our [API Reference documentation](https://docs.loginid.io/Client-SDKs/Web/web) for package implementation.
22
+ - visit our [API Reference documentation](https://docs.loginid.io/sdks/web/web) for package implementation.
23
23
 
24
- ## Contact and Support
24
+ ## Contact and support
25
25
 
26
- - **Email**: [support@loginid.io](mailto:support@loginid.io)
27
- - **Community Chat**: [Join our Slack](https://loginidiocommunity.slack.com)
28
- - **Documentation**: [Read our full documentation](https://docs.loginid.io)
26
+ - **email**: [support@loginid.io](mailto:support@loginid.io)
27
+ - **documentation**: [read our full documentation](https://docs.loginid.io)
28
+ - **forum**: https://forum.loginid.dev
29
+ - **bug reporting**: https://loginid.dev
30
+ - **dashboard**: https://dashboard.loginid.io
29
31
 
30
32
  ## License
31
33
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var _=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Be=Object.prototype.hasOwnProperty;var Ee=(t,e)=>{for(var r in e)_(t,r,{get:e[r],enumerable:!0})},Oe=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Te(e))!Be.call(t,o)&&o!==r&&_(t,o,{get:()=>e[o],enumerable:!(s=Ie(e,o))||s.enumerable});return t};var xe=t=>Oe(_({},"__esModule",{value:!0}),t);var Je={};Ee(Je,{AbortError:()=>H,ApiError:()=>c,AuthService:()=>g,BaseHttpRequest:()=>h,CancelError:()=>k,CancelablePromise:()=>R,LoginIDService:()=>T,LoginIDWebSDK:()=>oe,MgmtService:()=>C,OpenAPI:()=>he,PasskeyError:()=>d,PasskeysService:()=>b,ProfileService:()=>P,RegService:()=>q,TxService:()=>A,VersionService:()=>I,WebAuthnHelper:()=>V,createPasskeyCredential:()=>E,default:()=>We,doesDeviceSupportPasskeys:()=>Pe,getPasskeyCredential:()=>O,isConditionalUIAvailable:()=>be,isPlatformAuthenticatorAvailable:()=>Ce});module.exports=xe(Je);var j=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https:\/\/([0-9a-fA-F-]+)\.api.*\.loginid\.io/,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},D=j;var W=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=W;var ne=(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},ie=(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},N=new Error("User needs to be logged in to perform this operation.");var Se=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),ke=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},ve=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},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=ke(e);return Se(s)},f=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=ve(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("-"),ue=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},S=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()},le=t=>{document.cookie=t},de=t=>{document.cookie=`${t}=; expires=${new Date}`};var J=class{config;constructor(e){this.config=new D(e)}getToken(e){if(e.token)return e.token;{let r=this.getJwtCookie();return r||""}}getUser(){if(!this.isLoggedIn())throw N;let e=S(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=S(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;le(o)}getJwtCookie(){return pe(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){de(this.getJwtCookieName())}},ce=J;var h=class{constructor(e){this.config=e}};var c=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 k=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},R=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 k("Request aborted"))}}get isCancelled(){return this.#e}};var z=t=>t!=null,v=t=>typeof t=="string",M=t=>v(t)&&t!=="",$=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]),ye=t=>t instanceof FormData,we=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},De=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{z(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("&")}`:""},Ne=(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}${De(e.query)}`:o},Ue=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{v(o)||$(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>z(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},U=async(t,e)=>typeof e=="function"?e(t):e,Le=async(t,e)=>{let[r,s,o,n]=await Promise.all([U(e,t.TOKEN),U(e,t.USERNAME),U(e,t.PASSWORD),U(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>z(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(M(r)&&(i.Authorization=`Bearer ${r}`),M(s)&&M(o)){let a=we(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:$(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":v(e.body)?i["Content-Type"]="text/plain":ye(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},He=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):v(t.body)||$(t.body)||ye(t.body)?t.body:JSON.stringify(t.body)},Fe=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)},Ke=(t,e)=>{if(e){let r=t.headers.get(e);if(v(r))return r}},Ve=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)}},_e=(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 c(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 c(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},me=(t,e)=>new R(async(r,s,o)=>{try{let n=Ne(t,e),i=Ue(e),a=He(e),u=await Le(t,e);if(!o.isCancelled){let p=await Fe(t,e,n,a,i,u,o),x=await Ve(p),w=Ke(p,e.responseHeader),se={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:w??x};_e(e,se),r(se.body)}}catch(n){s(n)}});var L=class extends h{constructor(e){super(e)}request(e){return me(this.config,e)}};var g=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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var C=class{constructor(e){this.httpRequest=e}mgmtGrantCreate({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/grant",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}mgmtTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/token/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}};var b=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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var P=class{constructor(e){this.httpRequest=e}profileProfileDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}",path:{id:e},errors:{404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/email",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}/phone",path:{id:e},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/phone",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/email/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/phone/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var q=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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var A=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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",500:"InternalServerError: Internal Server Error response."}})}};var I=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var T=class{auth;mgmt;passkeys;profile;reg;tx;version;request;constructor(e,r=L){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 g(this.request),this.mgmt=new C(this.request),this.passkeys=new b(this.request),this.profile=new P(this.request),this.reg=new q(this.request),this.tx=new A(this.request),this.version=new I(this.request)}};var G=class{config;service;session;constructor(e){this.config=new D(e),this.service=new T({BASE:e.baseUrl}),this.session=new ce(e)}},y=G;var Y=class extends Error{constructor(e){super(e),this.name="AbortError"}},H=Y;var Q=class t{static abortController=new AbortController;static renewWebAuthnAbortController=()=>{let e=new H("Cancelling current WebAuthn request");t.abortController.abort(e);let r=new AbortController;t.abortController=r}},B=Q;var m=(t,e)=>({...e,token:e.token||"",usernameType:e.usernameType||"email",displayName:e.displayName||t}),fe=(t,e)=>({...m(t,e),txType:e.txType||"raw",nonce:e.nonce||ae()});var X=class extends y{constructor(e){super(e)}async authenticateWithCode(e,r,s={}){let o=m(e,s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n});return B.renewWebAuthnAbortController(),this.session.setJwtCookie(i.jwtAccess),i}async sendCode(e,r="email",s={}){let o=m(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")}return null}},F=X;var he={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 Z=class extends y{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=m("",{}),s={app:{id:this.config.getAppId()},deviceInfo:{},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 c&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getUser(){return this.session.getUser()}isLoggedIn(){return this.session.isLoggedIn()}signout(){this.session.signout()}},Re=Z;var ge=require("ua-parser-js"),ee=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),je=(t,e)=>{let r=t.split(".").map(Number),s=e.split(".").map(Number),o=Math.max(r.length,s.length);for(let n=0;n<o;n++){let i=n<r.length?r[n]:0,a=n<s.length?s[n]:0;if(i<a)return-1;if(i>a)return 1}return 0};async function Ce(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function be(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function Pe(){let t=new ge.UAParser(window.navigator.userAgent).getResult(),e={solution:"",deviceSupported:!1};if(!window.PublicKeyCredential)return e.solution="Your browser seems to be outdated. Please upgrade to the latest version.",e;if(!await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable())switch(t.os.name){case"Mac OS":{let s=t.browser.version||"";return t.browser.name==="Firefox"&&je(s,"122.0")<0?(e.solution="Please update your Firefox browser to the latest version.",e):(e.solution="Enable Touch ID on your device.",e)}case"iOS":return e.solution="Enable Face ID or Touch ID on your device.",e;case"Windows":return e.solution="Enable Windows Hello on your device. See here: https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0.",e;case"Android":return t.browser.name==="Firefox"?(e.solution="Passkeys may not be supported on your Firefox browser. Please switch to a Chromium browser.",e):(e.solution="Enable device unlock via fingerprint, PIN, or facial recognition on your device.",e);default:return e.solution="Enable device unlock features such as fingerprint, PIN, or facial recognition.",e}return e.deviceSupported=!0,e}var E=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:f(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:f(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:f(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?ne(o,s):o}},O=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:f(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortSignal&&{signal:e.abortSignal},publicKey:{allowCredentials:r,challenge:f(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?ie(o,s):o}};var te=class extends F{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;B.renewWebAuthnAbortController();let o=await E(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:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}async registerWithPasskey(e,r={}){let s=ee(),o=m(e,r);r.token=this.session.getToken(r),r.token&&S(r.token).username!==e&&(r.token="");let n={app:{id:this.config.getAppId()},deviceInfo:s,user:{username:e,usernameType:o.usernameType,displayName:o.displayName},...r.session&&{session:r.session}},i=await this.service.reg.regRegInit({requestBody:n,...r.token&&{authorization:r.token}}),a=await this.createNavigatorCredential(i),u=await this.service.reg.regRegComplete({requestBody:a});return this.session.setJwtCookie(u.jwtAccess),u}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortSignal||(B.renewWebAuthnAbortController(),r.abortSignal=B.abortController.signal);let n=await O(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=ee(),o=m(e,r),n={app:{id:this.config.getAppId()},deviceInfo:s,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthInit({requestBody:n}),a=await this.getNavigatorCredential(i,r),u=await this.service.auth.authAuthComplete({requestBody:a});return this.session.setJwtCookie(u.jwtAccess),u}async enablePasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async generateCodeWithPasskey(e,r={}){if(r.token=this.session.getToken(r),!r.token){let o=await this.authenticateWithPasskey(e,r);r.token=o.jwtAccess}return await this.service.auth.authAuthCodeRequest({authorization:r.token})}async addPasskey(e,r={}){let s=this.session.getToken(r);if(!s)throw N;return r.token=s,await this.registerWithPasskey(e,r)}async addPasskeyWithCode(e,r,s={}){return await this.authenticateWithCode(e,r,s),await this.registerWithPasskey(e,s)}async confirmTransaction(e,r,s={}){let o=fe(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",affirmMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),x={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature},w=await this.service.tx.txTxComplete({requestBody:x});return this.session.setJwtCookie(w.jwtAccess),w}},qe=te;var re=class extends y{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};return await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n}),null}async deletePasskey(e,r={}){let s=this.session.getToken(r);return await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e}),null}},Ae=re;var K=class extends y{constructor(e){super(e)}};ue(K,[y,qe,F,Ae,Re]);var oe=K;var V=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await O(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await E(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:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}};var We=oe;0&&(module.exports={AbortError,ApiError,AuthService,BaseHttpRequest,CancelError,CancelablePromise,LoginIDService,LoginIDWebSDK,MgmtService,OpenAPI,PasskeyError,PasskeysService,ProfileService,RegService,TxService,VersionService,WebAuthnHelper,createPasskeyCredential,doesDeviceSupportPasskeys,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
1
+ "use strict";var M=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var de=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},Ue=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of De(e))!Ne.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(s=we(e,o))||s.enumerable});return t};var Le=t=>Ue(M({},"__esModule",{value:!0}),t);var Ze={};de(Ze,{AbortError:()=>_,ApiError:()=>m,LoginIDAPI:()=>ne,LoginIDWebSDK:()=>le,PasskeyError:()=>d,WebAuthnHelper:()=>j,createPasskeyCredential:()=>x,default:()=>Xe,doesDeviceSupportPasskeys:()=>Te,getPasskeyCredential:()=>S,isConditionalUIAvailable:()=>ke,isPlatformAuthenticatorAvailable:()=>Ie});module.exports=Le(Ze);var J=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https:\/\/([0-9a-fA-F-]+)\.api.*\.loginid\.io/,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},L=J;var z=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=z;var $=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},G=$;var ce=(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},me=(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},F=new G("User needs to be logged in to perform this operation."),Y=new G("No login options available.");var Fe=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Ke=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++),l=i<<16|a<<8|u;r.push(e[l>>18&63]+e[l>>12&63]+e[l>>6&63]+e[l&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},He=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},p=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=Ke(e);return Fe(s)},h=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=He(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},ye=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),fe=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},w=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)}},he=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},Re=t=>{document.cookie=t},ge=t=>{document.cookie=`${t}=; expires=${new Date}`};var Q=class{config;constructor(e){this.config=new L(e)}getToken(e){if(e.token)return e.token;{let r=this.getJwtCookie();return r||""}}getUser(){if(!this.isLoggedIn())throw F;let e=w(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=w(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;Re(o)}getJwtCookie(){return he(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){ge(this.getJwtCookieName())}},be=Q;var R=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 D=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},g=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 D("Request aborted"))}}get isCancelled(){return this.#e}};var Z=t=>t!=null,N=t=>typeof t=="string",X=t=>N(t)&&t!=="",ee=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]),Ce=t=>t instanceof FormData,_e=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Ve=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{Z(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("&")}`:""},We=(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}${Ve(e.query)}`:o},je=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{N(o)||ee(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>Z(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},K=async(t,e)=>typeof e=="function"?e(t):e,Me=async(t,e)=>{let[r,s,o,n]=await Promise.all([K(e,t.TOKEN),K(e,t.USERNAME),K(e,t.PASSWORD),K(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>Z(u)).reduce((a,[u,l])=>({...a,[u]:String(l)}),{});if(X(r)&&(i.Authorization=`Bearer ${r}`),X(s)&&X(o)){let a=_e(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:ee(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":N(e.body)?i["Content-Type"]="text/plain":Ce(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},Je=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):N(t.body)||ee(t.body)||Ce(t.body)?t.body:JSON.stringify(t.body)},ze=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)},$e=(t,e)=>{if(e){let r=t.headers.get(e);if(N(r))return r}},Ge=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)}},Ye=(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}`)}},Pe=(t,e)=>new g(async(r,s,o)=>{try{let n=We(t,e),i=je(e),a=Je(e),u=await Me(t,e);if(!o.isCancelled){let l=await ze(t,e,n,a,i,u,o),c=await Ge(l),v=$e(l,e.responseHeader),pe={url:n,ok:l.ok,status:l.status,statusText:l.statusText,body:v??c};Ye(e,pe),r(pe.body)}}catch(n){s(n)}});var H=class extends R{constructor(e){super(e)}request(e){return Pe(this.config,e)}};var b=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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var C=class{constructor(e){this.httpRequest=e}mgmtGrantCreate({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/grant",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}mgmtTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/token/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}};var P=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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var q=class{constructor(e){this.httpRequest=e}profileProfileDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}",path:{id:e},errors:{404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/email",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}/phone",path:{id:e},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/phone",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/email/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/phone/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var A=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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var I=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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",500:"InternalServerError: Internal Server Error response."}})}};var k=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var T=class{constructor(e){this.httpRequest=e}wellKnownJwks(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/.well-known/jwks.json",errors:{500:"InternalServerError: Internal Server Error response."}})}};var O=class{auth;mgmt;passkeys;profile;reg;tx;version;wellKnown;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 b(this.request),this.mgmt=new C(this.request),this.passkeys=new P(this.request),this.profile=new q(this.request),this.reg=new A(this.request),this.tx=new I(this.request),this.version=new k(this.request),this.wellKnown=new T(this.request)}};var te=class{config;service;session;constructor(e){this.config=new L(e),this.service=new O({BASE:e.baseUrl}),this.session=new be(e)}},y=te;var re=class extends Error{constructor(e){super(e),this.name="AbortError"}},_=re;var oe=class t{static abortController=new AbortController;static renewWebAuthnAbortController=()=>{let e=new _("Cancelling current WebAuthn request");t.abortController.abort(e);let r=new AbortController;t.abortController=r}},E=oe;var f=(t,e)=>({...e,token:e.token||"",usernameType:e.usernameType||"email",displayName:e.displayName||t,callbacks:e.callbacks||{}}),qe=(t,e)=>({...f(t,e),txType:e.txType||"raw",nonce:e.nonce||ye()});var se=class extends y{constructor(e){super(e)}async authenticateWithCode(e,r,s={}){let o=f(e,s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},a={...await this.service.auth.authAuthCodeVerify({requestBody:n}),isAuthenticated:!0};return E.renewWebAuthnAbortController(),this.session.setJwtCookie(a.jwtAccess),a}async sendCode(e,r="email",s={}){let o=f(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")}return null}},V=se;var Ae=require("ua-parser-js"),U=t=>{let e={clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height,clientName:"",clientVersion:"",osName:"",osVersion:"",osArch:""};return t&&(e.deviceId=t),e},Qe=(t,e)=>{let r=t.split(".").map(Number),s=e.split(".").map(Number),o=Math.max(r.length,s.length);for(let n=0;n<o;n++){let i=n<r.length?r[n]:0,a=n<s.length?s[n]:0;if(i<a)return-1;if(i>a)return 1}return 0};async function Ie(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function ke(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function Te(){let t=new Ae.UAParser(window.navigator.userAgent).getResult(),e={solution:"",deviceSupported:!1};if(!window.PublicKeyCredential)return e.solution="Your browser seems to be outdated. Please upgrade to the latest version.",e;if(!await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable())switch(t.os.name){case"Mac OS":{let s=t.browser.version||"";return t.browser.name==="Firefox"&&Qe(s,"122.0")<0?(e.solution="Please update your Firefox browser to the latest version.",e):(e.solution="Enable Touch ID on your device.",e)}case"iOS":return e.solution="Enable Face ID or Touch ID on your device.",e;case"Windows":return e.solution="Enable Windows Hello on your device. See here: https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0.",e;case"Android":return t.browser.name==="Firefox"?(e.solution="Passkeys may not be supported on your Firefox browser. Please switch to a Chromium browser.",e):(e.solution="Enable device unlock via fingerprint, PIN, or facial recognition on your device.",e);default:return e.solution="Enable device unlock features such as fingerprint, PIN, or facial recognition.",e}return e.deviceSupported=!0,e}var ne={};de(ne,{ApiError:()=>m,AuthService:()=>b,BaseHttpRequest:()=>R,CancelError:()=>D,CancelablePromise:()=>g,LoginIDService:()=>O,MgmtService:()=>C,OpenAPI:()=>Oe,PasskeysService:()=>P,ProfileService:()=>q,RegService:()=>A,TxService:()=>I,VersionService:()=>k,WellKnownService:()=>T});var Oe={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 ie=class extends y{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=f("",{}),s={app:{id:this.config.getAppId()},deviceInfo:U(),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}getUser(){return this.session.getUser()}isLoggedIn(){return this.session.isLoggedIn()}signout(){this.session.signout()}},Ee=ie;var Be=t=>`LoginID_${t}_device-id`,B=class{static persistDeviceId(e,r){r&&localStorage.setItem(Be(e),r)}static getDeviceId(e){return localStorage.getItem(Be(e))||""}};var xe=t=>{let e={ciam:!1,otp:!1,"otp:email":!1,"otp:sms":!1};return[...t.crossAuthMethods,...t.fallbackMethods].reduce((o,n)=>(o[n]=!0,o),e)};var x=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:h(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:h(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:h(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?ce(o,s):o}},S=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:h(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortSignal&&{signal:e.abortSignal},publicKey:{allowCredentials:r,challenge:h(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?me(o,s):o}};var ae=class extends V{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;E.renewWebAuthnAbortController();let o=await x(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),l=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:p(n.attestationObject),clientDataJSON:p(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:p(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:p(u)},...l&&{transports:l}},session:s}}async registerWithPasskey(e,r={}){let s=this.config.getAppId(),o=U(B.getDeviceId(s)),n=f(e,r);r.token=this.session.getToken(r),r.token&&w(r.token).username!==e&&(r.token="");let i={app:{id:s},deviceInfo:o,user:{username:e,usernameType:n.usernameType,displayName:n.displayName},...r.session&&{session:r.session}},a=await this.service.reg.regRegInit({requestBody:i,...r.token&&{authorization:r.token}}),u=await this.createNavigatorCredential(a),c={...await this.service.reg.regRegComplete({requestBody:u}),isAuthenticated:!0};return this.session.setJwtCookie(c.jwtAccess),B.persistDeviceId(s,c.deviceID),c}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortSignal||(E.renewWebAuthnAbortController(),r.abortSignal=E.abortController.signal);let n=await S(s,r),i=n.response;return{assertionResult:{authenticatorData:p(i.authenticatorData),clientDataJSON:p(i.clientDataJSON),credentialId:n.id,signature:p(i.signature),...i.userHandle&&{userHandle:p(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=U(B.getDeviceId(s)),n=f(e,r),i={app:{id:s},deviceInfo:o,user:{username:e,usernameType:n.usernameType}},a=await this.service.auth.authAuthInit({requestBody:i});switch(a.action){case"proceed":{let u=await this.getNavigatorCredential(a,r),c={...await this.service.auth.authAuthComplete({requestBody:u}),isAuthenticated:!0};return this.session.setJwtCookie(c.jwtAccess),n?.callbacks?.onSuccess&&await n.callbacks.onSuccess(c),c}case"crossAuth":case"fallback":{if(n?.callbacks?.onFallback){let u=xe(a);return await n.callbacks.onFallback(e,{fallbackOptions:u}),{jwtAccess:"",isAuthenticated:!1,fallbackOptions:u}}throw Y}default:throw Y}}async enablePasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async generateCodeWithPasskey(e,r={}){if(r.token=this.session.getToken(r),!r.token){let o=await this.authenticateWithPasskey(e,r);r.token=o.jwtAccess}return await this.service.auth.authAuthCodeRequest({authorization:r.token})}async addPasskey(e,r={}){let s=this.session.getToken(r);if(!s)throw F;return r.token=s,await this.registerWithPasskey(e,r)}async addPasskeyWithCode(e,r,s={}){return await this.authenticateWithCode(e,r,s),await this.registerWithPasskey(e,s)}async confirmTransaction(e,r,s={}){let o=qe(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:l}=await this.getNavigatorCredential(u),c={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:a,signature:l.signature},v=await this.service.tx.txTxComplete({requestBody:c});return this.session.setJwtCookie(v.jwtAccess),v}},Se=ae;var ue=class extends y{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};return await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n}),null}async deletePasskey(e,r={}){let s=this.session.getToken(r);return await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e}),null}},ve=ue;var W=class extends y{constructor(e){super(e)}};fe(W,[y,Se,V,ve,Ee]);var le=W;var j=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await S(s,r),i=n.response;return{assertionResult:{authenticatorData:p(i.authenticatorData),clientDataJSON:p(i.clientDataJSON),credentialId:n.id,signature:p(i.signature),...i.userHandle&&{userHandle:p(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await x(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),l=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:p(n.attestationObject),clientDataJSON:p(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:p(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:p(u)},...l&&{transports:l}},session:s}}};var Xe=le;0&&(module.exports={AbortError,ApiError,LoginIDAPI,LoginIDWebSDK,PasskeyError,WebAuthnHelper,createPasskeyCredential,doesDeviceSupportPasskeys,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -178,12 +178,12 @@ type AuthInit = {
178
178
  /**
179
179
  * An action to be performed by the front-end to complete the authentication flow.
180
180
  */
181
- action: 'proceed' | 'affirm' | 'fallback';
181
+ action: 'proceed' | 'crossAuth' | 'fallback';
182
+ assertionOptions: PublicKeyCredentialRequestOptions;
182
183
  /**
183
184
  * List of cross authentication methods in the order of preference
184
185
  */
185
- affirmMethods: Array<'otp' | 'otp:sms' | 'otp:email'>;
186
- assertionOptions: PublicKeyCredentialRequestOptions;
186
+ crossAuthMethods: Array<'otp' | 'otp:sms' | 'otp:email'>;
187
187
  /**
188
188
  * The list contains available fallback methods in the order of preference. The
189
189
  * list is dynamic and shall not be cached. The default fallback mechanism is
@@ -227,15 +227,15 @@ type DeviceInfo = {
227
227
  /**
228
228
  * Client name
229
229
  */
230
- clientName?: string;
230
+ clientName: string;
231
231
  /**
232
232
  * Client type.
233
233
  */
234
- clientType?: 'browser' | 'other';
234
+ clientType: 'browser' | 'other';
235
235
  /**
236
236
  * Client version
237
237
  */
238
- clientVersion?: string;
238
+ clientVersion: string;
239
239
  /**
240
240
  * An unique device identifier
241
241
  */
@@ -243,23 +243,23 @@ type DeviceInfo = {
243
243
  /**
244
244
  * OS architecture
245
245
  */
246
- osArch?: string;
246
+ osArch: string;
247
247
  /**
248
248
  * OS name
249
249
  */
250
- osName?: string;
250
+ osName: string;
251
251
  /**
252
252
  * OS version
253
253
  */
254
- osVersion?: string;
254
+ osVersion: string;
255
255
  /**
256
256
  * Screen height in pixels
257
257
  */
258
- screenHeight?: number;
258
+ screenHeight: number;
259
259
  /**
260
260
  * Screen width in pixels
261
261
  */
262
- screenWidth?: number;
262
+ screenWidth: number;
263
263
  };
264
264
 
265
265
  type AuthInitRequestBody = {
@@ -351,7 +351,7 @@ type GrantCreateRequestBody = {
351
351
  /**
352
352
  * List of requested grants
353
353
  */
354
- grants: Array<'passkey:read' | 'passkey:write' | 'profile:read' | 'profile:write' | 'self:write'>;
354
+ grants: Array<'passkey:read' | 'passkey:write' | 'profile:read' | 'profile:write' | 'reg:write' | 'auth:write'>;
355
355
  /**
356
356
  * User identifier
357
357
  */
@@ -398,6 +398,10 @@ type Passkey = {
398
398
  * Timestamp in RFC3339 format.
399
399
  */
400
400
  createdAt: string;
401
+ /**
402
+ * Credential available on multiple devices
403
+ */
404
+ credentialSynced?: boolean;
401
405
  /**
402
406
  * Device type
403
407
  */
@@ -726,6 +730,13 @@ type RegInit = {
726
730
  session: string;
727
731
  };
728
732
 
733
+ type PasskeyOptions$1 = {
734
+ /**
735
+ * Flag to allow conditional creation
736
+ */
737
+ conditionalCreate: boolean;
738
+ };
739
+
729
740
  type User = {
730
741
  /**
731
742
  * Display Name
@@ -744,6 +755,7 @@ type User = {
744
755
  type RegInitRequestBody = {
745
756
  app: Application;
746
757
  deviceInfo: DeviceInfo;
758
+ passkeyOptions?: PasskeyOptions$1;
747
759
  /**
748
760
  * An opaque object containing user data. It is used in place of "user" attribute
749
761
  * for creating passkeys for pre-authorized users ("user" attribute is ignored if
@@ -912,6 +924,21 @@ declare class VersionService {
912
924
  versionVersionShow(): CancelablePromise<Version>;
913
925
  }
914
926
 
927
+ type WellKnownJwks = {
928
+ keys?: Array<string>;
929
+ };
930
+
931
+ declare class WellKnownService {
932
+ readonly httpRequest: BaseHttpRequest;
933
+ constructor(httpRequest: BaseHttpRequest);
934
+ /**
935
+ * JWKS for auth token validation
936
+ * @returns WellKnownJwks OK response.
937
+ * @throws ApiError
938
+ */
939
+ wellKnownJwks(): CancelablePromise<WellKnownJwks>;
940
+ }
941
+
915
942
  type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest;
916
943
  declare class LoginIDService {
917
944
  readonly auth: AuthService;
@@ -921,6 +948,7 @@ declare class LoginIDService {
921
948
  readonly reg: RegService;
922
949
  readonly tx: TxService;
923
950
  readonly version: VersionService;
951
+ readonly wellKnown: WellKnownService;
924
952
  readonly request: BaseHttpRequest;
925
953
  constructor(config?: Partial<OpenAPIConfig>, HttpRequest?: HttpRequestConstructor);
926
954
  }
@@ -947,6 +975,77 @@ type BadRequestError = {
947
975
  msgCode: string;
948
976
  };
949
977
 
978
+ type index_ApiError = ApiError;
979
+ declare const index_ApiError: typeof ApiError;
980
+ type index_Application = Application;
981
+ type index_AuthCode = AuthCode;
982
+ type index_AuthCodeRequestSMSRequestBody = AuthCodeRequestSMSRequestBody;
983
+ type index_AuthCodeVerifyRequestBody = AuthCodeVerifyRequestBody;
984
+ type index_AuthCompleteRequestBody = AuthCompleteRequestBody;
985
+ type index_AuthInit = AuthInit;
986
+ type index_AuthInitRequestBody = AuthInitRequestBody;
987
+ type index_AuthService = AuthService;
988
+ declare const index_AuthService: typeof AuthService;
989
+ type index_AuthenticatorAssertionResponse = AuthenticatorAssertionResponse;
990
+ type index_AuthenticatorSelectionCriteria = AuthenticatorSelectionCriteria;
991
+ type index_BadRequestError = BadRequestError;
992
+ type index_BaseHttpRequest = BaseHttpRequest;
993
+ declare const index_BaseHttpRequest: typeof BaseHttpRequest;
994
+ type index_CancelError = CancelError;
995
+ declare const index_CancelError: typeof CancelError;
996
+ type index_CancelablePromise<T> = CancelablePromise<T>;
997
+ declare const index_CancelablePromise: typeof CancelablePromise;
998
+ type index_CreationResult = CreationResult;
999
+ type index_DeviceInfo = DeviceInfo;
1000
+ type index_GrantCreateRequestBody = GrantCreateRequestBody;
1001
+ type index_GrantCreateResponseBody = GrantCreateResponseBody;
1002
+ type index_JWT = JWT;
1003
+ type index_LoginIDService = LoginIDService;
1004
+ declare const index_LoginIDService: typeof LoginIDService;
1005
+ type index_MgmtService = MgmtService;
1006
+ declare const index_MgmtService: typeof MgmtService;
1007
+ declare const index_OpenAPI: typeof OpenAPI;
1008
+ type index_OpenAPIConfig = OpenAPIConfig;
1009
+ type index_Passkey = Passkey;
1010
+ type index_PasskeyCollection = PasskeyCollection;
1011
+ type index_PasskeyRenameRequestBody = PasskeyRenameRequestBody;
1012
+ type index_PasskeysService = PasskeysService;
1013
+ declare const index_PasskeysService: typeof PasskeysService;
1014
+ type index_ProfileEmailUpdateRequestBody = ProfileEmailUpdateRequestBody;
1015
+ type index_ProfilePhoneUpdateRequestBody = ProfilePhoneUpdateRequestBody;
1016
+ type index_ProfilePhoneVerifyRequestBody = ProfilePhoneVerifyRequestBody;
1017
+ type index_ProfileService = ProfileService;
1018
+ declare const index_ProfileService: typeof ProfileService;
1019
+ type index_PubKeyCredentialDescriptor = PubKeyCredentialDescriptor;
1020
+ type index_PublicKeyCredentialCreationOptions = PublicKeyCredentialCreationOptions;
1021
+ type index_PublicKeyCredentialParameters = PublicKeyCredentialParameters;
1022
+ type index_PublicKeyCredentialRequestOptions = PublicKeyCredentialRequestOptions;
1023
+ type index_PublicKeyCredentialRpEntity = PublicKeyCredentialRpEntity;
1024
+ type index_PublicKeyCredentialUserEntity = PublicKeyCredentialUserEntity;
1025
+ type index_RegCompleteRequestBody = RegCompleteRequestBody;
1026
+ type index_RegInit = RegInit;
1027
+ type index_RegInitRequestBody = RegInitRequestBody;
1028
+ type index_RegService = RegService;
1029
+ declare const index_RegService: typeof RegService;
1030
+ type index_TokenVerifyRequestBody = TokenVerifyRequestBody;
1031
+ type index_TxComplete = TxComplete;
1032
+ type index_TxCompleteRequestBody = TxCompleteRequestBody;
1033
+ type index_TxInit = TxInit;
1034
+ type index_TxInitRequestBody = TxInitRequestBody;
1035
+ type index_TxService = TxService;
1036
+ declare const index_TxService: typeof TxService;
1037
+ type index_User = User;
1038
+ type index_UserLogin = UserLogin;
1039
+ type index_Version = Version;
1040
+ type index_VersionService = VersionService;
1041
+ declare const index_VersionService: typeof VersionService;
1042
+ type index_WellKnownJwks = WellKnownJwks;
1043
+ type index_WellKnownService = WellKnownService;
1044
+ declare const index_WellKnownService: typeof WellKnownService;
1045
+ declare namespace index {
1046
+ export { index_ApiError as ApiError, type index_Application as Application, type index_AuthCode as AuthCode, type index_AuthCodeRequestSMSRequestBody as AuthCodeRequestSMSRequestBody, type index_AuthCodeVerifyRequestBody as AuthCodeVerifyRequestBody, type index_AuthCompleteRequestBody as AuthCompleteRequestBody, type index_AuthInit as AuthInit, type index_AuthInitRequestBody as AuthInitRequestBody, index_AuthService as AuthService, type index_AuthenticatorAssertionResponse as AuthenticatorAssertionResponse, type index_AuthenticatorSelectionCriteria as AuthenticatorSelectionCriteria, type index_BadRequestError as BadRequestError, index_BaseHttpRequest as BaseHttpRequest, index_CancelError as CancelError, index_CancelablePromise as CancelablePromise, type index_CreationResult as CreationResult, type index_DeviceInfo as DeviceInfo, type index_GrantCreateRequestBody as GrantCreateRequestBody, type index_GrantCreateResponseBody as GrantCreateResponseBody, type index_JWT as JWT, index_LoginIDService as LoginIDService, index_MgmtService as MgmtService, index_OpenAPI as OpenAPI, type index_OpenAPIConfig as OpenAPIConfig, type index_Passkey as Passkey, type index_PasskeyCollection as PasskeyCollection, type PasskeyOptions$1 as PasskeyOptions, type index_PasskeyRenameRequestBody as PasskeyRenameRequestBody, index_PasskeysService as PasskeysService, type index_ProfileEmailUpdateRequestBody as ProfileEmailUpdateRequestBody, type index_ProfilePhoneUpdateRequestBody as ProfilePhoneUpdateRequestBody, type index_ProfilePhoneVerifyRequestBody as ProfilePhoneVerifyRequestBody, index_ProfileService as ProfileService, type index_PubKeyCredentialDescriptor as PubKeyCredentialDescriptor, type index_PublicKeyCredentialCreationOptions as PublicKeyCredentialCreationOptions, type index_PublicKeyCredentialParameters as PublicKeyCredentialParameters, type index_PublicKeyCredentialRequestOptions as PublicKeyCredentialRequestOptions, type index_PublicKeyCredentialRpEntity as PublicKeyCredentialRpEntity, type index_PublicKeyCredentialUserEntity as PublicKeyCredentialUserEntity, type index_RegCompleteRequestBody as RegCompleteRequestBody, type index_RegInit as RegInit, type index_RegInitRequestBody as RegInitRequestBody, index_RegService as RegService, type index_TokenVerifyRequestBody as TokenVerifyRequestBody, type index_TxComplete as TxComplete, type index_TxCompleteRequestBody as TxCompleteRequestBody, type index_TxInit as TxInit, type index_TxInitRequestBody as TxInitRequestBody, index_TxService as TxService, type index_User as User, type index_UserLogin as UserLogin, type index_Version as Version, index_VersionService as VersionService, type index_WellKnownJwks as WellKnownJwks, index_WellKnownService as WellKnownService };
1047
+ }
1048
+
950
1049
  type Complete<T> = {
951
1050
  [P in keyof T]-?: T[P];
952
1051
  };
@@ -958,10 +1057,24 @@ interface LoginIDConfig {
958
1057
  baseUrl: string;
959
1058
  appId: string;
960
1059
  }
1060
+ type FallbackMethods = AuthInit['fallbackMethods'] | AuthInit['crossAuthMethods'];
1061
+ type CrossAuthMethodsResult = {
1062
+ [K in FallbackMethods[number]]: boolean;
1063
+ };
1064
+ interface FallbackMethodsResult {
1065
+ fallbackOptions: CrossAuthMethodsResult;
1066
+ }
1067
+ type FallbackCallback = (username: string, options: FallbackMethodsResult) => Promise<void>;
1068
+ type SuccessCallback = (result: PasskeyResult) => Promise<void>;
1069
+ interface Callbacks {
1070
+ onFallback?: FallbackCallback;
1071
+ onSuccess?: SuccessCallback;
1072
+ }
961
1073
  interface PasskeyOptions {
962
1074
  token?: string;
963
1075
  displayName?: string;
964
1076
  usernameType?: UsernameType;
1077
+ callbacks?: Callbacks;
965
1078
  }
966
1079
  interface PasskeyManagementOptions {
967
1080
  token?: string;
@@ -987,8 +1100,10 @@ interface SendCodeOptions {
987
1100
  usernameType?: UsernameType;
988
1101
  }
989
1102
  interface PasskeyResult {
1103
+ isAuthenticated: boolean;
990
1104
  jwtAccess: string;
991
1105
  deviceID?: string;
1106
+ fallbackOptions?: CrossAuthMethodsResult;
992
1107
  }
993
1108
  interface LoginIDUser {
994
1109
  username: string;
@@ -1348,4 +1463,4 @@ interface DoesDeviceSupportPasskeysResponse {
1348
1463
  */
1349
1464
  declare function doesDeviceSupportPasskeys(): Promise<DoesDeviceSupportPasskeysResponse>;
1350
1465
 
1351
- export { AbortError, ApiError, type Application, type AuthCode, type AuthCodeRequestSMSRequestBody, type AuthCodeVerifyRequestBody, type AuthCompleteRequestBody, type AuthInit, type AuthInitRequestBody, AuthService, type AuthenticateWithPasskeysOptions, type AuthenticatorAssertionResponse, type AuthenticatorSelectionCriteria, type BadRequestError, BaseHttpRequest, CancelError, CancelablePromise, type Complete, type ConfirmTransactionOptions, type CreationResult, type DeletePasskeyOptions, type DeviceInfo, type DeviceInfoRequestBody, type DoesDeviceSupportPasskeysResponse, type GrantCreateRequestBody, type GrantCreateResponseBody, type JWT, type ListPasskeysOptions, type LoginIDConfig, LoginIDService, type LoginIDUser, LoginIDWebSDK, type Message, MgmtService, OpenAPI, type OpenAPIConfig, type Passkey, type PasskeyCollection, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type PasskeyRenameRequestBody, type PasskeyResult, PasskeysService, type ProfileEmailUpdateRequestBody, type ProfilePhoneUpdateRequestBody, type ProfilePhoneVerifyRequestBody, ProfileService, type PubKeyCredentialDescriptor, type PublicKeyCredentialCreationOptions, type PublicKeyCredentialParameters, type PublicKeyCredentialRequestOptions, type PublicKeyCredentialRpEntity, type PublicKeyCredentialUserEntity, type RegCompleteRequestBody, type RegInit, type RegInitRequestBody, RegService, type RegisterWithPasskeyOptions, type RenamePasskeyOptions, type SendCodeOptions, type TokenVerifyRequestBody, type Transports, type TxComplete, type TxCompleteRequestBody, type TxInit, type TxInitRequestBody, TxService, type User, type UserLogin, type UsernameType, type VerifyConfigResult, type Version, VersionService, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
1466
+ export { AbortError, ApiError, type AuthenticateWithPasskeysOptions, type Callbacks, type Complete, type ConfirmTransactionOptions, type CrossAuthMethodsResult, type DeletePasskeyOptions, type DeviceInfoRequestBody, type DoesDeviceSupportPasskeysResponse, type FallbackCallback, type FallbackMethods, type FallbackMethodsResult, type ListPasskeysOptions, index as LoginIDAPI, type LoginIDConfig, type LoginIDUser, LoginIDWebSDK, type Message, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type PasskeyResult, type RegisterWithPasskeyOptions, type RenamePasskeyOptions, type SendCodeOptions, type SuccessCallback, type Transports, type UsernameType, type VerifyConfigResult, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
package/dist/index.d.ts CHANGED
@@ -178,12 +178,12 @@ type AuthInit = {
178
178
  /**
179
179
  * An action to be performed by the front-end to complete the authentication flow.
180
180
  */
181
- action: 'proceed' | 'affirm' | 'fallback';
181
+ action: 'proceed' | 'crossAuth' | 'fallback';
182
+ assertionOptions: PublicKeyCredentialRequestOptions;
182
183
  /**
183
184
  * List of cross authentication methods in the order of preference
184
185
  */
185
- affirmMethods: Array<'otp' | 'otp:sms' | 'otp:email'>;
186
- assertionOptions: PublicKeyCredentialRequestOptions;
186
+ crossAuthMethods: Array<'otp' | 'otp:sms' | 'otp:email'>;
187
187
  /**
188
188
  * The list contains available fallback methods in the order of preference. The
189
189
  * list is dynamic and shall not be cached. The default fallback mechanism is
@@ -227,15 +227,15 @@ type DeviceInfo = {
227
227
  /**
228
228
  * Client name
229
229
  */
230
- clientName?: string;
230
+ clientName: string;
231
231
  /**
232
232
  * Client type.
233
233
  */
234
- clientType?: 'browser' | 'other';
234
+ clientType: 'browser' | 'other';
235
235
  /**
236
236
  * Client version
237
237
  */
238
- clientVersion?: string;
238
+ clientVersion: string;
239
239
  /**
240
240
  * An unique device identifier
241
241
  */
@@ -243,23 +243,23 @@ type DeviceInfo = {
243
243
  /**
244
244
  * OS architecture
245
245
  */
246
- osArch?: string;
246
+ osArch: string;
247
247
  /**
248
248
  * OS name
249
249
  */
250
- osName?: string;
250
+ osName: string;
251
251
  /**
252
252
  * OS version
253
253
  */
254
- osVersion?: string;
254
+ osVersion: string;
255
255
  /**
256
256
  * Screen height in pixels
257
257
  */
258
- screenHeight?: number;
258
+ screenHeight: number;
259
259
  /**
260
260
  * Screen width in pixels
261
261
  */
262
- screenWidth?: number;
262
+ screenWidth: number;
263
263
  };
264
264
 
265
265
  type AuthInitRequestBody = {
@@ -351,7 +351,7 @@ type GrantCreateRequestBody = {
351
351
  /**
352
352
  * List of requested grants
353
353
  */
354
- grants: Array<'passkey:read' | 'passkey:write' | 'profile:read' | 'profile:write' | 'self:write'>;
354
+ grants: Array<'passkey:read' | 'passkey:write' | 'profile:read' | 'profile:write' | 'reg:write' | 'auth:write'>;
355
355
  /**
356
356
  * User identifier
357
357
  */
@@ -398,6 +398,10 @@ type Passkey = {
398
398
  * Timestamp in RFC3339 format.
399
399
  */
400
400
  createdAt: string;
401
+ /**
402
+ * Credential available on multiple devices
403
+ */
404
+ credentialSynced?: boolean;
401
405
  /**
402
406
  * Device type
403
407
  */
@@ -726,6 +730,13 @@ type RegInit = {
726
730
  session: string;
727
731
  };
728
732
 
733
+ type PasskeyOptions$1 = {
734
+ /**
735
+ * Flag to allow conditional creation
736
+ */
737
+ conditionalCreate: boolean;
738
+ };
739
+
729
740
  type User = {
730
741
  /**
731
742
  * Display Name
@@ -744,6 +755,7 @@ type User = {
744
755
  type RegInitRequestBody = {
745
756
  app: Application;
746
757
  deviceInfo: DeviceInfo;
758
+ passkeyOptions?: PasskeyOptions$1;
747
759
  /**
748
760
  * An opaque object containing user data. It is used in place of "user" attribute
749
761
  * for creating passkeys for pre-authorized users ("user" attribute is ignored if
@@ -912,6 +924,21 @@ declare class VersionService {
912
924
  versionVersionShow(): CancelablePromise<Version>;
913
925
  }
914
926
 
927
+ type WellKnownJwks = {
928
+ keys?: Array<string>;
929
+ };
930
+
931
+ declare class WellKnownService {
932
+ readonly httpRequest: BaseHttpRequest;
933
+ constructor(httpRequest: BaseHttpRequest);
934
+ /**
935
+ * JWKS for auth token validation
936
+ * @returns WellKnownJwks OK response.
937
+ * @throws ApiError
938
+ */
939
+ wellKnownJwks(): CancelablePromise<WellKnownJwks>;
940
+ }
941
+
915
942
  type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest;
916
943
  declare class LoginIDService {
917
944
  readonly auth: AuthService;
@@ -921,6 +948,7 @@ declare class LoginIDService {
921
948
  readonly reg: RegService;
922
949
  readonly tx: TxService;
923
950
  readonly version: VersionService;
951
+ readonly wellKnown: WellKnownService;
924
952
  readonly request: BaseHttpRequest;
925
953
  constructor(config?: Partial<OpenAPIConfig>, HttpRequest?: HttpRequestConstructor);
926
954
  }
@@ -947,6 +975,77 @@ type BadRequestError = {
947
975
  msgCode: string;
948
976
  };
949
977
 
978
+ type index_ApiError = ApiError;
979
+ declare const index_ApiError: typeof ApiError;
980
+ type index_Application = Application;
981
+ type index_AuthCode = AuthCode;
982
+ type index_AuthCodeRequestSMSRequestBody = AuthCodeRequestSMSRequestBody;
983
+ type index_AuthCodeVerifyRequestBody = AuthCodeVerifyRequestBody;
984
+ type index_AuthCompleteRequestBody = AuthCompleteRequestBody;
985
+ type index_AuthInit = AuthInit;
986
+ type index_AuthInitRequestBody = AuthInitRequestBody;
987
+ type index_AuthService = AuthService;
988
+ declare const index_AuthService: typeof AuthService;
989
+ type index_AuthenticatorAssertionResponse = AuthenticatorAssertionResponse;
990
+ type index_AuthenticatorSelectionCriteria = AuthenticatorSelectionCriteria;
991
+ type index_BadRequestError = BadRequestError;
992
+ type index_BaseHttpRequest = BaseHttpRequest;
993
+ declare const index_BaseHttpRequest: typeof BaseHttpRequest;
994
+ type index_CancelError = CancelError;
995
+ declare const index_CancelError: typeof CancelError;
996
+ type index_CancelablePromise<T> = CancelablePromise<T>;
997
+ declare const index_CancelablePromise: typeof CancelablePromise;
998
+ type index_CreationResult = CreationResult;
999
+ type index_DeviceInfo = DeviceInfo;
1000
+ type index_GrantCreateRequestBody = GrantCreateRequestBody;
1001
+ type index_GrantCreateResponseBody = GrantCreateResponseBody;
1002
+ type index_JWT = JWT;
1003
+ type index_LoginIDService = LoginIDService;
1004
+ declare const index_LoginIDService: typeof LoginIDService;
1005
+ type index_MgmtService = MgmtService;
1006
+ declare const index_MgmtService: typeof MgmtService;
1007
+ declare const index_OpenAPI: typeof OpenAPI;
1008
+ type index_OpenAPIConfig = OpenAPIConfig;
1009
+ type index_Passkey = Passkey;
1010
+ type index_PasskeyCollection = PasskeyCollection;
1011
+ type index_PasskeyRenameRequestBody = PasskeyRenameRequestBody;
1012
+ type index_PasskeysService = PasskeysService;
1013
+ declare const index_PasskeysService: typeof PasskeysService;
1014
+ type index_ProfileEmailUpdateRequestBody = ProfileEmailUpdateRequestBody;
1015
+ type index_ProfilePhoneUpdateRequestBody = ProfilePhoneUpdateRequestBody;
1016
+ type index_ProfilePhoneVerifyRequestBody = ProfilePhoneVerifyRequestBody;
1017
+ type index_ProfileService = ProfileService;
1018
+ declare const index_ProfileService: typeof ProfileService;
1019
+ type index_PubKeyCredentialDescriptor = PubKeyCredentialDescriptor;
1020
+ type index_PublicKeyCredentialCreationOptions = PublicKeyCredentialCreationOptions;
1021
+ type index_PublicKeyCredentialParameters = PublicKeyCredentialParameters;
1022
+ type index_PublicKeyCredentialRequestOptions = PublicKeyCredentialRequestOptions;
1023
+ type index_PublicKeyCredentialRpEntity = PublicKeyCredentialRpEntity;
1024
+ type index_PublicKeyCredentialUserEntity = PublicKeyCredentialUserEntity;
1025
+ type index_RegCompleteRequestBody = RegCompleteRequestBody;
1026
+ type index_RegInit = RegInit;
1027
+ type index_RegInitRequestBody = RegInitRequestBody;
1028
+ type index_RegService = RegService;
1029
+ declare const index_RegService: typeof RegService;
1030
+ type index_TokenVerifyRequestBody = TokenVerifyRequestBody;
1031
+ type index_TxComplete = TxComplete;
1032
+ type index_TxCompleteRequestBody = TxCompleteRequestBody;
1033
+ type index_TxInit = TxInit;
1034
+ type index_TxInitRequestBody = TxInitRequestBody;
1035
+ type index_TxService = TxService;
1036
+ declare const index_TxService: typeof TxService;
1037
+ type index_User = User;
1038
+ type index_UserLogin = UserLogin;
1039
+ type index_Version = Version;
1040
+ type index_VersionService = VersionService;
1041
+ declare const index_VersionService: typeof VersionService;
1042
+ type index_WellKnownJwks = WellKnownJwks;
1043
+ type index_WellKnownService = WellKnownService;
1044
+ declare const index_WellKnownService: typeof WellKnownService;
1045
+ declare namespace index {
1046
+ export { index_ApiError as ApiError, type index_Application as Application, type index_AuthCode as AuthCode, type index_AuthCodeRequestSMSRequestBody as AuthCodeRequestSMSRequestBody, type index_AuthCodeVerifyRequestBody as AuthCodeVerifyRequestBody, type index_AuthCompleteRequestBody as AuthCompleteRequestBody, type index_AuthInit as AuthInit, type index_AuthInitRequestBody as AuthInitRequestBody, index_AuthService as AuthService, type index_AuthenticatorAssertionResponse as AuthenticatorAssertionResponse, type index_AuthenticatorSelectionCriteria as AuthenticatorSelectionCriteria, type index_BadRequestError as BadRequestError, index_BaseHttpRequest as BaseHttpRequest, index_CancelError as CancelError, index_CancelablePromise as CancelablePromise, type index_CreationResult as CreationResult, type index_DeviceInfo as DeviceInfo, type index_GrantCreateRequestBody as GrantCreateRequestBody, type index_GrantCreateResponseBody as GrantCreateResponseBody, type index_JWT as JWT, index_LoginIDService as LoginIDService, index_MgmtService as MgmtService, index_OpenAPI as OpenAPI, type index_OpenAPIConfig as OpenAPIConfig, type index_Passkey as Passkey, type index_PasskeyCollection as PasskeyCollection, type PasskeyOptions$1 as PasskeyOptions, type index_PasskeyRenameRequestBody as PasskeyRenameRequestBody, index_PasskeysService as PasskeysService, type index_ProfileEmailUpdateRequestBody as ProfileEmailUpdateRequestBody, type index_ProfilePhoneUpdateRequestBody as ProfilePhoneUpdateRequestBody, type index_ProfilePhoneVerifyRequestBody as ProfilePhoneVerifyRequestBody, index_ProfileService as ProfileService, type index_PubKeyCredentialDescriptor as PubKeyCredentialDescriptor, type index_PublicKeyCredentialCreationOptions as PublicKeyCredentialCreationOptions, type index_PublicKeyCredentialParameters as PublicKeyCredentialParameters, type index_PublicKeyCredentialRequestOptions as PublicKeyCredentialRequestOptions, type index_PublicKeyCredentialRpEntity as PublicKeyCredentialRpEntity, type index_PublicKeyCredentialUserEntity as PublicKeyCredentialUserEntity, type index_RegCompleteRequestBody as RegCompleteRequestBody, type index_RegInit as RegInit, type index_RegInitRequestBody as RegInitRequestBody, index_RegService as RegService, type index_TokenVerifyRequestBody as TokenVerifyRequestBody, type index_TxComplete as TxComplete, type index_TxCompleteRequestBody as TxCompleteRequestBody, type index_TxInit as TxInit, type index_TxInitRequestBody as TxInitRequestBody, index_TxService as TxService, type index_User as User, type index_UserLogin as UserLogin, type index_Version as Version, index_VersionService as VersionService, type index_WellKnownJwks as WellKnownJwks, index_WellKnownService as WellKnownService };
1047
+ }
1048
+
950
1049
  type Complete<T> = {
951
1050
  [P in keyof T]-?: T[P];
952
1051
  };
@@ -958,10 +1057,24 @@ interface LoginIDConfig {
958
1057
  baseUrl: string;
959
1058
  appId: string;
960
1059
  }
1060
+ type FallbackMethods = AuthInit['fallbackMethods'] | AuthInit['crossAuthMethods'];
1061
+ type CrossAuthMethodsResult = {
1062
+ [K in FallbackMethods[number]]: boolean;
1063
+ };
1064
+ interface FallbackMethodsResult {
1065
+ fallbackOptions: CrossAuthMethodsResult;
1066
+ }
1067
+ type FallbackCallback = (username: string, options: FallbackMethodsResult) => Promise<void>;
1068
+ type SuccessCallback = (result: PasskeyResult) => Promise<void>;
1069
+ interface Callbacks {
1070
+ onFallback?: FallbackCallback;
1071
+ onSuccess?: SuccessCallback;
1072
+ }
961
1073
  interface PasskeyOptions {
962
1074
  token?: string;
963
1075
  displayName?: string;
964
1076
  usernameType?: UsernameType;
1077
+ callbacks?: Callbacks;
965
1078
  }
966
1079
  interface PasskeyManagementOptions {
967
1080
  token?: string;
@@ -987,8 +1100,10 @@ interface SendCodeOptions {
987
1100
  usernameType?: UsernameType;
988
1101
  }
989
1102
  interface PasskeyResult {
1103
+ isAuthenticated: boolean;
990
1104
  jwtAccess: string;
991
1105
  deviceID?: string;
1106
+ fallbackOptions?: CrossAuthMethodsResult;
992
1107
  }
993
1108
  interface LoginIDUser {
994
1109
  username: string;
@@ -1348,4 +1463,4 @@ interface DoesDeviceSupportPasskeysResponse {
1348
1463
  */
1349
1464
  declare function doesDeviceSupportPasskeys(): Promise<DoesDeviceSupportPasskeysResponse>;
1350
1465
 
1351
- export { AbortError, ApiError, type Application, type AuthCode, type AuthCodeRequestSMSRequestBody, type AuthCodeVerifyRequestBody, type AuthCompleteRequestBody, type AuthInit, type AuthInitRequestBody, AuthService, type AuthenticateWithPasskeysOptions, type AuthenticatorAssertionResponse, type AuthenticatorSelectionCriteria, type BadRequestError, BaseHttpRequest, CancelError, CancelablePromise, type Complete, type ConfirmTransactionOptions, type CreationResult, type DeletePasskeyOptions, type DeviceInfo, type DeviceInfoRequestBody, type DoesDeviceSupportPasskeysResponse, type GrantCreateRequestBody, type GrantCreateResponseBody, type JWT, type ListPasskeysOptions, type LoginIDConfig, LoginIDService, type LoginIDUser, LoginIDWebSDK, type Message, MgmtService, OpenAPI, type OpenAPIConfig, type Passkey, type PasskeyCollection, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type PasskeyRenameRequestBody, type PasskeyResult, PasskeysService, type ProfileEmailUpdateRequestBody, type ProfilePhoneUpdateRequestBody, type ProfilePhoneVerifyRequestBody, ProfileService, type PubKeyCredentialDescriptor, type PublicKeyCredentialCreationOptions, type PublicKeyCredentialParameters, type PublicKeyCredentialRequestOptions, type PublicKeyCredentialRpEntity, type PublicKeyCredentialUserEntity, type RegCompleteRequestBody, type RegInit, type RegInitRequestBody, RegService, type RegisterWithPasskeyOptions, type RenamePasskeyOptions, type SendCodeOptions, type TokenVerifyRequestBody, type Transports, type TxComplete, type TxCompleteRequestBody, type TxInit, type TxInitRequestBody, TxService, type User, type UserLogin, type UsernameType, type VerifyConfigResult, type Version, VersionService, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
1466
+ export { AbortError, ApiError, type AuthenticateWithPasskeysOptions, type Callbacks, type Complete, type ConfirmTransactionOptions, type CrossAuthMethodsResult, type DeletePasskeyOptions, type DeviceInfoRequestBody, type DoesDeviceSupportPasskeysResponse, type FallbackCallback, type FallbackMethods, type FallbackMethodsResult, type ListPasskeysOptions, index as LoginIDAPI, type LoginIDConfig, type LoginIDUser, LoginIDWebSDK, type Message, PasskeyError, type PasskeyManagementOptions, type PasskeyOptions, type PasskeyResult, type RegisterWithPasskeyOptions, type RenamePasskeyOptions, type SendCodeOptions, type SuccessCallback, type Transports, type UsernameType, type VerifyConfigResult, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var K=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https:\/\/([0-9a-fA-F-]+)\.api.*\.loginid\.io/,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},w=K;var V=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=V;var oe=(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},se=(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},D=new Error("User needs to be logged in to perform this operation.");var ge=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Ce=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},be=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},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=Ce(e);return ge(s)},f=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=be(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},ne=()=>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))})})},g=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)}},ae=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},ue=t=>{document.cookie=t},pe=t=>{document.cookie=`${t}=; expires=${new Date}`};var _=class{config;constructor(e){this.config=new w(e)}getToken(e){if(e.token)return e.token;{let r=this.getJwtCookie();return r||""}}getUser(){if(!this.isLoggedIn())throw D;let e=g(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=g(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;ue(o)}getJwtCookie(){return ae(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){pe(this.getJwtCookieName())}},le=_;var C=class{constructor(e){this.config=e}};var c=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 N=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},b=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 N("Request aborted"))}}get isCancelled(){return this.#e}};var W=t=>t!=null,P=t=>typeof t=="string",j=t=>P(t)&&t!=="",J=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]),de=t=>t instanceof FormData,Pe=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)=>{W(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("&")}`:""},Ae=(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},Ie=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{P(o)||J(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>W(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},U=async(t,e)=>typeof e=="function"?e(t):e,Te=async(t,e)=>{let[r,s,o,n]=await Promise.all([U(e,t.TOKEN),U(e,t.USERNAME),U(e,t.PASSWORD),U(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>W(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(j(r)&&(i.Authorization=`Bearer ${r}`),j(s)&&j(o)){let a=Pe(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:J(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":P(e.body)?i["Content-Type"]="text/plain":de(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},Be=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):P(t.body)||J(t.body)||de(t.body)?t.body:JSON.stringify(t.body)},Ee=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)},Oe=(t,e)=>{if(e){let r=t.headers.get(e);if(P(r))return r}},xe=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)}},Se=(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 c(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 c(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},ce=(t,e)=>new b(async(r,s,o)=>{try{let n=Ae(t,e),i=Ie(e),a=Be(e),u=await Te(t,e);if(!o.isCancelled){let p=await Ee(t,e,n,a,i,u,o),R=await xe(p),v=Oe(p,e.responseHeader),re={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:v??R};Se(e,re),r(re.body)}}catch(n){s(n)}});var L=class extends C{constructor(e){super(e)}request(e){return ce(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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var A=class{constructor(e){this.httpRequest=e}mgmtGrantCreate({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/grant",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}mgmtTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/token/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}};var I=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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var T=class{constructor(e){this.httpRequest=e}profileProfileDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}",path:{id:e},errors:{404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/email",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}/phone",path:{id:e},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/phone",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/email/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/phone/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var B=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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",500:"InternalServerError: Internal Server Error response."}})}};var O=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var x=class{auth;mgmt;passkeys;profile;reg;tx;version;request;constructor(e,r=L){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.mgmt=new A(this.request),this.passkeys=new I(this.request),this.profile=new T(this.request),this.reg=new B(this.request),this.tx=new E(this.request),this.version=new O(this.request)}};var M=class{config;service;session;constructor(e){this.config=new w(e),this.service=new x({BASE:e.baseUrl}),this.session=new le(e)}},y=M;var z=class extends Error{constructor(e){super(e),this.name="AbortError"}},$=z;var G=class t{static abortController=new AbortController;static renewWebAuthnAbortController=()=>{let e=new $("Cancelling current WebAuthn request");t.abortController.abort(e);let r=new AbortController;t.abortController=r}},h=G;var m=(t,e)=>({...e,token:e.token||"",usernameType:e.usernameType||"email",displayName:e.displayName||t}),ye=(t,e)=>({...m(t,e),txType:e.txType||"raw",nonce:e.nonce||ne()});var Y=class extends y{constructor(e){super(e)}async authenticateWithCode(e,r,s={}){let o=m(e,s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthCodeVerify({requestBody:n});return h.renewWebAuthnAbortController(),this.session.setJwtCookie(i.jwtAccess),i}async sendCode(e,r="email",s={}){let o=m(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")}return null}},H=Y;var ke={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 Q=class extends y{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=m("",{}),s={app:{id:this.config.getAppId()},deviceInfo:{},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 c&&(e.code=r.body.msgCode||"unknown_error",e.message=r.body.msg||r.body.message||"Unknown error."),e}return e}getUser(){return this.session.getUser()}isLoggedIn(){return this.session.isLoggedIn()}signout(){this.session.signout()}},me=Q;import{UAParser as ve}from"ua-parser-js";var X=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),we=(t,e)=>{let r=t.split(".").map(Number),s=e.split(".").map(Number),o=Math.max(r.length,s.length);for(let n=0;n<o;n++){let i=n<r.length?r[n]:0,a=n<s.length?s[n]:0;if(i<a)return-1;if(i>a)return 1}return 0};async function De(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Ne(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function Ue(){let t=new ve(window.navigator.userAgent).getResult(),e={solution:"",deviceSupported:!1};if(!window.PublicKeyCredential)return e.solution="Your browser seems to be outdated. Please upgrade to the latest version.",e;if(!await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable())switch(t.os.name){case"Mac OS":{let s=t.browser.version||"";return t.browser.name==="Firefox"&&we(s,"122.0")<0?(e.solution="Please update your Firefox browser to the latest version.",e):(e.solution="Enable Touch ID on your device.",e)}case"iOS":return e.solution="Enable Face ID or Touch ID on your device.",e;case"Windows":return e.solution="Enable Windows Hello on your device. See here: https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0.",e;case"Android":return t.browser.name==="Firefox"?(e.solution="Passkeys may not be supported on your Firefox browser. Please switch to a Chromium browser.",e):(e.solution="Enable device unlock via fingerprint, PIN, or facial recognition on your device.",e);default:return e.solution="Enable device unlock features such as fingerprint, PIN, or facial recognition.",e}return e.deviceSupported=!0,e}var S=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:f(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:f(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:f(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?oe(o,s):o}},k=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:f(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortSignal&&{signal:e.abortSignal},publicKey:{allowCredentials:r,challenge:f(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?se(o,s):o}};var Z=class extends H{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;h.renewWebAuthnAbortController();let o=await S(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:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}async registerWithPasskey(e,r={}){let s=X(),o=m(e,r);r.token=this.session.getToken(r),r.token&&g(r.token).username!==e&&(r.token="");let n={app:{id:this.config.getAppId()},deviceInfo:s,user:{username:e,usernameType:o.usernameType,displayName:o.displayName},...r.session&&{session:r.session}},i=await this.service.reg.regRegInit({requestBody:n,...r.token&&{authorization:r.token}}),a=await this.createNavigatorCredential(i),u=await this.service.reg.regRegComplete({requestBody:a});return this.session.setJwtCookie(u.jwtAccess),u}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortSignal||(h.renewWebAuthnAbortController(),r.abortSignal=h.abortController.signal);let n=await k(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=X(),o=m(e,r),n={app:{id:this.config.getAppId()},deviceInfo:s,user:{username:e,usernameType:o.usernameType}},i=await this.service.auth.authAuthInit({requestBody:n}),a=await this.getNavigatorCredential(i,r),u=await this.service.auth.authAuthComplete({requestBody:a});return this.session.setJwtCookie(u.jwtAccess),u}async enablePasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async generateCodeWithPasskey(e,r={}){if(r.token=this.session.getToken(r),!r.token){let o=await this.authenticateWithPasskey(e,r);r.token=o.jwtAccess}return await this.service.auth.authAuthCodeRequest({authorization:r.token})}async addPasskey(e,r={}){let s=this.session.getToken(r);if(!s)throw D;return r.token=s,await this.registerWithPasskey(e,r)}async addPasskeyWithCode(e,r,s={}){return await this.authenticateWithCode(e,r,s),await this.registerWithPasskey(e,s)}async confirmTransaction(e,r,s={}){let o=ye(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",affirmMethods:[],fallbackMethods:[],assertionOptions:i,session:a},{assertionResult:p}=await this.getNavigatorCredential(u),R={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature},v=await this.service.tx.txTxComplete({requestBody:R});return this.session.setJwtCookie(v.jwtAccess),v}},fe=Z;var ee=class extends y{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};return await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n}),null}async deletePasskey(e,r={}){let s=this.session.getToken(r);return await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e}),null}},he=ee;var F=class extends y{constructor(e){super(e)}};ie(F,[y,fe,H,he,me]);var Re=F;var te=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await k(s,r),i=n.response;return{assertionResult:{authenticatorData:l(i.authenticatorData),clientDataJSON:l(i.clientDataJSON),credentialId:n.id,signature:l(i.signature),...i.userHandle&&{userHandle:l(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await S(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:l(n.attestationObject),clientDataJSON:l(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:l(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:l(u)},...p&&{transports:p}},session:s}}};var kr=Re;export{$ as AbortError,c as ApiError,q as AuthService,C as BaseHttpRequest,N as CancelError,b as CancelablePromise,x as LoginIDService,Re as LoginIDWebSDK,A as MgmtService,ke as OpenAPI,d as PasskeyError,I as PasskeysService,T as ProfileService,B as RegService,E as TxService,O as VersionService,te as WebAuthnHelper,S as createPasskeyCredential,kr as default,Ue as doesDeviceSupportPasskeys,k as getPasskeyCredential,Ne as isConditionalUIAvailable,De as isPlatformAuthenticatorAvailable};
1
+ var Oe=Object.defineProperty;var Ee=(t,e)=>{for(var r in e)Oe(t,r,{get:e[r],enumerable:!0})};var W=class{config;constructor(e){this.config=e}getAppId(){if(this.config.appId)return this.config.appId;let e=/https:\/\/([0-9a-fA-F-]+)\.api.*\.loginid\.io/,r=this.config.baseUrl.match(e);if(r)return r[1];throw new Error("Invalid LoginID base URL. App ID not found.")}},L=W;var j=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},c=j;var M=class extends Error{constructor(e){super(e),this.name="LoginIDError"}},J=M;var ue=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new c("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new c("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new c("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new c("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new c("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 c(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new c("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},le=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new c("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new c("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 c(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new c("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},F=new J("User needs to be logged in to perform this operation."),z=new J("No login options available.");var Be=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),xe=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++),l=i<<16|a<<8|u;r.push(e[l>>18&63]+e[l>>12&63]+e[l>>6&63]+e[l&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},Se=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},p=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=xe(e);return Be(s)},h=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Se(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},pe=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),de=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},S=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)}},ce=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},me=t=>{document.cookie=t},ye=t=>{document.cookie=`${t}=; expires=${new Date}`};var $=class{config;constructor(e){this.config=new L(e)}getToken(e){if(e.token)return e.token;{let r=this.getJwtCookie();return r||""}}getUser(){if(!this.isLoggedIn())throw F;let e=S(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=S(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;me(o)}getJwtCookie(){return ce(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){ye(this.getJwtCookieName())}},fe=$;var R=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}},g=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 Y=t=>t!=null,w=t=>typeof t=="string",G=t=>w(t)&&t!=="",Q=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]),he=t=>t instanceof FormData,ve=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},we=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{Y(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("&")}`:""},De=(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}${we(e.query)}`:o},Ne=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{w(o)||Q(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>Y(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},K=async(t,e)=>typeof e=="function"?e(t):e,Ue=async(t,e)=>{let[r,s,o,n]=await Promise.all([K(e,t.TOKEN),K(e,t.USERNAME),K(e,t.PASSWORD),K(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>Y(u)).reduce((a,[u,l])=>({...a,[u]:String(l)}),{});if(G(r)&&(i.Authorization=`Bearer ${r}`),G(s)&&G(o)){let a=ve(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:Q(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":w(e.body)?i["Content-Type"]="text/plain":he(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},Le=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):w(t.body)||Q(t.body)||he(t.body)?t.body:JSON.stringify(t.body)},Fe=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)},Ke=(t,e)=>{if(e){let r=t.headers.get(e);if(w(r))return r}},He=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)}},_e=(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}`)}},Re=(t,e)=>new g(async(r,s,o)=>{try{let n=De(t,e),i=Ne(e),a=Le(e),u=await Ue(t,e);if(!o.isCancelled){let l=await Fe(t,e,n,a,i,u,o),d=await He(l),x=Ke(l,e.responseHeader),ae={url:n,ok:l.ok,status:l.status,statusText:l.statusText,body:x??d};_e(e,ae),r(ae.body)}}catch(n){s(n)}});var H=class extends R{constructor(e){super(e)}request(e){return Re(this.config,e)}};var b=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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var C=class{constructor(e){this.httpRequest=e}mgmtGrantCreate({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/grant",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}mgmtTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/mgmt/token/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",500:"InternalServerError: Internal Server Error response."}})}};var P=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:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var q=class{constructor(e){this.httpRequest=e}profileProfileDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}",path:{id:e},errors:{404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/email",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneDelete({id:e}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/profile/{id}/phone",path:{id:e},errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneUpdate({id:e,requestBody:r}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/{id}/phone",path:{id:e},body:r,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfileEmailVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/email/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}profileProfilePhoneVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/profile/phone/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var A=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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var I=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:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: 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:"BadRequest: Bad Request response.",500:"InternalServerError: Internal Server Error response."}})}};var k=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var T=class{constructor(e){this.httpRequest=e}wellKnownJwks(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/.well-known/jwks.json",errors:{500:"InternalServerError: Internal Server Error response."}})}};var O=class{auth;mgmt;passkeys;profile;reg;tx;version;wellKnown;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 b(this.request),this.mgmt=new C(this.request),this.passkeys=new P(this.request),this.profile=new q(this.request),this.reg=new A(this.request),this.tx=new I(this.request),this.version=new k(this.request),this.wellKnown=new T(this.request)}};var X=class{config;service;session;constructor(e){this.config=new L(e),this.service=new O({BASE:e.baseUrl}),this.session=new fe(e)}},y=X;var Z=class extends Error{constructor(e){super(e),this.name="AbortError"}},ee=Z;var te=class t{static abortController=new AbortController;static renewWebAuthnAbortController=()=>{let e=new ee("Cancelling current WebAuthn request");t.abortController.abort(e);let r=new AbortController;t.abortController=r}},E=te;var f=(t,e)=>({...e,token:e.token||"",usernameType:e.usernameType||"email",displayName:e.displayName||t,callbacks:e.callbacks||{}}),ge=(t,e)=>({...f(t,e),txType:e.txType||"raw",nonce:e.nonce||pe()});var re=class extends y{constructor(e){super(e)}async authenticateWithCode(e,r,s={}){let o=f(e,s),n={authCode:r,user:{username:e,usernameType:o.usernameType}},a={...await this.service.auth.authAuthCodeVerify({requestBody:n}),isAuthenticated:!0};return E.renewWebAuthnAbortController(),this.session.setJwtCookie(a.jwtAccess),a}async sendCode(e,r="email",s={}){let o=f(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")}return null}},_=re;import{UAParser as Ve}from"ua-parser-js";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},We=(t,e)=>{let r=t.split(".").map(Number),s=e.split(".").map(Number),o=Math.max(r.length,s.length);for(let n=0;n<o;n++){let i=n<r.length?r[n]:0,a=n<s.length?s[n]:0;if(i<a)return-1;if(i>a)return 1}return 0};async function je(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Me(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function Je(){let t=new Ve(window.navigator.userAgent).getResult(),e={solution:"",deviceSupported:!1};if(!window.PublicKeyCredential)return e.solution="Your browser seems to be outdated. Please upgrade to the latest version.",e;if(!await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable())switch(t.os.name){case"Mac OS":{let s=t.browser.version||"";return t.browser.name==="Firefox"&&We(s,"122.0")<0?(e.solution="Please update your Firefox browser to the latest version.",e):(e.solution="Enable Touch ID on your device.",e)}case"iOS":return e.solution="Enable Face ID or Touch ID on your device.",e;case"Windows":return e.solution="Enable Windows Hello on your device. See here: https://support.microsoft.com/en-us/windows/learn-about-windows-hello-and-set-it-up-dae28983-8242-bb2a-d3d1-87c9d265a5f0.",e;case"Android":return t.browser.name==="Firefox"?(e.solution="Passkeys may not be supported on your Firefox browser. Please switch to a Chromium browser.",e):(e.solution="Enable device unlock via fingerprint, PIN, or facial recognition on your device.",e);default:return e.solution="Enable device unlock features such as fingerprint, PIN, or facial recognition.",e}return e.deviceSupported=!0,e}var Ce={};Ee(Ce,{ApiError:()=>m,AuthService:()=>b,BaseHttpRequest:()=>R,CancelError:()=>v,CancelablePromise:()=>g,LoginIDService:()=>O,MgmtService:()=>C,OpenAPI:()=>be,PasskeysService:()=>P,ProfileService:()=>q,RegService:()=>A,TxService:()=>I,VersionService:()=>k,WellKnownService:()=>T});var be={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 oe=class extends y{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=f("",{}),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}getUser(){return this.session.getUser()}isLoggedIn(){return this.session.isLoggedIn()}signout(){this.session.signout()}},Pe=oe;var qe=t=>`LoginID_${t}_device-id`,B=class{static persistDeviceId(e,r){r&&localStorage.setItem(qe(e),r)}static getDeviceId(e){return localStorage.getItem(qe(e))||""}};var Ae=t=>{let e={ciam:!1,otp:!1,"otp:email":!1,"otp:sms":!1};return[...t.crossAuthMethods,...t.fallbackMethods].reduce((o,n)=>(o[n]=!0,o),e)};var N=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:h(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:h(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:h(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?ue(o,s):o}},U=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:h(o.id),transports:o.transports,type:o.type};r.push(n)}}let s={...e.autoFill&&{mediation:"conditional"},...e.abortSignal&&{signal:e.abortSignal},publicKey:{allowCredentials:r,challenge:h(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?le(o,s):o}};var se=class extends _{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;E.renewWebAuthnAbortController();let o=await N(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),l=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:p(n.attestationObject),clientDataJSON:p(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:p(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:p(u)},...l&&{transports:l}},session:s}}async registerWithPasskey(e,r={}){let s=this.config.getAppId(),o=D(B.getDeviceId(s)),n=f(e,r);r.token=this.session.getToken(r),r.token&&S(r.token).username!==e&&(r.token="");let i={app:{id:s},deviceInfo:o,user:{username:e,usernameType:n.usernameType,displayName:n.displayName},...r.session&&{session:r.session}},a=await this.service.reg.regRegInit({requestBody:i,...r.token&&{authorization:r.token}}),u=await this.createNavigatorCredential(a),d={...await this.service.reg.regRegComplete({requestBody:u}),isAuthenticated:!0};return this.session.setJwtCookie(d.jwtAccess),B.persistDeviceId(s,d.deviceID),d}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortSignal||(E.renewWebAuthnAbortController(),r.abortSignal=E.abortController.signal);let n=await U(s,r),i=n.response;return{assertionResult:{authenticatorData:p(i.authenticatorData),clientDataJSON:p(i.clientDataJSON),credentialId:n.id,signature:p(i.signature),...i.userHandle&&{userHandle:p(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=this.config.getAppId(),o=D(B.getDeviceId(s)),n=f(e,r),i={app:{id:s},deviceInfo:o,user:{username:e,usernameType:n.usernameType}},a=await this.service.auth.authAuthInit({requestBody:i});switch(a.action){case"proceed":{let u=await this.getNavigatorCredential(a,r),d={...await this.service.auth.authAuthComplete({requestBody:u}),isAuthenticated:!0};return this.session.setJwtCookie(d.jwtAccess),n?.callbacks?.onSuccess&&await n.callbacks.onSuccess(d),d}case"crossAuth":case"fallback":{if(n?.callbacks?.onFallback){let u=Ae(a);return await n.callbacks.onFallback(e,{fallbackOptions:u}),{jwtAccess:"",isAuthenticated:!1,fallbackOptions:u}}throw z}default:throw z}}async enablePasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async generateCodeWithPasskey(e,r={}){if(r.token=this.session.getToken(r),!r.token){let o=await this.authenticateWithPasskey(e,r);r.token=o.jwtAccess}return await this.service.auth.authAuthCodeRequest({authorization:r.token})}async addPasskey(e,r={}){let s=this.session.getToken(r);if(!s)throw F;return r.token=s,await this.registerWithPasskey(e,r)}async addPasskeyWithCode(e,r,s={}){return await this.authenticateWithCode(e,r,s),await this.registerWithPasskey(e,s)}async confirmTransaction(e,r,s={}){let o=ge(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:l}=await this.getNavigatorCredential(u),d={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:a,signature:l.signature},x=await this.service.tx.txTxComplete({requestBody:d});return this.session.setJwtCookie(x.jwtAccess),x}},Ie=se;var ne=class extends y{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};return await this.service.passkeys.passkeysPasskeyRename({authorization:o,id:e,requestBody:n}),null}async deletePasskey(e,r={}){let s=this.session.getToken(r);return await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e}),null}},ke=ne;var V=class extends y{constructor(e){super(e)}};de(V,[y,Ie,_,ke,Pe]);var Te=V;var ie=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await U(s,r),i=n.response;return{assertionResult:{authenticatorData:p(i.authenticatorData),clientDataJSON:p(i.clientDataJSON),credentialId:n.id,signature:p(i.signature),...i.userHandle&&{userHandle:p(i.userHandle)}},session:o}}static async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await N(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),u=n.getAuthenticatorData&&n.getAuthenticatorData(),l=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:p(n.attestationObject),clientDataJSON:p(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:p(i)},...a&&{publicKeyAlgorithm:a},...u&&{authenticatorData:p(u)},...l&&{transports:l}},session:s}}};var Xr=Te;export{ee as AbortError,m as ApiError,Ce as LoginIDAPI,Te as LoginIDWebSDK,c as PasskeyError,ie as WebAuthnHelper,N as createPasskeyCredential,Xr as default,Je as doesDeviceSupportPasskeys,U as getPasskeyCredential,Me as isConditionalUIAvailable,je as isPlatformAuthenticatorAvailable};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loginid/websdk3",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",