@loginid/websdk3 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var k=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var se=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},ne=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of re(e))!oe.call(t,o)&&o!==r&&k(t,o,{get:()=>e[o],enumerable:!(s=te(e,o))||s.enumerable});return t};var ie=t=>ne(k({},"__esModule",{value:!0}),t);var Ae={};se(Ae,{ApiError:()=>d,LoginIDWebSDK:()=>F,PasskeyError:()=>u,createPasskeyCredential:()=>B,default:()=>Pe,doesDeviceSupportPasskeys:()=>Y,getPasskeyCredential:()=>v,isConditionalUIAvailable:()=>G,isPlatformAuthenticatorAvailable:()=>z});module.exports=ie(Ae);var f=class{constructor(e){this.config=e}};var d=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 I=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 I("Request aborted"))}}get isCancelled(){return this.#e}};var N=t=>t!=null,h=t=>typeof t=="string",D=t=>h(t)&&t!=="",H=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]),V=t=>t instanceof FormData,ae=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},le=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{N(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("&")}`:""},pe=(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}${le(e.query)}`:o},ue=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{h(o)||H(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>N(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},O=async(t,e)=>typeof e=="function"?e(t):e,ce=async(t,e)=>{let[r,s,o,n]=await Promise.all([O(e,t.TOKEN),O(e,t.USERNAME),O(e,t.PASSWORD),O(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,p])=>N(p)).reduce((a,[p,l])=>({...a,[p]:String(l)}),{});if(D(r)&&(i.Authorization=`Bearer ${r}`),D(s)&&D(o)){let a=ae(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:H(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":h(e.body)?i["Content-Type"]="text/plain":V(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):h(t.body)||H(t.body)||V(t.body)?t.body:JSON.stringify(t.body)},ye=async(t,e,r,s,o,n,i)=>{let a=new AbortController,p={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(p.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,p)},me=(t,e)=>{if(e){let r=t.headers.get(e);if(h(r))return r}},fe=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)}},Re=(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 d(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 d(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},M=(t,e)=>new R(async(r,s,o)=>{try{let n=pe(t,e),i=ue(e),a=de(e),p=await ce(t,e);if(!o.isCancelled){let l=await ye(t,e,n,a,i,p,o),E=await fe(l),x=me(l,e.responseHeader),W={url:n,ok:l.ok,status:l.status,statusText:l.statusText,body:x??E};Re(e,W),r(W.body)}}catch(n){s(n)}});var S=class extends f{constructor(e){super(e)}request(e){return M(this.config,e)}};var b=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",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.",500:"InternalServerError: Internal Server Error response."}})}};var g=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.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",headers:{Authorization:r},path:{id:e},errors:{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}",headers:{Authorization:s},path:{id:e},body:r,mediaType:"application/json",errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var C=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}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var P=class{constructor(e){this.httpRequest=e}tokenTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/token/verify",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}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 q=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var T=class{auth;passkeys;reg;token;tx;version;request;constructor(e,r=S){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new b(this.request),this.passkeys=new g(this.request),this.reg=new C(this.request),this.token=new P(this.request),this.tx=new A(this.request),this.version=new q(this.request)}};var U=class{config;service;constructor(e){this.config=e,this.service=new T({BASE:e.baseUrl})}},y=U;var he=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++),p=t.charCodeAt(s++),l=i<<16|a<<8|p;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},ge=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r={},s=String.fromCharCode;for(let a=0;a<64;a++)r[e.charAt(a)]=a;let o=0,n=0,i="";for(let a of t){let p=r[a];if(p!==void 0)for(o=(o<<6)+p,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},c=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=be(e);return he(s)},m=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=ge(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},J=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})};var $=require("ua-parser-js"),K=()=>({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 z(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function G(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function Y(){let t=new $.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"&&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 j=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},u=j;var Q=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new u("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new u("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new u("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new u("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new u("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 u(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new u("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},X=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new u("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new u("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 u(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new u("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t};var B=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:m(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:m(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:m(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?Q(o,s):o}},v=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:m(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:m(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?X(o,s):o}};var L=class extends y{jwtAccess="";constructor(e){super(e)}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(),p=n.getAuthenticatorData&&n.getAuthenticatorData(),l=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:c(n.attestationObject),clientDataJSON:c(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:c(i)},...a&&{publicKeyAlgorithm:a},...p&&{authenticatorData:c(p)},...l&&{transports:l}},session:s}}async registerWithPasskey(e,r={}){let s=K();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}},...r.mfa&&{mfa:r.mfa}},n=await this.service.reg.regRegInit({requestBody:o}),i=await this.createNavigatorCredential(n),a=await this.service.reg.regRegComplete({requestBody:i});return this.jwtAccess=a.jwtAccess,a}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await v(s,r),i=n.response;return{assertionResult:{authenticatorData:c(i.authenticatorData),clientDataJSON:c(i.clientDataJSON),credentialId:n.id,signature:c(i.signature),...i.userHandle&&{userHandle:c(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=K();r.usernameType||(r.usernameType="email");let o={app:{id:this.config.appId,...r.token&&{token:r.token}},deviceInfo:s,...!r.autoFill&&e!==""&&{user:{username:e,usernameType:r.usernameType,...r.displayName&&{displayName:r.displayName}}}},n=await this.service.auth.authAuthInit({requestBody:o});e===""&&(r.autoFill=!0);let i=await this.getNavigatorCredential(n,r),a=await this.service.auth.authAuthComplete({requestBody:i});return this.jwtAccess=a.jwtAccess,a}async confirmTransaction(e,r,s,o={}){let n={username:e,txPayload:r,nonce:s,txType:o.txType||""},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),p={assertionOptions:i,session:a},{assertionResult:l}=await this.getNavigatorCredential(p),E={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:a,signature:l.signature},x=await this.service.tx.txTxComplete({requestBody:E});return this.jwtAccess=x.jwtAccess,x}getJWTAccess(){return this.jwtAccess}},Z=L;var _=class extends y{constructor(e){super(e)}async listPasskeys(e){return await this.service.passkeys.passkeysPasskeysList({authorization:e})}async renamePasskey(e,r,s){let o={name:s};return await this.service.passkeys.passkeysPasskeyRename({authorization:e,id:r,requestBody:o}),null}async deletePasskey(e,r){return await this.service.passkeys.passkeysPasskeyDelete({authorization:e,id:r}),null}},ee=_;var w=class extends y{constructor(e){super(e)}};J(w,[y,Z,ee]);var F=w;var Pe=F;0&&(module.exports={ApiError,LoginIDWebSDK,PasskeyError,createPasskeyCredential,doesDeviceSupportPasskeys,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
1
+ "use strict";var w=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var ne=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})},ie=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of oe(e))!se.call(t,o)&&o!==r&&w(t,o,{get:()=>e[o],enumerable:!(s=re(e,o))||s.enumerable});return t};var ae=t=>ie(w({},"__esModule",{value:!0}),t);var qe={};ne(qe,{ApiError:()=>d,LoginIDWebSDK:()=>_,PasskeyError:()=>l,createPasskeyCredential:()=>S,default:()=>Ae,doesDeviceSupportPasskeys:()=>z,getPasskeyCredential:()=>v,isConditionalUIAvailable:()=>$,isPlatformAuthenticatorAvailable:()=>J});module.exports=ae(qe);var R=class{constructor(e){this.config=e}};var d=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 I=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},h=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 I("Request aborted"))}}get isCancelled(){return this.#e}};var D=t=>t!=null,g=t=>typeof t=="string",k=t=>g(t)&&t!=="",N=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]),W=t=>t instanceof FormData,pe=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},ue=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{D(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("&")}`:""},le=(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}${ue(e.query)}`:o},ce=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{g(o)||N(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>D(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},x=async(t,e)=>typeof e=="function"?e(t):e,de=async(t,e)=>{let[r,s,o,n]=await Promise.all([x(e,t.TOKEN),x(e,t.USERNAME),x(e,t.PASSWORD),x(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,p])=>D(p)).reduce((a,[p,u])=>({...a,[p]:String(u)}),{});if(k(r)&&(i.Authorization=`Bearer ${r}`),k(s)&&k(o)){let a=pe(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:N(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":g(e.body)?i["Content-Type"]="text/plain":W(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},ye=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):g(t.body)||N(t.body)||W(t.body)?t.body:JSON.stringify(t.body)},me=async(t,e,r,s,o,n,i)=>{let a=new AbortController,p={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(p.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,p)},fe=(t,e)=>{if(e){let r=t.headers.get(e);if(g(r))return r}},Re=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 d(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 d(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},V=(t,e)=>new h(async(r,s,o)=>{try{let n=le(t,e),i=ce(e),a=ye(e),p=await de(t,e);if(!o.isCancelled){let u=await me(t,e,n,a,i,p,o),f=await Re(u),te=fe(u,e.responseHeader),F={url:n,ok:u.ok,status:u.status,statusText:u.statusText,body:te??f};he(e,F),r(F.body)}}catch(n){s(n)}});var O=class extends R{constructor(e){super(e)}request(e){return V(this.config,e)}};var b=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",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.",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.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",headers:{Authorization:r},path:{id:e},errors:{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}",headers:{Authorization:s},path:{id:e},body:r,mediaType:"application/json",errors:{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}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}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var A=class{constructor(e){this.httpRequest=e}tokenTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/token/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request 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 T=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var E=class{auth;passkeys;reg;token;tx;version;request;constructor(e,r=O){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new b(this.request),this.passkeys=new C(this.request),this.reg=new P(this.request),this.token=new A(this.request),this.tx=new q(this.request),this.version=new T(this.request)}};var U=class{config;service;constructor(e){this.config=e,this.service=new E({BASE:e.baseUrl})}},y=U;var M=require("ua-parser-js"),H=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),ge=(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 J(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function $(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function z(){let t=new M.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"&&ge(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 be=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Ce=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),p=t.charCodeAt(s++),u=i<<16|a<<8|p;r.push(e[u>>18&63]+e[u>>12&63]+e[u>>6&63]+e[u&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},Pe=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 p=r[a];if(p!==void 0)for(o=(o<<6)+p,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},c=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=Ce(e);return be(s)},m=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=Pe(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},G=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),Y=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})};var K=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},l=K;var Q=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new l("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new l("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new l("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new l("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new l("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 l(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new l("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},X=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new l("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new l("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 l(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new l("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t};var S=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:m(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:m(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:m(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?Q(o,s):o}},v=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:m(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:m(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?X(o,s):o}};var j=class extends y{jwtAccess="";constructor(e){super(e)}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(),p=n.getAuthenticatorData&&n.getAuthenticatorData(),u=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:c(n.attestationObject),clientDataJSON:c(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:c(i)},...a&&{publicKeyAlgorithm:a},...p&&{authenticatorData:c(p)},...u&&{transports:u}},session:s}}async registerWithPasskey(e,r={}){let s=H();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}},...r.mfa&&{mfa:r.mfa},...r.session&&{session:r.session}},n=await this.service.reg.regRegInit({requestBody:o}),i=await this.createNavigatorCredential(n),a=await this.service.reg.regRegComplete({requestBody:i});return this.jwtAccess=a.jwtAccess,a}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await v(s,r),i=n.response;return{assertionResult:{authenticatorData:c(i.authenticatorData),clientDataJSON:c(i.clientDataJSON),credentialId:n.id,signature:c(i.signature),...i.userHandle&&{userHandle:c(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=H();r.usernameType||(r.usernameType="email");let o={app:{id:this.config.appId,...r.token&&{token:r.token}},deviceInfo:s,...!r.autoFill&&{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.jwtAccess=a.jwtAccess,a}async confirmTransaction(e,r,s={}){let o={username:e,txPayload:r,nonce:s.nonce||G(),txType:s.txType||"raw"},{assertionOptions:n,session:i}=await this.service.tx.txTxInit({requestBody:o}),a={assertionOptions:n,session:i},{assertionResult:p}=await this.getNavigatorCredential(a),u={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:i,signature:p.signature},f=await this.service.tx.txTxComplete({requestBody:u});return this.jwtAccess=f.jwtAccess,f}getJWTAccess(){return this.jwtAccess}},Z=j;var L=class extends y{constructor(e){super(e)}async listPasskeys(e){return await this.service.passkeys.passkeysPasskeysList({authorization:e})}async renamePasskey(e,r,s){let o={name:s};return await this.service.passkeys.passkeysPasskeyRename({authorization:e,id:r,requestBody:o}),null}async deletePasskey(e,r){return await this.service.passkeys.passkeysPasskeyDelete({authorization:e,id:r}),null}},ee=L;var B=class extends y{constructor(e){super(e)}};Y(B,[y,Z,ee]);var _=B;var Ae=_;0&&(module.exports={ApiError,LoginIDWebSDK,PasskeyError,createPasskeyCredential,doesDeviceSupportPasskeys,getPasskeyCredential,isConditionalUIAvailable,isPlatformAuthenticatorAvailable});
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -478,7 +478,15 @@ type RegInitRequestBody = {
478
478
  * - Passwordless + MFA: FIDO2 discoverable credentials + PIN;
479
479
  */
480
480
  mfa?: Array<'fido2' | 'email' | 'phone' | 'password' | 'pin'>;
481
- user: User;
481
+ /**
482
+ * An opaque object containing user data. It is used in place of "user" attribute
483
+ * for creating passkeys for pre-authorized users ("user" attribute is ignored if
484
+ * session is present). The value of this attribute is generated by this service
485
+ * and require backend integration for obtaining it. This value is time sensitive
486
+ * and has rather short expiry.
487
+ */
488
+ session?: string;
489
+ user?: User;
482
490
  };
483
491
 
484
492
  declare class RegService {
@@ -702,8 +710,11 @@ interface AuthenticateWithPasskeysOptions extends PasskeyOptions {
702
710
  }
703
711
  interface RegisterWithPasskeyOptions extends PasskeyOptions {
704
712
  mfa?: MFA;
713
+ session?: string;
705
714
  }
706
- interface ConfirmTransactionOptions extends Partial<Pick<TxInitRequestBody, 'txType'>> {
715
+ interface ConfirmTransactionOptions extends PasskeyOptions {
716
+ txType?: string;
717
+ nonce?: string;
707
718
  }
708
719
  interface PasskeyResult {
709
720
  jwtAccess: string;
@@ -782,7 +793,7 @@ declare class Passkeys extends LoginIDBase {
782
793
  * @returns {Promise<any>} A promise that resolves with the result of the transaction confirmation operation.
783
794
  * The result includes details about the transaction's details and includes a new JWT access token.
784
795
  */
785
- confirmTransaction(username: string, txPayload: string, nonce: string, options?: ConfirmTransactionOptions): Promise<TxComplete>;
796
+ confirmTransaction(username: string, txPayload: string, options?: ConfirmTransactionOptions): Promise<TxComplete>;
786
797
  /**
787
798
  * Retrieves the JWT access token.
788
799
  * @returns {string} The JWT access token.
package/dist/index.d.ts CHANGED
@@ -478,7 +478,15 @@ type RegInitRequestBody = {
478
478
  * - Passwordless + MFA: FIDO2 discoverable credentials + PIN;
479
479
  */
480
480
  mfa?: Array<'fido2' | 'email' | 'phone' | 'password' | 'pin'>;
481
- user: User;
481
+ /**
482
+ * An opaque object containing user data. It is used in place of "user" attribute
483
+ * for creating passkeys for pre-authorized users ("user" attribute is ignored if
484
+ * session is present). The value of this attribute is generated by this service
485
+ * and require backend integration for obtaining it. This value is time sensitive
486
+ * and has rather short expiry.
487
+ */
488
+ session?: string;
489
+ user?: User;
482
490
  };
483
491
 
484
492
  declare class RegService {
@@ -702,8 +710,11 @@ interface AuthenticateWithPasskeysOptions extends PasskeyOptions {
702
710
  }
703
711
  interface RegisterWithPasskeyOptions extends PasskeyOptions {
704
712
  mfa?: MFA;
713
+ session?: string;
705
714
  }
706
- interface ConfirmTransactionOptions extends Partial<Pick<TxInitRequestBody, 'txType'>> {
715
+ interface ConfirmTransactionOptions extends PasskeyOptions {
716
+ txType?: string;
717
+ nonce?: string;
707
718
  }
708
719
  interface PasskeyResult {
709
720
  jwtAccess: string;
@@ -782,7 +793,7 @@ declare class Passkeys extends LoginIDBase {
782
793
  * @returns {Promise<any>} A promise that resolves with the result of the transaction confirmation operation.
783
794
  * The result includes details about the transaction's details and includes a new JWT access token.
784
795
  */
785
- confirmTransaction(username: string, txPayload: string, nonce: string, options?: ConfirmTransactionOptions): Promise<TxComplete>;
796
+ confirmTransaction(username: string, txPayload: string, options?: ConfirmTransactionOptions): Promise<TxComplete>;
786
797
  /**
787
798
  * Retrieves the JWT access token.
788
799
  * @returns {string} The JWT access token.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var f=class{constructor(e){this.config=e}};var d=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 I=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 I("Request aborted"))}}get isCancelled(){return this.#e}};var w=t=>t!=null,h=t=>typeof t=="string",v=t=>h(t)&&t!=="",k=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]),F=t=>t instanceof FormData,Y=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},Q=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{w(n)&&(Array.isArray(n)?n.forEach(i=>{s(o,i)}):typeof n=="object"?Object.entries(n).forEach(([i,a])=>{s(`${o}[${i}]`,a)}):r(o,n))};return Object.entries(t).forEach(([o,n])=>{s(o,n)}),e.length>0?`?${e.join("&")}`:""},X=(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}${Q(e.query)}`:o},Z=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{h(o)||k(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>w(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},O=async(t,e)=>typeof e=="function"?e(t):e,ee=async(t,e)=>{let[r,s,o,n]=await Promise.all([O(e,t.TOKEN),O(e,t.USERNAME),O(e,t.PASSWORD),O(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,p])=>w(p)).reduce((a,[p,l])=>({...a,[p]:String(l)}),{});if(v(r)&&(i.Authorization=`Bearer ${r}`),v(s)&&v(o)){let a=Y(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:k(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":h(e.body)?i["Content-Type"]="text/plain":F(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},te=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):h(t.body)||k(t.body)||F(t.body)?t.body:JSON.stringify(t.body)},re=async(t,e,r,s,o,n,i)=>{let a=new AbortController,p={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(p.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,p)},oe=(t,e)=>{if(e){let r=t.headers.get(e);if(h(r))return r}},se=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)}},ne=(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 d(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 d(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},W=(t,e)=>new R(async(r,s,o)=>{try{let n=X(t,e),i=Z(e),a=te(e),p=await ee(t,e);if(!o.isCancelled){let l=await re(t,e,n,a,i,p,o),E=await se(l),x=oe(l,e.responseHeader),_={url:n,ok:l.ok,status:l.status,statusText:l.statusText,body:x??E};ne(e,_),r(_.body)}}catch(n){s(n)}});var S=class extends f{constructor(e){super(e)}request(e){return W(this.config,e)}};var b=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",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.",500:"InternalServerError: Internal Server Error response."}})}};var g=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.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",headers:{Authorization:r},path:{id:e},errors:{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}",headers:{Authorization:s},path:{id:e},body:r,mediaType:"application/json",errors:{401:"Unauthorized: Unauthorized response.",403:"Forbidden: Forbidden response.",404:"NotFound: Not Found response.",500:"InternalServerError: Internal Server Error response."}})}};var C=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}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var P=class{constructor(e){this.httpRequest=e}tokenTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/token/verify",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}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 q=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var T=class{auth;passkeys;reg;token;tx;version;request;constructor(e,r=S){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new b(this.request),this.passkeys=new g(this.request),this.reg=new C(this.request),this.token=new P(this.request),this.tx=new A(this.request),this.version=new q(this.request)}};var D=class{config;service;constructor(e){this.config=e,this.service=new T({BASE:e.baseUrl})}},y=D;var ie=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),ae=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),p=t.charCodeAt(s++),l=i<<16|a<<8|p;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},le=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 p=r[a];if(p!==void 0)for(o=(o<<6)+p,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},c=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=ae(e);return ie(s)},m=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=le(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},V=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})};import{UAParser as pe}from"ua-parser-js";var N=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),ue=(t,e)=>{let r=t.split(".").map(Number),s=e.split(".").map(Number),o=Math.max(r.length,s.length);for(let n=0;n<o;n++){let i=n<r.length?r[n]:0,a=n<s.length?s[n]:0;if(i<a)return-1;if(i>a)return 1}return 0};async function ce(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function de(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function ye(){let t=new pe(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"&&ue(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 H=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},u=H;var M=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new u("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new u("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new u("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new u("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new u("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 u(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new u("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},J=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new u("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new u("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 u(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new u("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t};var U=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:m(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:m(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:m(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?M(o,s):o}},K=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:m(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:m(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?J(o,s):o}};var j=class extends y{jwtAccess="";constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await U(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),p=n.getAuthenticatorData&&n.getAuthenticatorData(),l=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:c(n.attestationObject),clientDataJSON:c(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:c(i)},...a&&{publicKeyAlgorithm:a},...p&&{authenticatorData:c(p)},...l&&{transports:l}},session:s}}async registerWithPasskey(e,r={}){let s=N();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}},...r.mfa&&{mfa:r.mfa}},n=await this.service.reg.regRegInit({requestBody:o}),i=await this.createNavigatorCredential(n),a=await this.service.reg.regRegComplete({requestBody:i});return this.jwtAccess=a.jwtAccess,a}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await K(s,r),i=n.response;return{assertionResult:{authenticatorData:c(i.authenticatorData),clientDataJSON:c(i.clientDataJSON),credentialId:n.id,signature:c(i.signature),...i.userHandle&&{userHandle:c(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=N();r.usernameType||(r.usernameType="email");let o={app:{id:this.config.appId,...r.token&&{token:r.token}},deviceInfo:s,...!r.autoFill&&e!==""&&{user:{username:e,usernameType:r.usernameType,...r.displayName&&{displayName:r.displayName}}}},n=await this.service.auth.authAuthInit({requestBody:o});e===""&&(r.autoFill=!0);let i=await this.getNavigatorCredential(n,r),a=await this.service.auth.authAuthComplete({requestBody:i});return this.jwtAccess=a.jwtAccess,a}async confirmTransaction(e,r,s,o={}){let n={username:e,txPayload:r,nonce:s,txType:o.txType||""},{assertionOptions:i,session:a}=await this.service.tx.txTxInit({requestBody:n}),p={assertionOptions:i,session:a},{assertionResult:l}=await this.getNavigatorCredential(p),E={authenticatorData:l.authenticatorData,clientData:l.clientDataJSON,keyHandle:l.credentialId,session:a,signature:l.signature},x=await this.service.tx.txTxComplete({requestBody:E});return this.jwtAccess=x.jwtAccess,x}getJWTAccess(){return this.jwtAccess}},$=j;var L=class extends y{constructor(e){super(e)}async listPasskeys(e){return await this.service.passkeys.passkeysPasskeysList({authorization:e})}async renamePasskey(e,r,s){let o={name:s};return await this.service.passkeys.passkeysPasskeyRename({authorization:e,id:r,requestBody:o}),null}async deletePasskey(e,r){return await this.service.passkeys.passkeysPasskeyDelete({authorization:e,id:r}),null}},z=L;var B=class extends y{constructor(e){super(e)}};V(B,[y,$,z]);var G=B;var vt=G;export{d as ApiError,G as LoginIDWebSDK,u as PasskeyError,U as createPasskeyCredential,vt as default,ye as doesDeviceSupportPasskeys,K as getPasskeyCredential,de as isConditionalUIAvailable,ce as isPlatformAuthenticatorAvailable};
1
+ var R=class{constructor(e){this.config=e}};var d=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 I=class extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}},h=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 I("Request aborted"))}}get isCancelled(){return this.#e}};var B=t=>t!=null,g=t=>typeof t=="string",v=t=>g(t)&&t!=="",w=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,Q=t=>{try{return btoa(t)}catch{return Buffer.from(t).toString("base64")}},X=t=>{let e=[],r=(o,n)=>{e.push(`${encodeURIComponent(o)}=${encodeURIComponent(String(n))}`)},s=(o,n)=>{B(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("&")}`:""},Z=(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}${X(e.query)}`:o},ee=t=>{if(t.formData){let e=new FormData,r=(s,o)=>{g(o)||w(o)?e.append(s,o):e.append(s,JSON.stringify(o))};return Object.entries(t.formData).filter(([s,o])=>B(o)).forEach(([s,o])=>{Array.isArray(o)?o.forEach(n=>r(s,n)):r(s,o)}),e}},x=async(t,e)=>typeof e=="function"?e(t):e,te=async(t,e)=>{let[r,s,o,n]=await Promise.all([x(e,t.TOKEN),x(e,t.USERNAME),x(e,t.PASSWORD),x(e,t.HEADERS)]),i=Object.entries({Accept:"application/json",...n,...e.headers}).filter(([a,p])=>B(p)).reduce((a,[p,u])=>({...a,[p]:String(u)}),{});if(v(r)&&(i.Authorization=`Bearer ${r}`),v(s)&&v(o)){let a=Q(`${s}:${o}`);i.Authorization=`Basic ${a}`}return e.body&&(e.mediaType?i["Content-Type"]=e.mediaType:w(e.body)?i["Content-Type"]=e.body.type||"application/octet-stream":g(e.body)?i["Content-Type"]="text/plain":_(e.body)||(i["Content-Type"]="application/json")),new Headers(i)},re=t=>{if(t.body!==void 0)return t.mediaType?.includes("/json")?JSON.stringify(t.body):g(t.body)||w(t.body)||_(t.body)?t.body:JSON.stringify(t.body)},oe=async(t,e,r,s,o,n,i)=>{let a=new AbortController,p={headers:n,body:s??o,method:e.method,signal:a.signal};return t.WITH_CREDENTIALS&&(p.credentials=t.CREDENTIALS),i(()=>a.abort()),await fetch(r,p)},se=(t,e)=>{if(e){let r=t.headers.get(e);if(g(r))return r}},ne=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)}},ie=(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 d(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 d(t,e,`Generic Error: status: ${o}; status text: ${n}; body: ${i}`)}},F=(t,e)=>new h(async(r,s,o)=>{try{let n=Z(t,e),i=ee(e),a=re(e),p=await te(t,e);if(!o.isCancelled){let u=await oe(t,e,n,a,i,p,o),f=await ne(u),Y=se(u,e.responseHeader),L={url:n,ok:u.ok,status:u.status,statusText:u.statusText,body:Y??f};ie(e,L),r(L.body)}}catch(n){s(n)}});var O=class extends R{constructor(e){super(e)}request(e){return F(this.config,e)}};var b=class{constructor(e){this.httpRequest=e}authAuthComplete({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/auth/complete",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",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.",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.",500:"InternalServerError: Internal Server Error response."}})}passkeysPasskeyDelete({id:e,authorization:r}){return this.httpRequest.request({method:"DELETE",url:"/fido2/v2/passkeys/{id}",headers:{Authorization:r},path:{id:e},errors:{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}",headers:{Authorization:s},path:{id:e},body:r,mediaType:"application/json",errors:{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}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}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/reg/init",headers:{"User-Agent":r},body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request response.",403:"Forbidden: Forbidden response.",500:"InternalServerError: Internal Server Error response."}})}};var A=class{constructor(e){this.httpRequest=e}tokenTokenVerify({requestBody:e}){return this.httpRequest.request({method:"POST",url:"/fido2/v2/token/verify",body:e,mediaType:"application/json",errors:{400:"BadRequest: Bad Request 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 T=class{constructor(e){this.httpRequest=e}versionVersionShow(){return this.httpRequest.request({method:"GET",url:"/fido2/v2/version"})}};var E=class{auth;passkeys;reg;token;tx;version;request;constructor(e,r=O){this.request=new r({BASE:e?.BASE??"https://api.loginid.io/fido2/v2",VERSION:e?.VERSION??"2.0",WITH_CREDENTIALS:e?.WITH_CREDENTIALS??!1,CREDENTIALS:e?.CREDENTIALS??"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.auth=new b(this.request),this.passkeys=new C(this.request),this.reg=new P(this.request),this.token=new A(this.request),this.tx=new q(this.request),this.version=new T(this.request)}};var k=class{config;service;constructor(e){this.config=e,this.service=new E({BASE:e.baseUrl})}},y=k;import{UAParser as ae}from"ua-parser-js";var D=()=>({clientType:"browser",screenWidth:window.screen.width,screenHeight:window.screen.height}),pe=(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 ue(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?!1:await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function le(){try{return!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable?!1:await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function ce(){let t=new ae(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"&&pe(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 de=t=>t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),ye=t=>{if(!t)return t;let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r=[],s=0;for(;s<t.length;){let i=t.charCodeAt(s++),a=t.charCodeAt(s++),p=t.charCodeAt(s++),u=i<<16|a<<8|p;r.push(e[u>>18&63]+e[u>>12&63]+e[u>>6&63]+e[u&63])}let o=r.join(""),n=t.length%3;return n?o.slice(0,n-3)+"===".slice(n||3):o},me=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 p=r[a];if(p!==void 0)for(o=(o<<6)+p,n+=6;n>=8;)i+=s(o>>(n-=8)&255)}return i},c=t=>{let e="",r=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)e+=String.fromCharCode(r[o]);let s=ye(e);return de(s)},m=t=>{t=t.replace(/-/g,"+").replace(/_/g,"/");let e=me(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e.charCodeAt(s);return r.buffer},W=()=>crypto.randomUUID?crypto.randomUUID():window.crypto.getRandomValues(new Uint32Array(4)).join("-"),V=(t,e)=>{e.forEach(r=>{Object.getOwnPropertyNames(r.prototype).forEach(s=>{Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(r.prototype,s)||Object.create(null))})})};var N=class extends Error{code;constructor(e,r,s){super(e),this.code=r,this.cause=s}},l=N;var M=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="ConstraintError"){if(s?.authenticatorSelection?.requireResidentKey===!0)return new l("Your device does not support discoverable credentials","ERROR_DISCOVERABLE_CREDENTIALS_UNSUPPORTED",t);if(s?.authenticatorSelection?.userVerification==="required")return new l("Your device does not support user verification","ERROR_USER_VERIFICATION_UNSUPPORTED",t)}if(r==="InvalidStateError")return new l("A passkey already exists on your device","ERROR_PASSKEY_EXISTS",t);if(r==="NotAllowedError")return new l("Passkey creation has failed","ERROR_GENERAL_ERROR_SEE_CAUSE_FIELD",t);if(r==="NotSupportedError")return new l("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 l(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new l("Your device could not process the requested options or could not create a new passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t},J=(t,e)=>{let r=t.name,{publicKey:s}=e;if(r==="AbortError"&&e.signal instanceof AbortSignal)return new l("Passkey authentication has been aborted","ERROR_PASSKEY_ABORTED",t);if(r==="NotAllowedError")return new l("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 l(`The domain of the relying party (${o}) is invalid for this domain`,"ERROR_DOMAIN_MISMATCH",t)}return r==="UnknownError"?new l("Your device could not process the requested options or could not authenticate with a passkey","ERROR_AUTHENTICATOR_UNKNOWN_ERROR",t):t};var U=async t=>{let e;if(t.excludeCredentials!==void 0){e=[];for(let o of t.excludeCredentials){let n={id:m(o.id),transports:o.transports,type:o.type};e.push(n)}}let r=t.pubKeyCredParams,s={publicKey:{attestation:t.attestation,authenticatorSelection:{...t.authenticatorSelection},challenge:m(t.challenge),excludeCredentials:e,extensions:t.extensions,pubKeyCredParams:r,rp:t.rp,timeout:t.timeout,user:{...t.user,id:m(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?M(o,s):o}},H=async(t,e={})=>{let r;if(t.allowCredentials!==void 0){r=[];for(let o of t.allowCredentials){let n={id:m(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:m(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?J(o,s):o}};var K=class extends y{jwtAccess="";constructor(e){super(e)}async createNavigatorCredential(e){let{registrationRequestOptions:r,session:s}=e,o=await U(r),n=o.response,i=n.getPublicKey&&n.getPublicKey(),a=n.getPublicKeyAlgorithm&&n.getPublicKeyAlgorithm(),p=n.getAuthenticatorData&&n.getAuthenticatorData(),u=n.getTransports&&n.getTransports();return{creationResult:{attestationObject:c(n.attestationObject),clientDataJSON:c(n.clientDataJSON),credentialId:o.id,...i&&{publicKey:c(i)},...a&&{publicKeyAlgorithm:a},...p&&{authenticatorData:c(p)},...u&&{transports:u}},session:s}}async registerWithPasskey(e,r={}){let s=D();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}},...r.mfa&&{mfa:r.mfa},...r.session&&{session:r.session}},n=await this.service.reg.regRegInit({requestBody:o}),i=await this.createNavigatorCredential(n),a=await this.service.reg.regRegComplete({requestBody:i});return this.jwtAccess=a.jwtAccess,a}async getNavigatorCredential(e,r={}){let{assertionOptions:s,session:o}=e,n=await H(s,r),i=n.response;return{assertionResult:{authenticatorData:c(i.authenticatorData),clientDataJSON:c(i.clientDataJSON),credentialId:n.id,signature:c(i.signature),...i.userHandle&&{userHandle:c(i.userHandle)}},session:o}}async authenticateWithPasskey(e="",r={}){let s=D();r.usernameType||(r.usernameType="email");let o={app:{id:this.config.appId,...r.token&&{token:r.token}},deviceInfo:s,...!r.autoFill&&{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.jwtAccess=a.jwtAccess,a}async confirmTransaction(e,r,s={}){let o={username:e,txPayload:r,nonce:s.nonce||W(),txType:s.txType||"raw"},{assertionOptions:n,session:i}=await this.service.tx.txTxInit({requestBody:o}),a={assertionOptions:n,session:i},{assertionResult:p}=await this.getNavigatorCredential(a),u={authenticatorData:p.authenticatorData,clientData:p.clientDataJSON,keyHandle:p.credentialId,session:i,signature:p.signature},f=await this.service.tx.txTxComplete({requestBody:u});return this.jwtAccess=f.jwtAccess,f}getJWTAccess(){return this.jwtAccess}},$=K;var j=class extends y{constructor(e){super(e)}async listPasskeys(e){return await this.service.passkeys.passkeysPasskeysList({authorization:e})}async renamePasskey(e,r,s){let o={name:s};return await this.service.passkeys.passkeysPasskeyRename({authorization:e,id:r,requestBody:o}),null}async deletePasskey(e,r){return await this.service.passkeys.passkeysPasskeyDelete({authorization:e,id:r}),null}},z=j;var S=class extends y{constructor(e){super(e)}};V(S,[y,$,z]);var G=S;var Bt=G;export{d as ApiError,G as LoginIDWebSDK,l as PasskeyError,U as createPasskeyCredential,Bt as default,ce as doesDeviceSupportPasskeys,H as getPasskeyCredential,le as isConditionalUIAvailable,ue as isPlatformAuthenticatorAvailable};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loginid/websdk3",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",