@loginid/websdk3 1.5.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +138 -48
- package/dist/index.d.ts +138 -48
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var H=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var me=(t,e)=>{for(var r in e)H(t,r,{get:e[r],enumerable:!0})},he=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ce(e))!ye.call(t,o)&&o!==r&&H(t,o,{get:()=>e[o],enumerable:!(s=de(e,o))||s.enumerable});return t};var fe=t=>he(H({},"__esModule",{value:!0}),t);var ke={};me(ke,{ApiError:()=>c,AuthService:()=>R,BaseHttpRequest:()=>h,CancelError:()=>S,CancelablePromise:()=>f,LoginIDService:()=>T,LoginIDWebSDK:()=>z,MgmtService:()=>g,OpenAPI:()=>le,PasskeyError:()=>d,PasskeysService:()=>C,ProfileService:()=>b,RegService:()=>P,TxService:()=>q,VersionService:()=>A,WebAuthnHelper:()=>U,createPasskeyCredential:()=>B,default:()=>ve,doesDeviceSupportPasskeys:()=>ie,getPasskeyCredential:()=>I,isConditionalUIAvailable:()=>ne,isPlatformAuthenticatorAvailable:()=>se});module.exports=fe(ke);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 S=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},f=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 S("Request aborted"))}}get isCancelled(){return this.#e}};var K=t=>t!=null,O=t=>typeof t=="string",F=t=>O(t)&&t!=="",L=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]),$=t=>t instanceof FormData,Re=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},ge=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{K(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("&")}`:""},Ce=(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}${ge(e.query)}`:o},be=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{O(o)||L(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>K(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},v=async(t,e)=>typeof e=="function"?e(t):e,Pe=async(t,e)=>{let[r,s,o,n]=await Promise.all([v(e,t.TOKEN),v(e,t.USERNAME),v(e,t.PASSWORD),v(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>K(u)).reduce((a,[u,l])=>({...a,[u]:String(l)}),{});if(F(r)&&(i.Authorization=`Bearer ${r}`),F(s)&&F(o)){let a=Re(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:L(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":O(e.body)?i["Content-Type"]="text/plain":$(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},qe=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):O(t.body)||L(t.body)||$(t.body)?t.body:JSON.stringify(t.body)},Ae=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)},Te=(t,e)=>{if(e){let r=t.headers.get(e);if(O(r))return r}},Ee=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)}},Be=(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}`)}},G=(t,e)=>new f(async(r,s,o)=>{try{let n=Ce(t,e),i=be(e),a=qe(e),u=await Pe(t,e);if(!o.isCancelled){let l=await Ae(t,e,n,a,i,u,o),m=await Ee(l),pe=Te(l,e.responseHeader),M={url:n,ok:l.ok,status:l.status,statusText:l.statusText,body:pe??m};Be(e,M),r(M.body)}}catch(n){s(n)}});var k=class extends h{constructor(e){super(e)}request(e){return G(this.config,e)}};var R=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.",403:"Forbidden: Forbidden 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 g=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 C=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 b=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 P=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 q=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 A=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=k){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 R(this.request),this.mgmt=new g(this.request),this.passkeys=new C(this.request),this.profile=new b(this.request),this.reg=new P(this.request),this.tx=new q(this.request),this.version=new A(this.request)}};var _=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=_;var Y=(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},Q=(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},w=t=>{let e=new Error("Cancelling current WebAuthn request");return e.name="AbortError",t.abort(e),new AbortController},D=new Error("User needs to be logged in to perform this operation.");var Ie=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Se=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},Oe=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=Se(e);return Ie(s)},E=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Oe(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},X=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),Z=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},x=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)}},ee=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},te=t=>{document.cookie=t},re=t=>{document.cookie=`${t}=; expires=${new Date}`};var j=class{config;service;abortController=new AbortController;constructor(e){this.config=e,this.service=new T({BASE:e.baseUrl})}getToken(e){if(e.token)return e.token;{let r=this.getJwtCookie();return r||""}}getUser(){if(!this.isLoggedIn())throw D;let e=x(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.appId}_token`}setJwtCookie(e){let r=x(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;te(o)}getJwtCookie(){return ee(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){re(this.getJwtCookieName())}},y=j;var oe=require("ua-parser-js"),W=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),xe=(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 se(){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 ie(){let t=new oe.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"&&xe(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 B=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:E(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:E(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:E(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?Y(o,s):o}},I=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:E(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:E(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?Q(o,s):o}};var V=class extends y{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;this.abortController=w(this.abortController);let o=await B(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=W();r.usernameType||(r.usernameType="email"),r.token=this.getToken(r),r.token&&x(r.token).username!==e&&(r.token="");let o={app:{id:this.config.appId},deviceInfo:s,user:{username:e,usernameType:r.usernameType,...r.displayName&&{displayName:r.displayName}},...r.session&&{session:r.session}},n=await this.service.reg.regRegInit({requestBody:o,...r.token&&{authorization:r.token}}),i=await this.createNavigatorCredential(n),a=await this.service.reg.regRegComplete({requestBody:i});return this.setJwtCookie(a.jwtAccess),a}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortSignal||(this.abortController=w(this.abortController),r.abortSignal=this.abortController.signal);let n=await I(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=W();r.usernameType||(r.usernameType="email");let o={app:{id:this.config.appId,...r.token&&{token:r.token}},deviceInfo:s,user:{username:e,usernameType:r.usernameType,...r.displayName&&{displayName:r.displayName}}},n=await this.service.auth.authAuthInit({requestBody:o}),i=await this.getNavigatorCredential(n,r),a=await this.service.auth.authAuthComplete({requestBody:i});return this.setJwtCookie(a.jwtAccess),a}async enablePasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async generateCodeWithPasskey(e,r={}){if(r.token=this.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 authenticateWithCode(e,r,s={}){s.usernameType||(s.usernameType="email");let o={authCode:r,user:{username:e,usernameType:s.usernameType}},n=await this.service.auth.authAuthCodeVerify({requestBody:o});return this.abortController=w(this.abortController),this.setJwtCookie(n.jwtAccess),n}async addPasskey(e,r={}){let s=this.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={username:e,txPayload:r,nonce:s.nonce||X(),txType:s.txType||"raw"},{assertionOptions:n,session:i}=await this.service.tx.txTxInit({requestBody:o}),a={assertionOptions:n,session:i},{assertionResult:u}=await this.getNavigatorCredential(a),l={authenticatorData:u.authenticatorData,clientData:u.clientDataJSON,keyHandle:u.credentialId,session:i,signature:u.signature},m=await this.service.tx.txTxComplete({requestBody:l});return this.setJwtCookie(m.jwtAccess),m}},ae=V;var J=class extends y{constructor(e){super(e)}async listPasskeys(e={}){let r=this.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.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.getToken(r);return await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e}),null}},ue=J;var N=class extends y{constructor(e){super(e)}};Z(N,[y,ae,ue]);var z=N;var U=class{static async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await I(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 B(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 le={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 ve=z;0&&(module.exports={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 j=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var qe=Object.prototype.hasOwnProperty;var Ae=(t,e)=>{for(var r in e)j(t,r,{get:e[r],enumerable:!0})},Te=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pe(e))!qe.call(t,o)&&o!==r&&j(t,o,{get:()=>e[o],enumerable:!(s=be(e,o))||s.enumerable});return t};var Ie=t=>Te(j({},"__esModule",{value:!0}),t);var je={};Ae(je,{ApiError:()=>c,AuthService:()=>g,BaseHttpRequest:()=>h,CancelError:()=>k,CancelablePromise:()=>R,LoginIDService:()=>I,LoginIDWebSDK:()=>ee,MgmtService:()=>C,OpenAPI:()=>Ce,PasskeyError:()=>d,PasskeysService:()=>b,ProfileService:()=>P,RegService:()=>q,TxService:()=>A,VersionService:()=>T,WebAuthnHelper:()=>K,createPasskeyCredential:()=>B,default:()=>Ke,doesDeviceSupportPasskeys:()=>he,getPasskeyCredential:()=>O,isConditionalUIAvailable:()=>fe,isPlatformAuthenticatorAvailable:()=>me});module.exports=Ie(je);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.")}},D=W;var _=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=_;var re=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new d("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new d("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new d("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new d("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new d("Your device does not support the algorithms required for passkey creation","ERROR_ALGORITHMS_UNSUPPORTED",t);if(r==="SecurityError"){let o=s?.rp?.id;if(o!==window.location.hostname)return new d(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new d("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},oe=(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 Ee=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Be=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},Oe=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=Be(e);return Ee(s)},f=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Oe(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},se=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),ne=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},x=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)}},ie=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},ae=t=>{document.cookie=t},ue=t=>{document.cookie=`${t}=; expires=${new Date}`};var V=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=x(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.getAppId()}_token`}setJwtCookie(e){let r=x(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;ae(o)}getJwtCookie(){return ie(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){ue(this.getJwtCookieName())}},pe=V;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 M=t=>t!=null,v=t=>typeof t=="string",J=t=>v(t)&&t!=="",z=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]),le=t=>t instanceof FormData,Se=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},xe=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{M(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("&")}`:""},ke=(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}${xe(e.query)}`:o},ve=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{v(o)||z(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>M(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,we=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])=>M(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(J(r)&&(i.Authorization=`Bearer ${r}`),J(s)&&J(o)){let a=Se(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:z(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":v(e.body)?i["Content-Type"]="text/plain":le(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},De=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):v(t.body)||z(t.body)||le(t.body)?t.body:JSON.stringify(t.body)},Ne=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)},Ue=(t,e)=>{if(e){let r=t.headers.get(e);if(v(r))return r}},Le=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)}},He=(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}`)}},de=(t,e)=>new R(async(r,s,o)=>{try{let n=ke(t,e),i=ve(e),a=De(e),u=await we(t,e);if(!o.isCancelled){let p=await Ne(t,e,n,a,i,u,o),S=await Le(p),w=Ue(p,e.responseHeader),te={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:w??S};He(e,te),r(te.body)}}catch(n){s(n)}});var L=class extends h{constructor(e){super(e)}request(e){return de(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 T=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var I=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 T(this.request)}};var $=class{config;service;session;constructor(e){this.config=new D(e),this.service=new I({BASE:e.baseUrl}),this.session=new pe(e)}getUser(){return this.session.getUser()}isLoggedIn(){return this.session.isLoggedIn()}signout(){this.session.signout()}},y=$;var G=class t{static abortController=new AbortController;static renewWebAuthnAbortController=()=>{let e=new Error("Cancelling current WebAuthn request");e.name="AbortError",t.abortController.abort(e);let r=new AbortController;t.abortController=r}},E=G;var m=(t,e)=>({...e,token:e.token||"",usernameType:e.usernameType||"email",displayName:e.displayName||t}),ce=(t,e)=>({...m(t,e),txType:e.txType||"raw",nonce:e.nonce||se()});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 E.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 ye=require("ua-parser-js"),Q=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),Fe=(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 me(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function fe(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function he(){let t=new ye.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"&&Fe(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 B=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?re(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?oe(o,s):o}};var X=class extends H{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;E.renewWebAuthnAbortController();let o=await B(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=Q(),o=m(e,r);r.token=this.session.getToken(r),r.token&&x(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||(E.renewWebAuthnAbortController(),r.abortSignal=E.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=Q(),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=ce(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),S={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:a,signature:p.signature},w=await this.service.tx.txTxComplete({requestBody:S});return this.session.setJwtCookie(w.jwtAccess),w}},Re=X;var Z=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}},ge=Z;var F=class extends y{constructor(e){super(e)}};ne(F,[y,Re,H,ge]);var ee=F;var K=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 B(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 Ce={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 Ke=ee;0&&(module.exports={ApiError,AuthService,BaseHttpRequest,CancelError,CancelablePromise,LoginIDService,LoginIDWebSDK,MgmtService,OpenAPI,PasskeyError,PasskeysService,ProfileService,RegService,TxService,VersionService,WebAuthnHelper,createPasskeyCredential,doesDeviceSupportPasskeys,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -128,7 +128,7 @@ type PubKeyCredentialDescriptor = {
|
|
|
128
128
|
* Base64 encoded byte array of the public key identifier.
|
|
129
129
|
*/
|
|
130
130
|
id: string;
|
|
131
|
-
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid'>;
|
|
131
|
+
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid' | 'cable' | 'smart-card'>;
|
|
132
132
|
type: 'public-key';
|
|
133
133
|
};
|
|
134
134
|
|
|
@@ -175,11 +175,28 @@ type PublicKeyCredentialRequestOptions = {
|
|
|
175
175
|
};
|
|
176
176
|
|
|
177
177
|
type AuthInit = {
|
|
178
|
+
/**
|
|
179
|
+
* An action to be performed by the front-end to complete the authentication flow.
|
|
180
|
+
*/
|
|
181
|
+
action: 'proceed' | 'affirm' | 'fallback';
|
|
182
|
+
/**
|
|
183
|
+
* List of cross authentication methods in the order of preference
|
|
184
|
+
*/
|
|
185
|
+
affirmMethods: Array<'otp' | 'otp:sms' | 'otp:email'>;
|
|
178
186
|
assertionOptions: PublicKeyCredentialRequestOptions;
|
|
179
187
|
/**
|
|
180
|
-
*
|
|
188
|
+
* The list contains available fallback methods in the order of preference. The
|
|
189
|
+
* list is dynamic and shall not be cached. The default fallback mechanism is
|
|
190
|
+
* the one provided by CIAM but our system may provide additional ones as well.
|
|
191
|
+
* These methods may be enabled by customer via application configuration but
|
|
192
|
+
* they are disabled by default. The list may be empty which means no fallback
|
|
193
|
+
* is available and authentication flow shall terminate at this point.
|
|
181
194
|
*/
|
|
182
|
-
|
|
195
|
+
fallbackMethods: Array<'ciam'>;
|
|
196
|
+
/**
|
|
197
|
+
* Type of passkey supported by the client.
|
|
198
|
+
*/
|
|
199
|
+
passkeyType?: string;
|
|
183
200
|
/**
|
|
184
201
|
* An opaque object containing session data.
|
|
185
202
|
*/
|
|
@@ -251,19 +268,11 @@ type AuthInitRequestBody = {
|
|
|
251
268
|
user?: UserLogin;
|
|
252
269
|
};
|
|
253
270
|
|
|
254
|
-
type
|
|
255
|
-
/**
|
|
256
|
-
* Generated code
|
|
257
|
-
*/
|
|
258
|
-
code: string;
|
|
271
|
+
type JWT = {
|
|
259
272
|
/**
|
|
260
|
-
*
|
|
273
|
+
* Device ID
|
|
261
274
|
*/
|
|
262
|
-
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
type JWT = {
|
|
266
|
-
code?: CodeResult;
|
|
275
|
+
deviceID?: string;
|
|
267
276
|
/**
|
|
268
277
|
* JWT access token
|
|
269
278
|
*/
|
|
@@ -599,7 +608,7 @@ type CreationResult = {
|
|
|
599
608
|
* These values are the transports that the authenticator is believed to support,
|
|
600
609
|
* or an empty sequence if the information is unavailable.
|
|
601
610
|
*/
|
|
602
|
-
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid'>;
|
|
611
|
+
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid' | 'cable' | 'smart-card'>;
|
|
603
612
|
};
|
|
604
613
|
|
|
605
614
|
type RegCompleteRequestBody = {
|
|
@@ -706,6 +715,10 @@ type PublicKeyCredentialCreationOptions = {
|
|
|
706
715
|
};
|
|
707
716
|
|
|
708
717
|
type RegInit = {
|
|
718
|
+
/**
|
|
719
|
+
* An action to be performed by the front-end to complete the registration flow.
|
|
720
|
+
*/
|
|
721
|
+
action: 'proceed' | 'signIn' | 'fail';
|
|
709
722
|
registrationRequestOptions: PublicKeyCredentialCreationOptions;
|
|
710
723
|
/**
|
|
711
724
|
* An opaque object containing session data.
|
|
@@ -934,9 +947,13 @@ type BadRequestError = {
|
|
|
934
947
|
msgCode: string;
|
|
935
948
|
};
|
|
936
949
|
|
|
950
|
+
type Complete<T> = {
|
|
951
|
+
[P in keyof T]-?: T[P];
|
|
952
|
+
};
|
|
937
953
|
type UsernameType = User['usernameType'];
|
|
938
954
|
type DeviceInfoRequestBody = DeviceInfo;
|
|
939
955
|
type Transports = CreationResult['transports'];
|
|
956
|
+
type Message = 'email' | 'sms';
|
|
940
957
|
interface LoginIDConfig {
|
|
941
958
|
baseUrl: string;
|
|
942
959
|
appId: string;
|
|
@@ -966,43 +983,39 @@ interface ConfirmTransactionOptions extends PasskeyOptions {
|
|
|
966
983
|
txType?: string;
|
|
967
984
|
nonce?: string;
|
|
968
985
|
}
|
|
986
|
+
interface SendCodeOptions {
|
|
987
|
+
usernameType?: UsernameType;
|
|
988
|
+
}
|
|
969
989
|
interface PasskeyResult {
|
|
970
990
|
jwtAccess: string;
|
|
991
|
+
deviceID?: string;
|
|
971
992
|
}
|
|
972
993
|
interface LoginIDUser {
|
|
973
994
|
username: string;
|
|
974
995
|
id: string;
|
|
975
996
|
}
|
|
976
997
|
|
|
977
|
-
|
|
978
|
-
* Provides a base class for integrating with the LoginID API services.
|
|
979
|
-
* This class initializes the common configuration and service needed for derived classes to interact with LoginID services.
|
|
980
|
-
*/
|
|
981
|
-
declare class LoginIDBase {
|
|
998
|
+
declare class SessionManager {
|
|
982
999
|
/**
|
|
983
1000
|
* Holds the configuration settings for the LoginID integration, including API base URL.
|
|
984
1001
|
*/
|
|
985
|
-
|
|
1002
|
+
private config;
|
|
986
1003
|
/**
|
|
987
|
-
*
|
|
1004
|
+
* Initializes a new instance of SessionManager with the provided configuration.
|
|
1005
|
+
* @param {LoginIDConfig} config Configuration object for LoginID.
|
|
988
1006
|
*/
|
|
989
|
-
|
|
1007
|
+
constructor(config: LoginIDConfig);
|
|
990
1008
|
/**
|
|
991
|
-
*
|
|
992
|
-
*
|
|
1009
|
+
* Retrieves the authentication token from the provided options or from cookies if not available in options.
|
|
1010
|
+
* @param {PasskeyOptions} options Options containing the token.
|
|
1011
|
+
* @returns {string} The authentication token.
|
|
993
1012
|
*/
|
|
994
|
-
|
|
1013
|
+
getToken(options: PasskeyOptions): string;
|
|
995
1014
|
/**
|
|
996
|
-
*
|
|
997
|
-
* @
|
|
1015
|
+
* Retrieves the currently authenticated user's information.
|
|
1016
|
+
* @returns {LoginIDUser} The currently authenticated user's information, including username and id.
|
|
1017
|
+
* @throws {Error} If the user is not logged in, throws USER_NO_OP_ERROR.
|
|
998
1018
|
*/
|
|
999
|
-
constructor(config: LoginIDConfig);
|
|
1000
|
-
protected getToken(options: PasskeyOptions): string;
|
|
1001
|
-
/**
|
|
1002
|
-
* Retrieves the currently authenticated user's information.
|
|
1003
|
-
* @returns {LoginIDUser} The currently authenticated user's information, including username and id.
|
|
1004
|
-
* @throws {Error} If the user is not logged in, throws USER_NO_OP_ERROR.
|
|
1005
|
-
*/
|
|
1006
1019
|
getUser(): LoginIDUser;
|
|
1007
1020
|
/**
|
|
1008
1021
|
*
|
|
@@ -1010,7 +1023,7 @@ declare class LoginIDBase {
|
|
|
1010
1023
|
*/
|
|
1011
1024
|
getJwtCookieName(): string;
|
|
1012
1025
|
/**
|
|
1013
|
-
* Set jwt token to
|
|
1026
|
+
* Set jwt token to local Cookie
|
|
1014
1027
|
* @param {string} jwt Configuration object for LoginID API, including the base URL.
|
|
1015
1028
|
*/
|
|
1016
1029
|
setJwtCookie(jwt: string): void;
|
|
@@ -1031,10 +1044,95 @@ declare class LoginIDBase {
|
|
|
1031
1044
|
signout(): void;
|
|
1032
1045
|
}
|
|
1033
1046
|
|
|
1047
|
+
declare class LoginIDConfigValidator {
|
|
1048
|
+
/**
|
|
1049
|
+
* Holds the configuration settings for the LoginID integration, including API base URL and optional app ID.
|
|
1050
|
+
*/
|
|
1051
|
+
private readonly config;
|
|
1052
|
+
/**
|
|
1053
|
+
* Constructs a new instance of the LoginIDConfigValidator class, initializing with the provided configuration.
|
|
1054
|
+
* @param {LoginIDConfig} config Configuration object for LoginID API, including the base URL and optional app ID.
|
|
1055
|
+
*/
|
|
1056
|
+
constructor(config: LoginIDConfig);
|
|
1057
|
+
/**
|
|
1058
|
+
* Retrieves the application ID from the configuration or extracts it from the base URL if not provided.
|
|
1059
|
+
* @returns {string} The application ID.
|
|
1060
|
+
* @throws {Error} If the app ID is not found in the configuration or the base URL, throws an error.
|
|
1061
|
+
*/
|
|
1062
|
+
getAppId(): string;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
/**
|
|
1066
|
+
* Provides a base class for integrating with the LoginID API services.
|
|
1067
|
+
* This class initializes the common configuration and service needed for derived classes to interact with LoginID services.
|
|
1068
|
+
*/
|
|
1069
|
+
declare class LoginIDBase {
|
|
1070
|
+
/**
|
|
1071
|
+
* Holds the configuration settings for the LoginID integration, including API base URL.
|
|
1072
|
+
*/
|
|
1073
|
+
protected readonly config: LoginIDConfigValidator;
|
|
1074
|
+
/**
|
|
1075
|
+
* Instance of LoginIDService, providing access to the LoginID API methods.
|
|
1076
|
+
*/
|
|
1077
|
+
protected readonly service: LoginIDService;
|
|
1078
|
+
/**
|
|
1079
|
+
* Instance of SessionManager, providing access to the session management methods.
|
|
1080
|
+
*/
|
|
1081
|
+
readonly session: SessionManager;
|
|
1082
|
+
/**
|
|
1083
|
+
* Constructs a new instance of the LoginIDBase class, initializing the service with the provided configuration.
|
|
1084
|
+
* @param {LoginIDConfig} config Configuration object for LoginID API, including the base URL.
|
|
1085
|
+
*/
|
|
1086
|
+
constructor(config: LoginIDConfig);
|
|
1087
|
+
/**
|
|
1088
|
+
* Retrieves the currently authenticated user's information.
|
|
1089
|
+
* @returns {LoginIDUser} The currently authenticated user's information, including username and id.
|
|
1090
|
+
* @throws {Error} If the user is not logged in, throws USER_NO_OP_ERROR.
|
|
1091
|
+
*/
|
|
1092
|
+
getUser(): LoginIDUser;
|
|
1093
|
+
/**
|
|
1094
|
+
* checks if the user is logged in.
|
|
1095
|
+
* @returns {boolean}
|
|
1096
|
+
*/
|
|
1097
|
+
isLoggedIn(): boolean;
|
|
1098
|
+
/**
|
|
1099
|
+
* deletes the jwt cookie.
|
|
1100
|
+
* @returns {boolean}
|
|
1101
|
+
*/
|
|
1102
|
+
signout(): void;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/**
|
|
1106
|
+
* Extends LoginIDBase to support OTP codes.
|
|
1107
|
+
*/
|
|
1108
|
+
declare class Code extends LoginIDBase {
|
|
1109
|
+
/**
|
|
1110
|
+
* Initializes a new instance of Code with the provided configuration.
|
|
1111
|
+
* @param {LoginIDConfig} config Configuration object for LoginID.
|
|
1112
|
+
*/
|
|
1113
|
+
constructor(config: LoginIDConfig);
|
|
1114
|
+
/**
|
|
1115
|
+
* Authenticate with a code.
|
|
1116
|
+
* @param {string} username Username to authenticate.
|
|
1117
|
+
* @param {string} code code to authenticate.
|
|
1118
|
+
* @param {AuthenticateWithPasskeysOptions} options Additional authentication options.
|
|
1119
|
+
* @returns {Promise<PasskeyResult>} Result of the authentication operation.
|
|
1120
|
+
*/
|
|
1121
|
+
authenticateWithCode(username: string, code: string, options?: AuthenticateWithPasskeysOptions): Promise<PasskeyResult>;
|
|
1122
|
+
/**
|
|
1123
|
+
* Send a code to the user via the specified method.
|
|
1124
|
+
* @param {string} username Username to send the code to.
|
|
1125
|
+
* @param {Message} method Method to send the code, either 'email' or 'sms'. Default is 'email'.
|
|
1126
|
+
* @param {SendCodeOptions} options Additional options for sending the code.
|
|
1127
|
+
* @returns {Promise<null>} A promise that resolves to null upon successful completion.
|
|
1128
|
+
*/
|
|
1129
|
+
sendCode(username: string, method?: Message, options?: SendCodeOptions): Promise<null>;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1034
1132
|
/**
|
|
1035
1133
|
* Extends LoginIDBase to support creation, registration, and authentication of passkeys.
|
|
1036
1134
|
*/
|
|
1037
|
-
declare class Passkeys extends
|
|
1135
|
+
declare class Passkeys extends Code {
|
|
1038
1136
|
/**
|
|
1039
1137
|
* Initializes a new Passkeys instance with the provided configuration.
|
|
1040
1138
|
* @param {LoginIDConfig} config Configuration object for LoginID.
|
|
@@ -1068,7 +1166,7 @@ declare class Passkeys extends LoginIDBase {
|
|
|
1068
1166
|
*/
|
|
1069
1167
|
authenticateWithPasskey(username?: string, options?: AuthenticateWithPasskeysOptions): Promise<PasskeyResult>;
|
|
1070
1168
|
/**
|
|
1071
|
-
* Authenticates a user with
|
|
1169
|
+
* Authenticates a user with conditional UI (passkey autofill).
|
|
1072
1170
|
* @param {AuthenticateWithPasskeysOptions} options Additional authentication options.
|
|
1073
1171
|
* @returns {Promise<any>} Result of the authentication operation.
|
|
1074
1172
|
*/
|
|
@@ -1080,14 +1178,6 @@ declare class Passkeys extends LoginIDBase {
|
|
|
1080
1178
|
* @returns {Promise<AuthCode>} Code and expiry.
|
|
1081
1179
|
*/
|
|
1082
1180
|
generateCodeWithPasskey(username: string, options?: AuthenticateWithPasskeysOptions): Promise<AuthCode>;
|
|
1083
|
-
/**
|
|
1084
|
-
* Authenticate with a code.
|
|
1085
|
-
* @param {string} username Username to authenticate.
|
|
1086
|
-
* @param {string} code code to authenticate.
|
|
1087
|
-
* @param {AuthenticateWithPasskeysOptions} options Additional authentication options.
|
|
1088
|
-
* @returns {Promise<any>} Result of the authentication operation.
|
|
1089
|
-
*/
|
|
1090
|
-
authenticateWithCode(username: string, code: string, options?: AuthenticateWithPasskeysOptions): Promise<JWT>;
|
|
1091
1181
|
/**
|
|
1092
1182
|
* Add passkey
|
|
1093
1183
|
* @param username Username to authenticate.
|
|
@@ -1154,7 +1244,7 @@ declare class PasskeyManager extends LoginIDBase {
|
|
|
1154
1244
|
deletePasskey(id: string, options?: DeletePasskeyOptions): Promise<null>;
|
|
1155
1245
|
}
|
|
1156
1246
|
|
|
1157
|
-
interface LoginIDWebSDK extends Passkeys, PasskeyManager {
|
|
1247
|
+
interface LoginIDWebSDK extends Passkeys, Code, PasskeyManager {
|
|
1158
1248
|
}
|
|
1159
1249
|
declare class LoginIDWebSDK extends LoginIDBase {
|
|
1160
1250
|
constructor(config: LoginIDConfig);
|
|
@@ -1226,4 +1316,4 @@ interface DoesDeviceSupportPasskeysResponse {
|
|
|
1226
1316
|
*/
|
|
1227
1317
|
declare function doesDeviceSupportPasskeys(): Promise<DoesDeviceSupportPasskeysResponse>;
|
|
1228
1318
|
|
|
1229
|
-
export { 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
|
|
1319
|
+
export { 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 Version, VersionService, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
|
package/dist/index.d.ts
CHANGED
|
@@ -128,7 +128,7 @@ type PubKeyCredentialDescriptor = {
|
|
|
128
128
|
* Base64 encoded byte array of the public key identifier.
|
|
129
129
|
*/
|
|
130
130
|
id: string;
|
|
131
|
-
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid'>;
|
|
131
|
+
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid' | 'cable' | 'smart-card'>;
|
|
132
132
|
type: 'public-key';
|
|
133
133
|
};
|
|
134
134
|
|
|
@@ -175,11 +175,28 @@ type PublicKeyCredentialRequestOptions = {
|
|
|
175
175
|
};
|
|
176
176
|
|
|
177
177
|
type AuthInit = {
|
|
178
|
+
/**
|
|
179
|
+
* An action to be performed by the front-end to complete the authentication flow.
|
|
180
|
+
*/
|
|
181
|
+
action: 'proceed' | 'affirm' | 'fallback';
|
|
182
|
+
/**
|
|
183
|
+
* List of cross authentication methods in the order of preference
|
|
184
|
+
*/
|
|
185
|
+
affirmMethods: Array<'otp' | 'otp:sms' | 'otp:email'>;
|
|
178
186
|
assertionOptions: PublicKeyCredentialRequestOptions;
|
|
179
187
|
/**
|
|
180
|
-
*
|
|
188
|
+
* The list contains available fallback methods in the order of preference. The
|
|
189
|
+
* list is dynamic and shall not be cached. The default fallback mechanism is
|
|
190
|
+
* the one provided by CIAM but our system may provide additional ones as well.
|
|
191
|
+
* These methods may be enabled by customer via application configuration but
|
|
192
|
+
* they are disabled by default. The list may be empty which means no fallback
|
|
193
|
+
* is available and authentication flow shall terminate at this point.
|
|
181
194
|
*/
|
|
182
|
-
|
|
195
|
+
fallbackMethods: Array<'ciam'>;
|
|
196
|
+
/**
|
|
197
|
+
* Type of passkey supported by the client.
|
|
198
|
+
*/
|
|
199
|
+
passkeyType?: string;
|
|
183
200
|
/**
|
|
184
201
|
* An opaque object containing session data.
|
|
185
202
|
*/
|
|
@@ -251,19 +268,11 @@ type AuthInitRequestBody = {
|
|
|
251
268
|
user?: UserLogin;
|
|
252
269
|
};
|
|
253
270
|
|
|
254
|
-
type
|
|
255
|
-
/**
|
|
256
|
-
* Generated code
|
|
257
|
-
*/
|
|
258
|
-
code: string;
|
|
271
|
+
type JWT = {
|
|
259
272
|
/**
|
|
260
|
-
*
|
|
273
|
+
* Device ID
|
|
261
274
|
*/
|
|
262
|
-
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
type JWT = {
|
|
266
|
-
code?: CodeResult;
|
|
275
|
+
deviceID?: string;
|
|
267
276
|
/**
|
|
268
277
|
* JWT access token
|
|
269
278
|
*/
|
|
@@ -599,7 +608,7 @@ type CreationResult = {
|
|
|
599
608
|
* These values are the transports that the authenticator is believed to support,
|
|
600
609
|
* or an empty sequence if the information is unavailable.
|
|
601
610
|
*/
|
|
602
|
-
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid'>;
|
|
611
|
+
transports?: Array<'usb' | 'nfc' | 'ble' | 'internal' | 'hybrid' | 'cable' | 'smart-card'>;
|
|
603
612
|
};
|
|
604
613
|
|
|
605
614
|
type RegCompleteRequestBody = {
|
|
@@ -706,6 +715,10 @@ type PublicKeyCredentialCreationOptions = {
|
|
|
706
715
|
};
|
|
707
716
|
|
|
708
717
|
type RegInit = {
|
|
718
|
+
/**
|
|
719
|
+
* An action to be performed by the front-end to complete the registration flow.
|
|
720
|
+
*/
|
|
721
|
+
action: 'proceed' | 'signIn' | 'fail';
|
|
709
722
|
registrationRequestOptions: PublicKeyCredentialCreationOptions;
|
|
710
723
|
/**
|
|
711
724
|
* An opaque object containing session data.
|
|
@@ -934,9 +947,13 @@ type BadRequestError = {
|
|
|
934
947
|
msgCode: string;
|
|
935
948
|
};
|
|
936
949
|
|
|
950
|
+
type Complete<T> = {
|
|
951
|
+
[P in keyof T]-?: T[P];
|
|
952
|
+
};
|
|
937
953
|
type UsernameType = User['usernameType'];
|
|
938
954
|
type DeviceInfoRequestBody = DeviceInfo;
|
|
939
955
|
type Transports = CreationResult['transports'];
|
|
956
|
+
type Message = 'email' | 'sms';
|
|
940
957
|
interface LoginIDConfig {
|
|
941
958
|
baseUrl: string;
|
|
942
959
|
appId: string;
|
|
@@ -966,43 +983,39 @@ interface ConfirmTransactionOptions extends PasskeyOptions {
|
|
|
966
983
|
txType?: string;
|
|
967
984
|
nonce?: string;
|
|
968
985
|
}
|
|
986
|
+
interface SendCodeOptions {
|
|
987
|
+
usernameType?: UsernameType;
|
|
988
|
+
}
|
|
969
989
|
interface PasskeyResult {
|
|
970
990
|
jwtAccess: string;
|
|
991
|
+
deviceID?: string;
|
|
971
992
|
}
|
|
972
993
|
interface LoginIDUser {
|
|
973
994
|
username: string;
|
|
974
995
|
id: string;
|
|
975
996
|
}
|
|
976
997
|
|
|
977
|
-
|
|
978
|
-
* Provides a base class for integrating with the LoginID API services.
|
|
979
|
-
* This class initializes the common configuration and service needed for derived classes to interact with LoginID services.
|
|
980
|
-
*/
|
|
981
|
-
declare class LoginIDBase {
|
|
998
|
+
declare class SessionManager {
|
|
982
999
|
/**
|
|
983
1000
|
* Holds the configuration settings for the LoginID integration, including API base URL.
|
|
984
1001
|
*/
|
|
985
|
-
|
|
1002
|
+
private config;
|
|
986
1003
|
/**
|
|
987
|
-
*
|
|
1004
|
+
* Initializes a new instance of SessionManager with the provided configuration.
|
|
1005
|
+
* @param {LoginIDConfig} config Configuration object for LoginID.
|
|
988
1006
|
*/
|
|
989
|
-
|
|
1007
|
+
constructor(config: LoginIDConfig);
|
|
990
1008
|
/**
|
|
991
|
-
*
|
|
992
|
-
*
|
|
1009
|
+
* Retrieves the authentication token from the provided options or from cookies if not available in options.
|
|
1010
|
+
* @param {PasskeyOptions} options Options containing the token.
|
|
1011
|
+
* @returns {string} The authentication token.
|
|
993
1012
|
*/
|
|
994
|
-
|
|
1013
|
+
getToken(options: PasskeyOptions): string;
|
|
995
1014
|
/**
|
|
996
|
-
*
|
|
997
|
-
* @
|
|
1015
|
+
* Retrieves the currently authenticated user's information.
|
|
1016
|
+
* @returns {LoginIDUser} The currently authenticated user's information, including username and id.
|
|
1017
|
+
* @throws {Error} If the user is not logged in, throws USER_NO_OP_ERROR.
|
|
998
1018
|
*/
|
|
999
|
-
constructor(config: LoginIDConfig);
|
|
1000
|
-
protected getToken(options: PasskeyOptions): string;
|
|
1001
|
-
/**
|
|
1002
|
-
* Retrieves the currently authenticated user's information.
|
|
1003
|
-
* @returns {LoginIDUser} The currently authenticated user's information, including username and id.
|
|
1004
|
-
* @throws {Error} If the user is not logged in, throws USER_NO_OP_ERROR.
|
|
1005
|
-
*/
|
|
1006
1019
|
getUser(): LoginIDUser;
|
|
1007
1020
|
/**
|
|
1008
1021
|
*
|
|
@@ -1010,7 +1023,7 @@ declare class LoginIDBase {
|
|
|
1010
1023
|
*/
|
|
1011
1024
|
getJwtCookieName(): string;
|
|
1012
1025
|
/**
|
|
1013
|
-
* Set jwt token to
|
|
1026
|
+
* Set jwt token to local Cookie
|
|
1014
1027
|
* @param {string} jwt Configuration object for LoginID API, including the base URL.
|
|
1015
1028
|
*/
|
|
1016
1029
|
setJwtCookie(jwt: string): void;
|
|
@@ -1031,10 +1044,95 @@ declare class LoginIDBase {
|
|
|
1031
1044
|
signout(): void;
|
|
1032
1045
|
}
|
|
1033
1046
|
|
|
1047
|
+
declare class LoginIDConfigValidator {
|
|
1048
|
+
/**
|
|
1049
|
+
* Holds the configuration settings for the LoginID integration, including API base URL and optional app ID.
|
|
1050
|
+
*/
|
|
1051
|
+
private readonly config;
|
|
1052
|
+
/**
|
|
1053
|
+
* Constructs a new instance of the LoginIDConfigValidator class, initializing with the provided configuration.
|
|
1054
|
+
* @param {LoginIDConfig} config Configuration object for LoginID API, including the base URL and optional app ID.
|
|
1055
|
+
*/
|
|
1056
|
+
constructor(config: LoginIDConfig);
|
|
1057
|
+
/**
|
|
1058
|
+
* Retrieves the application ID from the configuration or extracts it from the base URL if not provided.
|
|
1059
|
+
* @returns {string} The application ID.
|
|
1060
|
+
* @throws {Error} If the app ID is not found in the configuration or the base URL, throws an error.
|
|
1061
|
+
*/
|
|
1062
|
+
getAppId(): string;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
/**
|
|
1066
|
+
* Provides a base class for integrating with the LoginID API services.
|
|
1067
|
+
* This class initializes the common configuration and service needed for derived classes to interact with LoginID services.
|
|
1068
|
+
*/
|
|
1069
|
+
declare class LoginIDBase {
|
|
1070
|
+
/**
|
|
1071
|
+
* Holds the configuration settings for the LoginID integration, including API base URL.
|
|
1072
|
+
*/
|
|
1073
|
+
protected readonly config: LoginIDConfigValidator;
|
|
1074
|
+
/**
|
|
1075
|
+
* Instance of LoginIDService, providing access to the LoginID API methods.
|
|
1076
|
+
*/
|
|
1077
|
+
protected readonly service: LoginIDService;
|
|
1078
|
+
/**
|
|
1079
|
+
* Instance of SessionManager, providing access to the session management methods.
|
|
1080
|
+
*/
|
|
1081
|
+
readonly session: SessionManager;
|
|
1082
|
+
/**
|
|
1083
|
+
* Constructs a new instance of the LoginIDBase class, initializing the service with the provided configuration.
|
|
1084
|
+
* @param {LoginIDConfig} config Configuration object for LoginID API, including the base URL.
|
|
1085
|
+
*/
|
|
1086
|
+
constructor(config: LoginIDConfig);
|
|
1087
|
+
/**
|
|
1088
|
+
* Retrieves the currently authenticated user's information.
|
|
1089
|
+
* @returns {LoginIDUser} The currently authenticated user's information, including username and id.
|
|
1090
|
+
* @throws {Error} If the user is not logged in, throws USER_NO_OP_ERROR.
|
|
1091
|
+
*/
|
|
1092
|
+
getUser(): LoginIDUser;
|
|
1093
|
+
/**
|
|
1094
|
+
* checks if the user is logged in.
|
|
1095
|
+
* @returns {boolean}
|
|
1096
|
+
*/
|
|
1097
|
+
isLoggedIn(): boolean;
|
|
1098
|
+
/**
|
|
1099
|
+
* deletes the jwt cookie.
|
|
1100
|
+
* @returns {boolean}
|
|
1101
|
+
*/
|
|
1102
|
+
signout(): void;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/**
|
|
1106
|
+
* Extends LoginIDBase to support OTP codes.
|
|
1107
|
+
*/
|
|
1108
|
+
declare class Code extends LoginIDBase {
|
|
1109
|
+
/**
|
|
1110
|
+
* Initializes a new instance of Code with the provided configuration.
|
|
1111
|
+
* @param {LoginIDConfig} config Configuration object for LoginID.
|
|
1112
|
+
*/
|
|
1113
|
+
constructor(config: LoginIDConfig);
|
|
1114
|
+
/**
|
|
1115
|
+
* Authenticate with a code.
|
|
1116
|
+
* @param {string} username Username to authenticate.
|
|
1117
|
+
* @param {string} code code to authenticate.
|
|
1118
|
+
* @param {AuthenticateWithPasskeysOptions} options Additional authentication options.
|
|
1119
|
+
* @returns {Promise<PasskeyResult>} Result of the authentication operation.
|
|
1120
|
+
*/
|
|
1121
|
+
authenticateWithCode(username: string, code: string, options?: AuthenticateWithPasskeysOptions): Promise<PasskeyResult>;
|
|
1122
|
+
/**
|
|
1123
|
+
* Send a code to the user via the specified method.
|
|
1124
|
+
* @param {string} username Username to send the code to.
|
|
1125
|
+
* @param {Message} method Method to send the code, either 'email' or 'sms'. Default is 'email'.
|
|
1126
|
+
* @param {SendCodeOptions} options Additional options for sending the code.
|
|
1127
|
+
* @returns {Promise<null>} A promise that resolves to null upon successful completion.
|
|
1128
|
+
*/
|
|
1129
|
+
sendCode(username: string, method?: Message, options?: SendCodeOptions): Promise<null>;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1034
1132
|
/**
|
|
1035
1133
|
* Extends LoginIDBase to support creation, registration, and authentication of passkeys.
|
|
1036
1134
|
*/
|
|
1037
|
-
declare class Passkeys extends
|
|
1135
|
+
declare class Passkeys extends Code {
|
|
1038
1136
|
/**
|
|
1039
1137
|
* Initializes a new Passkeys instance with the provided configuration.
|
|
1040
1138
|
* @param {LoginIDConfig} config Configuration object for LoginID.
|
|
@@ -1068,7 +1166,7 @@ declare class Passkeys extends LoginIDBase {
|
|
|
1068
1166
|
*/
|
|
1069
1167
|
authenticateWithPasskey(username?: string, options?: AuthenticateWithPasskeysOptions): Promise<PasskeyResult>;
|
|
1070
1168
|
/**
|
|
1071
|
-
* Authenticates a user with
|
|
1169
|
+
* Authenticates a user with conditional UI (passkey autofill).
|
|
1072
1170
|
* @param {AuthenticateWithPasskeysOptions} options Additional authentication options.
|
|
1073
1171
|
* @returns {Promise<any>} Result of the authentication operation.
|
|
1074
1172
|
*/
|
|
@@ -1080,14 +1178,6 @@ declare class Passkeys extends LoginIDBase {
|
|
|
1080
1178
|
* @returns {Promise<AuthCode>} Code and expiry.
|
|
1081
1179
|
*/
|
|
1082
1180
|
generateCodeWithPasskey(username: string, options?: AuthenticateWithPasskeysOptions): Promise<AuthCode>;
|
|
1083
|
-
/**
|
|
1084
|
-
* Authenticate with a code.
|
|
1085
|
-
* @param {string} username Username to authenticate.
|
|
1086
|
-
* @param {string} code code to authenticate.
|
|
1087
|
-
* @param {AuthenticateWithPasskeysOptions} options Additional authentication options.
|
|
1088
|
-
* @returns {Promise<any>} Result of the authentication operation.
|
|
1089
|
-
*/
|
|
1090
|
-
authenticateWithCode(username: string, code: string, options?: AuthenticateWithPasskeysOptions): Promise<JWT>;
|
|
1091
1181
|
/**
|
|
1092
1182
|
* Add passkey
|
|
1093
1183
|
* @param username Username to authenticate.
|
|
@@ -1154,7 +1244,7 @@ declare class PasskeyManager extends LoginIDBase {
|
|
|
1154
1244
|
deletePasskey(id: string, options?: DeletePasskeyOptions): Promise<null>;
|
|
1155
1245
|
}
|
|
1156
1246
|
|
|
1157
|
-
interface LoginIDWebSDK extends Passkeys, PasskeyManager {
|
|
1247
|
+
interface LoginIDWebSDK extends Passkeys, Code, PasskeyManager {
|
|
1158
1248
|
}
|
|
1159
1249
|
declare class LoginIDWebSDK extends LoginIDBase {
|
|
1160
1250
|
constructor(config: LoginIDConfig);
|
|
@@ -1226,4 +1316,4 @@ interface DoesDeviceSupportPasskeysResponse {
|
|
|
1226
1316
|
*/
|
|
1227
1317
|
declare function doesDeviceSupportPasskeys(): Promise<DoesDeviceSupportPasskeysResponse>;
|
|
1228
1318
|
|
|
1229
|
-
export { 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
|
|
1319
|
+
export { 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 Version, VersionService, WebAuthnHelper, createPasskeyCredential, LoginIDWebSDK as default, doesDeviceSupportPasskeys, getPasskeyCredential, isConditionalUIAvailable, isPlatformAuthenticatorAvailable };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var f=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 x=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 x("Request aborted"))}}get isCancelled(){return this.#e}};var H=t=>t!=null,g=t=>typeof t=="string",U=t=>g(t)&&t!=="",F=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]),z=t=>t instanceof FormData,ne=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},ie=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{H(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}${ie(e.query)}`:o},ue=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{g(o)||F(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>H(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},v=async(t,e)=>typeof e=="function"?e(t):e,le=async(t,e)=>{let[r,s,o,n]=await Promise.all([v(e,t.TOKEN),v(e,t.USERNAME),v(e,t.PASSWORD),v(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,u])=>H(u)).reduce((a,[u,l])=>({...a,[u]:String(l)}),{});if(U(r)&&(i.Authorization=`Bearer ${r}`),U(s)&&U(o)){let a=ne(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:F(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":g(e.body)?i["Content-Type"]="text/plain":z(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},pe=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):g(t.body)||F(t.body)||z(t.body)?t.body:JSON.stringify(t.body)},de=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)},ce=(t,e)=>{if(e){let r=t.headers.get(e);if(g(r))return r}},ye=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)}},me=(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}`)}},M=(t,e)=>new R(async(r,s,o)=>{try{let n=ae(t,e),i=ue(e),a=pe(e),u=await le(t,e);if(!o.isCancelled){let l=await de(t,e,n,a,i,u,o),m=await ye(l),se=ce(l,e.responseHeader),J={url:n,ok:l.ok,status:l.status,statusText:l.statusText,body:se??m};me(e,J),r(J.body)}}catch(n){s(n)}});var k=class extends f{constructor(e){super(e)}request(e){return M(this.config,e)}};var C=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.",403:"Forbidden: Forbidden 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 b=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 T=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 E=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var B=class{auth;mgmt;passkeys;profile;reg;tx;version;request;constructor(e,r=k){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 C(this.request),this.mgmt=new b(this.request),this.passkeys=new P(this.request),this.profile=new q(this.request),this.reg=new A(this.request),this.tx=new T(this.request),this.version=new E(this.request)}};var K=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=K;var $=(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},G=(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},w=t=>{let e=new Error("Cancelling current WebAuthn request");return e.name="AbortError",t.abort(e),new AbortController},D=new Error("User needs to be logged in to perform this operation.");var he=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),fe=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},Re=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=fe(e);return he(s)},h=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Re(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},Y=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),Q=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})},I=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)}},X=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},Z=t=>{document.cookie=t},ee=t=>{document.cookie=`${t}=; expires=${new Date}`};var L=class{config;service;abortController=new AbortController;constructor(e){this.config=e,this.service=new B({BASE:e.baseUrl})}getToken(e){if(e.token)return e.token;{let r=this.getJwtCookie();return r||""}}getUser(){if(!this.isLoggedIn())throw D;let e=I(this.getJwtCookie()||"{}");return{username:e.username,id:e.sub}}getJwtCookieName(){return`LoginID_${this.config.appId}_token`}setJwtCookie(e){let r=I(e),s=new Date(r.exp*1e3).toUTCString(),o=`${this.getJwtCookieName()}=${e}; expires=${s}`;Z(o)}getJwtCookie(){return X(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){ee(this.getJwtCookieName())}},y=L;import{UAParser as ge}from"ua-parser-js";var _=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),Ce=(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 be(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function Pe(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function qe(){let t=new ge(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"&&Ce(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: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?$(o,s):o}},O=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?G(o,s):o}};var j=class extends y{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;this.abortController=w(this.abortController);let o=await S(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=_();r.usernameType||(r.usernameType="email"),r.token=this.getToken(r),r.token&&I(r.token).username!==e&&(r.token="");let o={app:{id:this.config.appId},deviceInfo:s,user:{username:e,usernameType:r.usernameType,...r.displayName&&{displayName:r.displayName}},...r.session&&{session:r.session}},n=await this.service.reg.regRegInit({requestBody:o,...r.token&&{authorization:r.token}}),i=await this.createNavigatorCredential(n),a=await this.service.reg.regRegComplete({requestBody:i});return this.setJwtCookie(a.jwtAccess),a}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e;r.abortSignal||(this.abortController=w(this.abortController),r.abortSignal=this.abortController.signal);let n=await O(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=_();r.usernameType||(r.usernameType="email");let o={app:{id:this.config.appId,...r.token&&{token:r.token}},deviceInfo:s,user:{username:e,usernameType:r.usernameType,...r.displayName&&{displayName:r.displayName}}},n=await this.service.auth.authAuthInit({requestBody:o}),i=await this.getNavigatorCredential(n,r),a=await this.service.auth.authAuthComplete({requestBody:i});return this.setJwtCookie(a.jwtAccess),a}async enablePasskeyAutofill(e={}){return e.autoFill=!0,await this.authenticateWithPasskey("",e)}async generateCodeWithPasskey(e,r={}){if(r.token=this.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 authenticateWithCode(e,r,s={}){s.usernameType||(s.usernameType="email");let o={authCode:r,user:{username:e,usernameType:s.usernameType}},n=await this.service.auth.authAuthCodeVerify({requestBody:o});return this.abortController=w(this.abortController),this.setJwtCookie(n.jwtAccess),n}async addPasskey(e,r={}){let s=this.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={username:e,txPayload:r,nonce:s.nonce||Y(),txType:s.txType||"raw"},{assertionOptions:n,session:i}=await this.service.tx.txTxInit({requestBody:o}),a={assertionOptions:n,session:i},{assertionResult:u}=await this.getNavigatorCredential(a),l={authenticatorData:u.authenticatorData,clientData:u.clientDataJSON,keyHandle:u.credentialId,session:i,signature:u.signature},m=await this.service.tx.txTxComplete({requestBody:l});return this.setJwtCookie(m.jwtAccess),m}},te=j;var W=class extends y{constructor(e){super(e)}async listPasskeys(e={}){let r=this.getToken(e);return await this.service.passkeys.passkeysPasskeysList({authorization:r})}async renamePasskey(e,r,s={}){let o=this.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.getToken(r);return await this.service.passkeys.passkeysPasskeyDelete({authorization:s,id:e}),null}},re=W;var N=class extends y{constructor(e){super(e)}};Q(N,[y,te,re]);var oe=N;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: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 S(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 Ae={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 $t=oe;export{c as ApiError,C as AuthService,f as BaseHttpRequest,x as CancelError,R as CancelablePromise,B as LoginIDService,oe as LoginIDWebSDK,b as MgmtService,Ae as OpenAPI,d as PasskeyError,P as PasskeysService,q as ProfileService,A as RegService,T as TxService,E as VersionService,V as WebAuthnHelper,S as createPasskeyCredential,$t as default,qe as doesDeviceSupportPasskeys,O as getPasskeyCredential,Pe as isConditionalUIAvailable,be as isPlatformAuthenticatorAvailable};
|
|
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 j=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},d=j;var ee=(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},te=(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 me=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),fe=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},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},l=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=fe(e);return me(s)},f=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},re=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),oe=(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)}},se=t=>{let r=`; ${document.cookie}`.split(`; ${t}=`);if(r&&r.length===2)return r.pop().split(";").shift()},ne=t=>{document.cookie=t},ie=t=>{document.cookie=`${t}=; expires=${new Date}`};var W=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}`;ne(o)}getJwtCookie(){return se(this.getJwtCookieName())}isLoggedIn(){return!!this.getJwtCookie()}signout(){ie(this.getJwtCookieName())}},ae=W;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 V=t=>t!=null,P=t=>typeof t=="string",_=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]),ue=t=>t instanceof FormData,Re=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},ge=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{V(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("&")}`:""},Ce=(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}${ge(e.query)}`:o},be=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])=>V(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,Pe=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])=>V(u)).reduce((a,[u,p])=>({...a,[u]:String(p)}),{});if(_(r)&&(i.Authorization=`Bearer ${r}`),_(s)&&_(o)){let a=Re(`${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":ue(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},qe=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):P(t.body)||J(t.body)||ue(t.body)?t.body:JSON.stringify(t.body)},Ae=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)},Te=(t,e)=>{if(e){let r=t.headers.get(e);if(P(r))return r}},Ie=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)}},Ee=(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}`)}},pe=(t,e)=>new b(async(r,s,o)=>{try{let n=Ce(t,e),i=be(e),a=qe(e),u=await Pe(t,e);if(!o.isCancelled){let p=await Ae(t,e,n,a,i,u,o),R=await Ie(p),v=Te(p,e.responseHeader),Z={url:n,ok:p.ok,status:p.status,statusText:p.statusText,body:v??R};Ee(e,Z),r(Z.body)}}catch(n){s(n)}});var L=class extends C{constructor(e){super(e)}request(e){return pe(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 T=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 I=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 E=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 B=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 S=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 T(this.request),this.profile=new I(this.request),this.reg=new E(this.request),this.tx=new B(this.request),this.version=new O(this.request)}};var M=class{config;service;session;constructor(e){this.config=new w(e),this.service=new S({BASE:e.baseUrl}),this.session=new ae(e)}getUser(){return this.session.getUser()}isLoggedIn(){return this.session.isLoggedIn()}signout(){this.session.signout()}},y=M;var z=class t{static abortController=new AbortController;static renewWebAuthnAbortController=()=>{let e=new Error("Cancelling current WebAuthn request");e.name="AbortError",t.abortController.abort(e);let r=new AbortController;t.abortController=r}},h=z;var m=(t,e)=>({...e,token:e.token||"",usernameType:e.usernameType||"email",displayName:e.displayName||t}),le=(t,e)=>({...m(t,e),txType:e.txType||"raw",nonce:e.nonce||re()});var $=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=$;import{UAParser as Be}from"ua-parser-js";var G=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),Oe=(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 Se(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function xe(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function ke(){let t=new Be(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"&&Oe(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 x=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?ee(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?te(o,s):o}};var Y=class extends H{constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e;h.renewWebAuthnAbortController();let o=await x(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=G(),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=G(),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=le(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}},de=Y;var Q=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}},ce=Q;var F=class extends y{constructor(e){super(e)}};oe(F,[y,de,H,ce]);var ye=F;var X=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 x(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 ve={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 gr=ye;export{c as ApiError,q as AuthService,C as BaseHttpRequest,N as CancelError,b as CancelablePromise,S as LoginIDService,ye as LoginIDWebSDK,A as MgmtService,ve as OpenAPI,d as PasskeyError,T as PasskeysService,I as ProfileService,E as RegService,B as TxService,O as VersionService,X as WebAuthnHelper,x as createPasskeyCredential,gr as default,ke as doesDeviceSupportPasskeys,k as getPasskeyCredential,xe as isConditionalUIAvailable,Se as isPlatformAuthenticatorAvailable};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|