@authowl/core 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- export{a as LOCALES,b as directionFor,c as isLocale}from'./chunk-M4QJVSXT.js';import {c as c$1,d as d$1,k,m,i}from'./chunk-KZCWYFAX.js';export{g as AUTH_CHALLENGE_HEADER,h as AUTH_LOCALE_HEADER,b as AuthOwlHttpError,f as activeLocale,j as createIdempotencyKey,n as getPublicConfig,a as resolveProjectCapabilities,e as setActiveLocale}from'./chunk-KZCWYFAX.js';import {f,g,e,q as q$1,s,r}from'./chunk-V3MSLXXB.js';export{j as SESSION_TOKEN_HEADER,l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,o as TransportError,F as createMembershipHas,a as decodePublishableKey,E as membershipHas,B as membershipHasPermission,D as membershipHasRole,C as membershipHasTeam,m as resolveAuthTarget,n as resolveConfig,h as sessionChallengeIsEphemeral,b as sessionCookieName}from'./chunk-V3MSLXXB.js';import'./chunk-T5SH3ZZP.js';var M="authowl_invitation",V="authowl.invitation-claim",oe=/^[A-Za-z0-9_-]{1,128}$/,ie=10080*60*1e3;function Be(e=Date.now()){if(typeof window>"u")return C(e);let t;try{t=new URL(window.location.href);}catch{return C(e)}let n=t.searchParams.get(M);if(n===null)return C(e);t.searchParams.delete(M);try{window.history.replaceState(window.history.state,"",t.toString());}catch{}if(!oe.test(n))return C(e);let i={id:n,capturedAt:e};return f(g(),V,JSON.stringify(i)),i}function C(e$1=Date.now()){let t=e(g(),V);if(t===null)return null;let n;try{n=JSON.parse(t);}catch{return I(),null}if(typeof n!="object"||n===null)return I(),null;let{id:i,capturedAt:o}=n;return typeof i!="string"||!oe.test(i)||typeof o!="number"||e$1-o>ie?(I(),null):{id:i,capturedAt:o}}function I(){f(g(),V,null);}var re="authowl.last-used-method",qe=/^(password|username|magic-link|email-otp|phone-otp|passkey|sso|social:[a-z0-9][a-z0-9_-]{0,63})$/,K=e=>`${re}.${e}`;function D(e){return qe.test(e)}function He(e$1){let t=e(g(),K(e$1));return t===null||!D(t)?null:t}function Ge(e,t){D(t)&&(f(g(),x(e),null),f(g(),K(e),t));}var x=e=>`${re}.pending.${e}`;function Je(e,t){D(t)&&f(g(),x(e),t);}function We(e$1,t){let n=e(g(),x(e$1));f(g(),x(e$1),null),t&&n!==null&&D(n)&&f(g(),K(e$1),n);}function d(e){let t=new Uint8Array(e),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function y(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,i=t.padEnd(t.length+n,"="),o=atob(i),s=new ArrayBuffer(o.length),a=new Uint8Array(s);for(let l=0;l<o.length;l++)a[l]=o.charCodeAt(l);return s}function A(){return $e.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var $e={stubThis:e=>e};function v(e){let{id:t}=e;return {...e,id:y(t),transports:e.transports}}function U(e){return e==="localhost"||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var c=class extends Error{constructor({message:t,code:n,cause:i,name:o}){super(t,{cause:i}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=o??i.name,this.code=n;}};function ae({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new c({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(n.authenticatorSelection?.requireResidentKey===true)return new c({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&n.authenticatorSelection?.userVerification==="required")return new c({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(n.authenticatorSelection?.userVerification==="required")return new c({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else {if(e.name==="InvalidStateError")return new c({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new c({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return n.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new c({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new c({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){let i=globalThis.location.hostname;if(U(i)){if(n.rp.id!==i)return new c({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new c({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new c({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}var z=class{constructor(){Object.defineProperty(this,"controller",{enumerable:true,configurable:true,writable:true,value:void 0});}createNewAbortSignal(){if(this.controller){let n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n);}let t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){let t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0;}}},_=new z;var je=["cross-platform","platform"];function N(e){if(e&&!(je.indexOf(e)<0))return e}async function se(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:n=false}=e;if(!A())throw new Error("WebAuthn is not supported in this browser");let i={...t,challenge:y(t.challenge),user:{...t.user,id:y(t.user.id)},excludeCredentials:t.excludeCredentials?.map(v)},o={};n&&(o.mediation="conditional"),o.publicKey=i,o.signal=_.createNewAbortSignal();let s;try{s=await navigator.credentials.create(o);}catch(p){throw ae({error:p,options:o})}if(!s)throw new Error("Registration was not completed");let{id:a,rawId:l,response:r,type:b}=s,m;typeof r.getTransports=="function"&&(m=r.getTransports());let O;if(typeof r.getPublicKeyAlgorithm=="function")try{O=r.getPublicKeyAlgorithm();}catch(p){B("getPublicKeyAlgorithm()",p);}let h;if(typeof r.getPublicKey=="function")try{let p=r.getPublicKey();p!==null&&(h=d(p));}catch(p){B("getPublicKey()",p);}let f;if(typeof r.getAuthenticatorData=="function")try{f=d(r.getAuthenticatorData());}catch(p){B("getAuthenticatorData()",p);}return {id:a,rawId:d(l),response:{attestationObject:d(r.attestationObject),clientDataJSON:d(r.clientDataJSON),transports:m,publicKeyAlgorithm:O,publicKey:h,authenticatorData:f},type:b,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:N(s.authenticatorAttachment)}}function B(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
2
- `,t);}function ce(){if(!A())return q.stubThis(new Promise(t=>t(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?q.stubThis(new Promise(t=>t(false))):q.stubThis(e.isConditionalMediationAvailable())}var q={stubThis:e=>e};function le({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new c({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else {if(e.name==="NotAllowedError")return new c({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let i=globalThis.location.hostname;if(U(i)){if(n.rpId!==i)return new c({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new c({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}async function pe(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=false,verifyBrowserAutofillInput:i=true}=e;if(!A())throw new Error("WebAuthn is not supported in this browser");let o;t.allowCredentials?.length!==0&&(o=t.allowCredentials?.map(v));let s={...t,challenge:y(t.challenge),allowCredentials:o},a={};if(n){if(!await ce())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&i)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');a.mediation="conditional",s.allowCredentials=[];}a.publicKey=s,a.signal=_.createNewAbortSignal();let l;try{l=await navigator.credentials.get(a);}catch(f){throw le({error:f,options:a})}if(!l)throw new Error("Authentication was not completed");let{id:r,rawId:b,response:m,type:O}=l,h;return m.userHandle&&(h=d(m.userHandle)),{id:r,rawId:d(b),response:{authenticatorData:d(m.authenticatorData),clientDataJSON:d(m.clientDataJSON),signature:d(m.signature),userHandle:h},type:O,clientExtensionResults:l.getClientExtensionResults(),authenticatorAttachment:N(l.authenticatorAttachment)}}var ue={authenticate:e=>pe(e),register:e=>se(e),errorCode:e=>e instanceof c?e.code:void 0};function me(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function H(e){let t=await c$1(e,me(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:Ye});return t.response.status===401?{required:false}:d$1(t,"consent status")}async function G(e,t){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Consent version must be a positive integer.");return d$1(await c$1(e,me(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:t})},maxResponseBytes:64*1024,decode:Qe}),"consent accept")}function Ye(e){let t=q$1(e),n=s(t.required),i=Xe(t.needsConsent),o=fe(t.version),s$1=de(t.termsUrl),a=de(t.privacyUrl);return {required:n,...i===void 0?{}:{needsConsent:i},...o===void 0?{}:{version:o},...s$1===void 0?{}:{termsUrl:s$1},...a===void 0?{}:{privacyUrl:a}}}function Qe(e){let t=q$1(e),n=fe(t.version);return {ok:s(t.ok),...n===void 0?{}:{version:n}}}function Xe(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function fe(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function de(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var Ze=30;function et(e){return typeof e?.exp=="number"?e.exp:null}function tt(e){let t=e.split(".")[1];if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(n));return typeof i=="object"&&i!==null?i:null}catch{return null}}function J(e){let t=new Map;async function n(s={}){let a=s.template===void 0?null:s.template.trim().toLowerCase();if(a==="")throw new TypeError("Template missing");let l=a??"",r=t.get(l);r||(r={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},t.set(l,r));let b=s.forceRefresh===true;if(!b){let p=r.activeKey?r.cachedByKey.get(r.activeKey):null;if(p&&p.exp-Date.now()/1e3>Ze)return p.token;if(r.inflight)return r.inflight}let m=++r.sequence,O=()=>t.get(l)===r&&r.sequence===m,h=(async()=>{let p=a?`${e.projectBaseURL}/token/${encodeURIComponent(a)}`:`${e.projectBaseURL}/token`,j=await c$1(e,p,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:k=>nt(k,a!==null)});if(j.response.status===401)return O()&&i(),null;let Y=d$1(j,"token"),ge=Y.policyVersion,F=Y.token,w=tt(F),Q=et(w);if(O())if(Q!==null){let k=typeof w?.sub=="string"?w.sub:null,he=typeof w?.org_id=="string"?w.org_id:null;if(!a||k){let X=JSON.stringify([e.projectBaseURL,k,he,a,ge]);r.cachedByKey.clear(),r.cachedByKey.set(X,{token:F,exp:Q}),r.activeKey=X;}else o(r);}else o(r);return F})();if(b)return h;let f=h.finally(()=>{r.inflight===f&&(r.inflight=null);});return r.inflight=f,f}function i(){t.clear();}function o(s){s.cachedByKey.clear(),s.activeKey=null;}return {getToken:n,clear:i}}function nt(e,t){let n=q$1(e),i=r(n.token);if(i.length===0||i.length>32*1024)throw new TypeError("Invalid token response.");if(!t)return {token:i,policyVersion:0};let o=q$1(n.template);if(!Number.isSafeInteger(o.policyVersion)||o.policyVersion<1)throw new TypeError("Invalid token response.");return {token:i,policyVersion:o.policyVersion}}function ot(e){let t=J(e),n=k(e,t.clear,(a,l)=>m(a,l,ue)),i$1=i(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),o=a=>(...l)=>(t.clear(),a(...l)),s={getConsentStatus:()=>H(e),acceptConsent:a=>G(e,a),getToken:t.getToken,waitlist:{join:(a,l)=>i$1.request("/waitlist",{method:"POST",body:a,fetchOptions:l,credentials:"omit"})},account:{...n.account,updateUnsafeMetadata:o(n.account.updateUnsafeMetadata),updateProfile:o(n.account.updateProfile),changeEmail:o(n.account.changeEmail),changePassword:o(n.account.changePassword),revokeSession:o(n.account.revokeSession),delete:o(n.account.delete)},signIn:{email:o(n.signIn.email),username:o(n.signIn.username),social:o(n.signIn.social),sso:n.signIn.sso,magicLink:n.signIn.magicLink,emailOtp:o(n.signIn.emailOtp),passkey:o(n.signIn.passkey)},signUp:{email:o(n.signUp.email)},emailOtp:{...n.emailOtp,verifyEmail:o(n.emailOtp.verifyEmail)},twoFactor:{enable:n.twoFactor.enable,disable:o(n.twoFactor.disable),verifyTotp:o(n.twoFactor.verifyTotp),verifyBackupCode:o(n.twoFactor.verifyBackupCode),sendOtp:n.twoFactor.sendOtp,verifyOtp:o(n.twoFactor.verifyOtp),generateBackupCodes:n.twoFactor.generateBackupCodes},phoneOtp:{prepare:n.phoneOtp.prepare,start:n.phoneOtp.start,verify:o(n.phoneOtp.verify)},signOut:o(n.signOut)};return {...n,...s}}async function it(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let t=await rt(),n=e.challengeRequired?await t.solvePow(e.challenge,e.difficulty):null,i=e.turnstile.required?await t.getTurnstileToken(at(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...n?{challengeToken:e.challengeToken,nonce:n.nonce}:{},...i?{turnstileToken:i}:{}}}async function rt(){return import('@akedly/shield')}function at(e){if(!e)throw new Error("Akedly Shield did not provide a Turnstile site key.");return e}var P=class extends Error{constructor(n,i){super(n);this.cause=i;this.name="AuthOwlError";}cause},W=class extends P{constructor(n,i){super(`Rate limited. Retry after ${n}s.`,i);this.retryAfterSeconds=n;this.name="RateLimitedError";}retryAfterSeconds},$=class extends P{constructor(t="invalid publishable key",n){super(t,n),this.name="InvalidKeyError";}};
3
- export{P as AuthOwlError,ie as INVITATION_CLAIM_MAX_AGE_MS,M as INVITATION_QUERY_PARAM,$ as InvalidKeyError,W as RateLimitedError,G as acceptConsent,Be as captureInvitationClaim,I as clearInvitationClaim,ot as createAuthOwlClient,J as createTokenClient,H as getConsentStatus,C as readInvitationClaim,He as readLastUsedSignInMethod,Ge as recordLastUsedSignInMethod,Je as rememberPendingSignInMethod,We as settlePendingSignInMethod,it as solvePhoneOtpChallenge};
1
+ import {c as c$1,d as d$1,k,m,i,j}from'./chunk-GFSJFTD7.js';export{g as AUTH_CHALLENGE_HEADER,h as AUTH_LOCALE_HEADER,b as AuthOwlHttpError,f as activeLocale,n as getPublicConfig,a as resolveProjectCapabilities,e as setActiveLocale}from'./chunk-GFSJFTD7.js';export{a as LOCALES,b as directionFor,c as isLocale}from'./chunk-M4QJVSXT.js';export{a as createIdempotencyKey}from'./chunk-5NL5GJW6.js';import {f,g,e,q as q$1,s,r}from'./chunk-V3MSLXXB.js';export{j as SESSION_TOKEN_HEADER,l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,o as TransportError,F as createMembershipHas,a as decodePublishableKey,E as membershipHas,B as membershipHasPermission,D as membershipHasRole,C as membershipHasTeam,m as resolveAuthTarget,n as resolveConfig,h as sessionChallengeIsEphemeral,b as sessionCookieName}from'./chunk-V3MSLXXB.js';import'./chunk-T5SH3ZZP.js';var M="authowl_invitation",V="authowl.invitation-claim",ie=/^[A-Za-z0-9_-]{1,128}$/,re=10080*60*1e3;function qe(e=Date.now()){if(typeof window>"u")return C(e);let t;try{t=new URL(window.location.href);}catch{return C(e)}let n=t.searchParams.get(M);if(n===null)return C(e);t.searchParams.delete(M);try{window.history.replaceState(window.history.state,"",t.toString());}catch{}if(!ie.test(n))return C(e);let o={id:n,capturedAt:e};return f(g(),V,JSON.stringify(o)),o}function C(e$1=Date.now()){let t=e(g(),V);if(t===null)return null;let n;try{n=JSON.parse(t);}catch{return P(),null}if(typeof n!="object"||n===null)return P(),null;let{id:o,capturedAt:a}=n;return typeof o!="string"||!ie.test(o)||typeof a!="number"||e$1-a>re?(P(),null):{id:o,capturedAt:a}}function P(){f(g(),V,null);}var ae="authowl.last-used-method",He=/^(password|username|magic-link|email-otp|phone-otp|passkey|sso|social:[a-z0-9][a-z0-9_-]{0,63})$/,K=e=>`${ae}.${e}`;function D(e){return He.test(e)}function Ge(e$1){let t=e(g(),K(e$1));return t===null||!D(t)?null:t}function Je(e,t){D(t)&&(f(g(),x(e),null),f(g(),K(e),t));}var x=e=>`${ae}.pending.${e}`;function We(e,t){D(t)&&f(g(),x(e),t);}function $e(e$1,t){let n=e(g(),x(e$1));f(g(),x(e$1),null),t&&n!==null&&D(n)&&f(g(),K(e$1),n);}function d(e){let t=new Uint8Array(e),n="";for(let a of t)n+=String.fromCharCode(a);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function O(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,o=t.padEnd(t.length+n,"="),a=atob(o),i=new ArrayBuffer(a.length),l=new Uint8Array(i);for(let s=0;s<a.length;s++)l[s]=a.charCodeAt(s);return i}function A(){return je.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var je={stubThis:e=>e};function v(e){let{id:t}=e;return {...e,id:O(t),transports:e.transports}}function U(e){return e==="localhost"||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var c=class extends Error{constructor({message:t,code:n,cause:o,name:a}){super(t,{cause:o}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=a??o.name,this.code=n;}};function se({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new c({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(n.authenticatorSelection?.requireResidentKey===true)return new c({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&n.authenticatorSelection?.userVerification==="required")return new c({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(n.authenticatorSelection?.userVerification==="required")return new c({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else {if(e.name==="InvalidStateError")return new c({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new c({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return n.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new c({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new c({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){let o=globalThis.location.hostname;if(U(o)){if(n.rp.id!==o)return new c({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new c({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new c({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}var z=class{constructor(){Object.defineProperty(this,"controller",{enumerable:true,configurable:true,writable:true,value:void 0});}createNewAbortSignal(){if(this.controller){let n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n);}let t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){let t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0;}}},_=new z;var Ye=["cross-platform","platform"];function N(e){if(e&&!(Ye.indexOf(e)<0))return e}async function ce(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:n=false}=e;if(!A())throw new Error("WebAuthn is not supported in this browser");let o={...t,challenge:O(t.challenge),user:{...t.user,id:O(t.user.id)},excludeCredentials:t.excludeCredentials?.map(v)},a={};n&&(a.mediation="conditional"),a.publicKey=o,a.signal=_.createNewAbortSignal();let i;try{i=await navigator.credentials.create(a);}catch(p){throw se({error:p,options:a})}if(!i)throw new Error("Registration was not completed");let{id:l,rawId:s,response:r,type:b}=i,m;typeof r.getTransports=="function"&&(m=r.getTransports());let y;if(typeof r.getPublicKeyAlgorithm=="function")try{y=r.getPublicKeyAlgorithm();}catch(p){B("getPublicKeyAlgorithm()",p);}let h;if(typeof r.getPublicKey=="function")try{let p=r.getPublicKey();p!==null&&(h=d(p));}catch(p){B("getPublicKey()",p);}let f;if(typeof r.getAuthenticatorData=="function")try{f=d(r.getAuthenticatorData());}catch(p){B("getAuthenticatorData()",p);}return {id:l,rawId:d(s),response:{attestationObject:d(r.attestationObject),clientDataJSON:d(r.clientDataJSON),transports:m,publicKeyAlgorithm:y,publicKey:h,authenticatorData:f},type:b,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:N(i.authenticatorAttachment)}}function B(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
2
+ `,t);}function le(){if(!A())return q.stubThis(new Promise(t=>t(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?q.stubThis(new Promise(t=>t(false))):q.stubThis(e.isConditionalMediationAvailable())}var q={stubThis:e=>e};function pe({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new c({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else {if(e.name==="NotAllowedError")return new c({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let o=globalThis.location.hostname;if(U(o)){if(n.rpId!==o)return new c({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new c({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}async function ue(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=false,verifyBrowserAutofillInput:o=true}=e;if(!A())throw new Error("WebAuthn is not supported in this browser");let a;t.allowCredentials?.length!==0&&(a=t.allowCredentials?.map(v));let i={...t,challenge:O(t.challenge),allowCredentials:a},l={};if(n){if(!await le())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&o)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');l.mediation="conditional",i.allowCredentials=[];}l.publicKey=i,l.signal=_.createNewAbortSignal();let s;try{s=await navigator.credentials.get(l);}catch(f){throw pe({error:f,options:l})}if(!s)throw new Error("Authentication was not completed");let{id:r,rawId:b,response:m,type:y}=s,h;return m.userHandle&&(h=d(m.userHandle)),{id:r,rawId:d(b),response:{authenticatorData:d(m.authenticatorData),clientDataJSON:d(m.clientDataJSON),signature:d(m.signature),userHandle:h},type:y,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:N(s.authenticatorAttachment)}}var de={authenticate:e=>ue(e),register:e=>ce(e),errorCode:e=>e instanceof c?e.code:void 0};function fe(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function H(e){let t=await c$1(e,fe(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:Qe});return t.response.status===401?{required:false}:d$1(t,"consent status")}async function G(e,t){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Consent version must be a positive integer.");return d$1(await c$1(e,fe(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:t})},maxResponseBytes:64*1024,decode:Xe}),"consent accept")}function Qe(e){let t=q$1(e),n=s(t.required),o=Ze(t.needsConsent),a=ge(t.version),i=me(t.termsUrl),l=me(t.privacyUrl);return {required:n,...o===void 0?{}:{needsConsent:o},...a===void 0?{}:{version:a},...i===void 0?{}:{termsUrl:i},...l===void 0?{}:{privacyUrl:l}}}function Xe(e){let t=q$1(e),n=ge(t.version);return {ok:s(t.ok),...n===void 0?{}:{version:n}}}function Ze(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function ge(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function me(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var et=30;function tt(e){return typeof e?.exp=="number"?e.exp:null}function nt(e){let t=e.split(".")[1];if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),o=JSON.parse(atob(n));return typeof o=="object"&&o!==null?o:null}catch{return null}}function J(e){let t=new Map;async function n(i={}){let l=i.template===void 0?null:i.template.trim().toLowerCase();if(l==="")throw new TypeError("Template missing");let s=l??"",r=t.get(s);r||(r={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},t.set(s,r));let b=i.forceRefresh===true;if(!b){let p=r.activeKey?r.cachedByKey.get(r.activeKey):null;if(p&&p.exp-Date.now()/1e3>et)return p.token;if(r.inflight)return r.inflight}let m=++r.sequence,y=()=>t.get(s)===r&&r.sequence===m,h=(async()=>{let p=l?`${e.projectBaseURL}/token/${encodeURIComponent(l)}`:`${e.projectBaseURL}/token`,j=await c$1(e,p,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:k=>ot(k,l!==null)});if(j.response.status===401)return y()&&o(),null;let Y=d$1(j,"token"),he=Y.policyVersion,F=Y.token,w=nt(F),Q=tt(w);if(y())if(Q!==null){let k=typeof w?.sub=="string"?w.sub:null,ye=typeof w?.org_id=="string"?w.org_id:null;if(!l||k){let X=JSON.stringify([e.projectBaseURL,k,ye,l,he]);r.cachedByKey.clear(),r.cachedByKey.set(X,{token:F,exp:Q}),r.activeKey=X;}else a(r);}else a(r);return F})();if(b)return h;let f=h.finally(()=>{r.inflight===f&&(r.inflight=null);});return r.inflight=f,f}function o(){t.clear();}function a(i){i.cachedByKey.clear(),i.activeKey=null;}return {getToken:n,clear:o}}function ot(e,t){let n=q$1(e),o=r(n.token);if(o.length===0||o.length>32*1024)throw new TypeError("Invalid token response.");if(!t)return {token:o,policyVersion:0};let a=q$1(n.template);if(!Number.isSafeInteger(a.policyVersion)||a.policyVersion<1)throw new TypeError("Invalid token response.");return {token:o,policyVersion:a.policyVersion}}function it(e){let t=J(e),n=k(e,t.clear,(s,r)=>m(s,r,de)),o=i(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),a=j(o),i$1=s=>(...r)=>(t.clear(),s(...r)),l={getConsentStatus:()=>H(e),acceptConsent:s=>G(e,s),getToken:t.getToken,privacy:a,waitlist:{join:(s,r)=>o.request("/waitlist",{method:"POST",body:s,fetchOptions:r,credentials:"omit"})},account:{...n.account,updateUnsafeMetadata:i$1(n.account.updateUnsafeMetadata),updateProfile:i$1(n.account.updateProfile),changeEmail:i$1(n.account.changeEmail),changePassword:i$1(n.account.changePassword),revokeSession:i$1(n.account.revokeSession),delete:i$1(n.account.delete)},signIn:{email:i$1(n.signIn.email),username:i$1(n.signIn.username),social:i$1(n.signIn.social),sso:n.signIn.sso,magicLink:n.signIn.magicLink,emailOtp:i$1(n.signIn.emailOtp),passkey:i$1(n.signIn.passkey)},signUp:{email:i$1(n.signUp.email)},emailOtp:{...n.emailOtp,verifyEmail:i$1(n.emailOtp.verifyEmail)},twoFactor:{enable:n.twoFactor.enable,disable:i$1(n.twoFactor.disable),verifyTotp:i$1(n.twoFactor.verifyTotp),verifyBackupCode:i$1(n.twoFactor.verifyBackupCode),sendOtp:n.twoFactor.sendOtp,verifyOtp:i$1(n.twoFactor.verifyOtp),generateBackupCodes:n.twoFactor.generateBackupCodes},phoneOtp:{prepare:n.phoneOtp.prepare,start:n.phoneOtp.start,verify:i$1(n.phoneOtp.verify)},signOut:i$1(n.signOut)};return {...n,...l}}async function rt(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let t=await at(),n=e.challengeRequired?await t.solvePow(e.challenge,e.difficulty):null,o=e.turnstile.required?await t.getTurnstileToken(st(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...n?{challengeToken:e.challengeToken,nonce:n.nonce}:{},...o?{turnstileToken:o}:{}}}async function at(){return import('@akedly/shield')}function st(e){if(!e)throw new Error("Akedly Shield did not provide a Turnstile site key.");return e}var I=class extends Error{constructor(n,o){super(n);this.cause=o;this.name="AuthOwlError";}cause},W=class extends I{constructor(n,o){super(`Rate limited. Retry after ${n}s.`,o);this.retryAfterSeconds=n;this.name="RateLimitedError";}retryAfterSeconds},$=class extends I{constructor(t="invalid publishable key",n){super(t,n),this.name="InvalidKeyError";}};
3
+ export{I as AuthOwlError,re as INVITATION_CLAIM_MAX_AGE_MS,M as INVITATION_QUERY_PARAM,$ as InvalidKeyError,W as RateLimitedError,G as acceptConsent,qe as captureInvitationClaim,P as clearInvitationClaim,it as createAuthOwlClient,J as createTokenClient,H as getConsentStatus,C as readInvitationClaim,Ge as readLastUsedSignInMethod,Je as recordLastUsedSignInMethod,We as rememberPendingSignInMethod,$e as settlePendingSignInMethod,rt as solvePhoneOtpChallenge};