@authowl/core 0.16.1 → 0.18.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.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,h,j,f as f$1}from'./chunk-ULB5QRXB.js';export{e as AUTH_CHALLENGE_HEADER,b as AuthOwlHttpError,g as createIdempotencyKey,k as getPublicConfig,a as resolveProjectCapabilities}from'./chunk-ULB5QRXB.js';import {f,g as g$1,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 N="authowl_invitation",F="authowl.invitation-claim",ee=/^[A-Za-z0-9_-]{1,128}$/,te=10080*60*1e3;function Ne(e=Date.now()){if(typeof window>"u")return S(e);let n;try{n=new URL(window.location.href);}catch{return S(e)}let t=n.searchParams.get(N);if(t===null)return S(e);n.searchParams.delete(N);try{window.history.replaceState(window.history.state,"",n.toString());}catch{}if(!ee.test(t))return S(e);let i={id:t,capturedAt:e};return f(g$1(),F,JSON.stringify(i)),i}function S(e$1=Date.now()){let n=e(g$1(),F);if(n===null)return null;let t;try{t=JSON.parse(n);}catch{return E(),null}if(typeof t!="object"||t===null)return E(),null;let{id:i,capturedAt:o}=t;return typeof i!="string"||!ee.test(i)||typeof o!="number"||e$1-o>te?(E(),null):{id:i,capturedAt:o}}function E(){f(g$1(),F,null);}function u(e){let n=new Uint8Array(e),t="";for(let o of n)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function g(e){let n=e.replace(/-/g,"+").replace(/_/g,"/"),t=(4-n.length%4)%4,i=n.padEnd(n.length+t,"="),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 y(){return Fe.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var Fe={stubThis:e=>e};function k(e){let{id:n}=e;return {...e,id:g(n),transports:e.transports}}function I(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:n,code:t,cause:i,name:o}){super(n,{cause:i}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=o??i.name,this.code=t;}};function ne({error:e,options:n}){let{publicKey:t}=n;if(!t)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(n.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(t.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(n.mediation==="conditional"&&t.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(t.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 t.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(I(i)){if(t.rp.id!==i)return new c({message:`The RP ID "${t.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(t.user.id.byteLength<1||t.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 L=class{constructor(){Object.defineProperty(this,"controller",{enumerable:true,configurable:true,writable:true,value:void 0});}createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t);}let n=new AbortController;return this.controller=n,n.signal}cancelCeremony(){if(this.controller){let n=new Error("Manually cancelling existing WebAuthn API call");n.name="AbortError",this.controller.abort(n),this.controller=void 0;}}},x=new L;var Le=["cross-platform","platform"];function D(e){if(e&&!(Le.indexOf(e)<0))return e}async function oe(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:n,useAutoRegister:t=false}=e;if(!y())throw new Error("WebAuthn is not supported in this browser");let i={...n,challenge:g(n.challenge),user:{...n.user,id:g(n.user.id)},excludeCredentials:n.excludeCredentials?.map(k)},o={};t&&(o.mediation="conditional"),o.publicKey=i,o.signal=x.createNewAbortSignal();let s;try{s=await navigator.credentials.create(o);}catch(p){throw ne({error:p,options:o})}if(!s)throw new Error("Registration was not completed");let{id:a,rawId:l,response:r,type:O}=s,d;typeof r.getTransports=="function"&&(d=r.getTransports());let h;if(typeof r.getPublicKeyAlgorithm=="function")try{h=r.getPublicKeyAlgorithm();}catch(p){V("getPublicKeyAlgorithm()",p);}let f;if(typeof r.getPublicKey=="function")try{let p=r.getPublicKey();p!==null&&(f=u(p));}catch(p){V("getPublicKey()",p);}let m;if(typeof r.getAuthenticatorData=="function")try{m=u(r.getAuthenticatorData());}catch(p){V("getAuthenticatorData()",p);}return {id:a,rawId:u(l),response:{attestationObject:u(r.attestationObject),clientDataJSON:u(r.clientDataJSON),transports:d,publicKeyAlgorithm:h,publicKey:f,authenticatorData:m},type:O,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:D(s.authenticatorAttachment)}}function V(e,n){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
2
- `,n);}function ie(){if(!y())return K.stubThis(new Promise(n=>n(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?K.stubThis(new Promise(n=>n(false))):K.stubThis(e.isConditionalMediationAvailable())}var K={stubThis:e=>e};function re({error:e,options:n}){let{publicKey:t}=n;if(!t)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(n.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(I(i)){if(t.rpId!==i)return new c({message:`The RP ID "${t.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 ae(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:n,useBrowserAutofill:t=false,verifyBrowserAutofillInput:i=true}=e;if(!y())throw new Error("WebAuthn is not supported in this browser");let o;n.allowCredentials?.length!==0&&(o=n.allowCredentials?.map(k));let s={...n,challenge:g(n.challenge),allowCredentials:o},a={};if(t){if(!await ie())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=x.createNewAbortSignal();let l;try{l=await navigator.credentials.get(a);}catch(m){throw re({error:m,options:a})}if(!l)throw new Error("Authentication was not completed");let{id:r,rawId:O,response:d,type:h}=l,f;return d.userHandle&&(f=u(d.userHandle)),{id:r,rawId:u(O),response:{authenticatorData:u(d.authenticatorData),clientDataJSON:u(d.clientDataJSON),signature:u(d.signature),userHandle:f},type:h,clientExtensionResults:l.getClientExtensionResults(),authenticatorAttachment:D(l.authenticatorAttachment)}}var se={authenticate:e=>ae(e),register:e=>oe(e),errorCode:e=>e instanceof c?e.code:void 0};function le(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function M(e){let n=await c$1(e,le(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:Ve});return n.response.status===401?{required:false}:d(n,"consent status")}async function z(e,n){if(!Number.isSafeInteger(n)||n<1)throw new TypeError("Consent version must be a positive integer.");return d(await c$1(e,le(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:n})},maxResponseBytes:64*1024,decode:Ke}),"consent accept")}function Ve(e){let n=q$1(e),t=s(n.required),i=Me(n.needsConsent),o=pe(n.version),s$1=ce(n.termsUrl),a=ce(n.privacyUrl);return {required:t,...i===void 0?{}:{needsConsent:i},...o===void 0?{}:{version:o},...s$1===void 0?{}:{termsUrl:s$1},...a===void 0?{}:{privacyUrl:a}}}function Ke(e){let n=q$1(e),t=pe(n.version);return {ok:s(n.ok),...t===void 0?{}:{version:t}}}function Me(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function pe(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function ce(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var ze=30;function Be(e){return typeof e?.exp=="number"?e.exp:null}function qe(e){let n=e.split(".")[1];if(!n)return null;try{let t=n.replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(t));return typeof i=="object"&&i!==null?i:null}catch{return null}}function B(e){let n=new Map;async function t(s={}){let a=s.template===void 0?null:s.template.trim().toLowerCase();if(a==="")throw new TypeError("Template missing");let l=a??"",r=n.get(l);r||(r={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},n.set(l,r));let O=s.forceRefresh===true;if(!O){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 d$1=++r.sequence,h=()=>n.get(l)===r&&r.sequence===d$1,f=(async()=>{let p=a?`${e.projectBaseURL}/token/${encodeURIComponent(a)}`:`${e.projectBaseURL}/token`,H=await c$1(e,p,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:T=>Ge(T,a!==null)});if(H.response.status===401)return h()&&i(),null;let J=d(H,"token"),ue=J.policyVersion,v=J.token,b=qe(v),W=Be(b);if(h())if(W!==null){let T=typeof b?.sub=="string"?b.sub:null,de=typeof b?.org_id=="string"?b.org_id:null;if(!a||T){let j=JSON.stringify([e.projectBaseURL,T,de,a,ue]);r.cachedByKey.clear(),r.cachedByKey.set(j,{token:v,exp:W}),r.activeKey=j;}else o(r);}else o(r);return v})();if(O)return f;let m=f.finally(()=>{r.inflight===m&&(r.inflight=null);});return r.inflight=m,m}function i(){n.clear();}function o(s){s.cachedByKey.clear(),s.activeKey=null;}return {getToken:t,clear:i}}function Ge(e,n){let t=q$1(e),i=r(t.token);if(i.length===0||i.length>32*1024)throw new TypeError("Invalid token response.");if(!n)return {token:i,policyVersion:0};let o=q$1(t.template);if(!Number.isSafeInteger(o.policyVersion)||o.policyVersion<1)throw new TypeError("Invalid token response.");return {token:i,policyVersion:o.policyVersion}}function He(e){let n=B(e),t=h(e,n.clear,(a,l)=>j(a,l,se)),i=f$1(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),o=a=>(...l)=>(n.clear(),a(...l)),s={getConsentStatus:()=>M(e),acceptConsent:a=>z(e,a),getToken:n.getToken,waitlist:{join:(a,l)=>i.request("/waitlist",{method:"POST",body:a,fetchOptions:l,credentials:"omit"})},account:{...t.account,updateUnsafeMetadata:o(t.account.updateUnsafeMetadata),updateProfile:o(t.account.updateProfile),changeEmail:o(t.account.changeEmail),changePassword:o(t.account.changePassword),revokeSession:o(t.account.revokeSession),delete:o(t.account.delete)},signIn:{email:o(t.signIn.email),username:o(t.signIn.username),social:o(t.signIn.social),sso:t.signIn.sso,magicLink:t.signIn.magicLink,emailOtp:o(t.signIn.emailOtp),passkey:o(t.signIn.passkey)},signUp:{email:o(t.signUp.email)},emailOtp:{...t.emailOtp,verifyEmail:o(t.emailOtp.verifyEmail)},twoFactor:{enable:t.twoFactor.enable,disable:o(t.twoFactor.disable),verifyTotp:o(t.twoFactor.verifyTotp),verifyBackupCode:o(t.twoFactor.verifyBackupCode),sendOtp:t.twoFactor.sendOtp,verifyOtp:o(t.twoFactor.verifyOtp),generateBackupCodes:t.twoFactor.generateBackupCodes},phoneOtp:{prepare:t.phoneOtp.prepare,start:t.phoneOtp.start,verify:o(t.phoneOtp.verify)},signOut:o(t.signOut)};return {...t,...s}}async function Je(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let n=await We(),t=e.challengeRequired?await n.solvePow(e.challenge,e.difficulty):null,i=e.turnstile.required?await n.getTurnstileToken(je(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...t?{challengeToken:e.challengeToken,nonce:t.nonce}:{},...i?{turnstileToken:i}:{}}}async function We(){return import('@akedly/shield')}function je(e){if(!e)throw new Error("Akedly Shield did not provide a Turnstile site key.");return e}var C=class extends Error{constructor(t,i){super(t);this.cause=i;this.name="AuthOwlError";}cause},q=class extends C{constructor(t,i){super(`Rate limited. Retry after ${t}s.`,i);this.retryAfterSeconds=t;this.name="RateLimitedError";}retryAfterSeconds},G=class extends C{constructor(n="invalid publishable key",t){super(n,t),this.name="InvalidKeyError";}};
3
- export{C as AuthOwlError,te as INVITATION_CLAIM_MAX_AGE_MS,N as INVITATION_QUERY_PARAM,G as InvalidKeyError,q as RateLimitedError,z as acceptConsent,Ne as captureInvitationClaim,E as clearInvitationClaim,He as createAuthOwlClient,B as createTokenClient,M as getConsentStatus,S as readInvitationClaim,Je as solvePhoneOtpChallenge};
1
+ export{a as LOCALES,b as directionFor,c as isLocale}from'./chunk-M4QJVSXT.js';import {c as c$1,d,h,j,f as f$1}from'./chunk-PYXM7X2H.js';export{e as AUTH_CHALLENGE_HEADER,b as AuthOwlHttpError,g as createIdempotencyKey,k as getPublicConfig,a as resolveProjectCapabilities}from'./chunk-PYXM7X2H.js';import {f,g as g$1,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 N="authowl_invitation",F="authowl.invitation-claim",ee=/^[A-Za-z0-9_-]{1,128}$/,te=10080*60*1e3;function Ne(e=Date.now()){if(typeof window>"u")return S(e);let n;try{n=new URL(window.location.href);}catch{return S(e)}let t=n.searchParams.get(N);if(t===null)return S(e);n.searchParams.delete(N);try{window.history.replaceState(window.history.state,"",n.toString());}catch{}if(!ee.test(t))return S(e);let i={id:t,capturedAt:e};return f(g$1(),F,JSON.stringify(i)),i}function S(e$1=Date.now()){let n=e(g$1(),F);if(n===null)return null;let t;try{t=JSON.parse(n);}catch{return E(),null}if(typeof t!="object"||t===null)return E(),null;let{id:i,capturedAt:o}=t;return typeof i!="string"||!ee.test(i)||typeof o!="number"||e$1-o>te?(E(),null):{id:i,capturedAt:o}}function E(){f(g$1(),F,null);}function u(e){let n=new Uint8Array(e),t="";for(let o of n)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function g(e){let n=e.replace(/-/g,"+").replace(/_/g,"/"),t=(4-n.length%4)%4,i=n.padEnd(n.length+t,"="),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 O(){return Fe.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var Fe={stubThis:e=>e};function k(e){let{id:n}=e;return {...e,id:g(n),transports:e.transports}}function I(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:n,code:t,cause:i,name:o}){super(n,{cause:i}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=o??i.name,this.code=t;}};function ne({error:e,options:n}){let{publicKey:t}=n;if(!t)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(n.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(t.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(n.mediation==="conditional"&&t.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(t.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 t.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(I(i)){if(t.rp.id!==i)return new c({message:`The RP ID "${t.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(t.user.id.byteLength<1||t.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 L=class{constructor(){Object.defineProperty(this,"controller",{enumerable:true,configurable:true,writable:true,value:void 0});}createNewAbortSignal(){if(this.controller){let t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t);}let n=new AbortController;return this.controller=n,n.signal}cancelCeremony(){if(this.controller){let n=new Error("Manually cancelling existing WebAuthn API call");n.name="AbortError",this.controller.abort(n),this.controller=void 0;}}},x=new L;var Le=["cross-platform","platform"];function D(e){if(e&&!(Le.indexOf(e)<0))return e}async function oe(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:n,useAutoRegister:t=false}=e;if(!O())throw new Error("WebAuthn is not supported in this browser");let i={...n,challenge:g(n.challenge),user:{...n.user,id:g(n.user.id)},excludeCredentials:n.excludeCredentials?.map(k)},o={};t&&(o.mediation="conditional"),o.publicKey=i,o.signal=x.createNewAbortSignal();let s;try{s=await navigator.credentials.create(o);}catch(p){throw ne({error:p,options:o})}if(!s)throw new Error("Registration was not completed");let{id:a,rawId:l,response:r,type:y}=s,d;typeof r.getTransports=="function"&&(d=r.getTransports());let h;if(typeof r.getPublicKeyAlgorithm=="function")try{h=r.getPublicKeyAlgorithm();}catch(p){V("getPublicKeyAlgorithm()",p);}let f;if(typeof r.getPublicKey=="function")try{let p=r.getPublicKey();p!==null&&(f=u(p));}catch(p){V("getPublicKey()",p);}let m;if(typeof r.getAuthenticatorData=="function")try{m=u(r.getAuthenticatorData());}catch(p){V("getAuthenticatorData()",p);}return {id:a,rawId:u(l),response:{attestationObject:u(r.attestationObject),clientDataJSON:u(r.clientDataJSON),transports:d,publicKeyAlgorithm:h,publicKey:f,authenticatorData:m},type:y,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:D(s.authenticatorAttachment)}}function V(e,n){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
2
+ `,n);}function ie(){if(!O())return M.stubThis(new Promise(n=>n(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?M.stubThis(new Promise(n=>n(false))):M.stubThis(e.isConditionalMediationAvailable())}var M={stubThis:e=>e};function re({error:e,options:n}){let{publicKey:t}=n;if(!t)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(n.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(I(i)){if(t.rpId!==i)return new c({message:`The RP ID "${t.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 ae(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:n,useBrowserAutofill:t=false,verifyBrowserAutofillInput:i=true}=e;if(!O())throw new Error("WebAuthn is not supported in this browser");let o;n.allowCredentials?.length!==0&&(o=n.allowCredentials?.map(k));let s={...n,challenge:g(n.challenge),allowCredentials:o},a={};if(t){if(!await ie())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=x.createNewAbortSignal();let l;try{l=await navigator.credentials.get(a);}catch(m){throw re({error:m,options:a})}if(!l)throw new Error("Authentication was not completed");let{id:r,rawId:y,response:d,type:h}=l,f;return d.userHandle&&(f=u(d.userHandle)),{id:r,rawId:u(y),response:{authenticatorData:u(d.authenticatorData),clientDataJSON:u(d.clientDataJSON),signature:u(d.signature),userHandle:f},type:h,clientExtensionResults:l.getClientExtensionResults(),authenticatorAttachment:D(l.authenticatorAttachment)}}var se={authenticate:e=>ae(e),register:e=>oe(e),errorCode:e=>e instanceof c?e.code:void 0};function le(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function K(e){let n=await c$1(e,le(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:Ve});return n.response.status===401?{required:false}:d(n,"consent status")}async function z(e,n){if(!Number.isSafeInteger(n)||n<1)throw new TypeError("Consent version must be a positive integer.");return d(await c$1(e,le(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:n})},maxResponseBytes:64*1024,decode:Me}),"consent accept")}function Ve(e){let n=q$1(e),t=s(n.required),i=Ke(n.needsConsent),o=pe(n.version),s$1=ce(n.termsUrl),a=ce(n.privacyUrl);return {required:t,...i===void 0?{}:{needsConsent:i},...o===void 0?{}:{version:o},...s$1===void 0?{}:{termsUrl:s$1},...a===void 0?{}:{privacyUrl:a}}}function Me(e){let n=q$1(e),t=pe(n.version);return {ok:s(n.ok),...t===void 0?{}:{version:t}}}function Ke(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function pe(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function ce(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var ze=30;function Be(e){return typeof e?.exp=="number"?e.exp:null}function qe(e){let n=e.split(".")[1];if(!n)return null;try{let t=n.replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(t));return typeof i=="object"&&i!==null?i:null}catch{return null}}function B(e){let n=new Map;async function t(s={}){let a=s.template===void 0?null:s.template.trim().toLowerCase();if(a==="")throw new TypeError("Template missing");let l=a??"",r=n.get(l);r||(r={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},n.set(l,r));let y=s.forceRefresh===true;if(!y){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 d$1=++r.sequence,h=()=>n.get(l)===r&&r.sequence===d$1,f=(async()=>{let p=a?`${e.projectBaseURL}/token/${encodeURIComponent(a)}`:`${e.projectBaseURL}/token`,G=await c$1(e,p,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:C=>He(C,a!==null)});if(G.response.status===401)return h()&&i(),null;let J=d(G,"token"),ue=J.policyVersion,v=J.token,b=qe(v),W=Be(b);if(h())if(W!==null){let C=typeof b?.sub=="string"?b.sub:null,de=typeof b?.org_id=="string"?b.org_id:null;if(!a||C){let j=JSON.stringify([e.projectBaseURL,C,de,a,ue]);r.cachedByKey.clear(),r.cachedByKey.set(j,{token:v,exp:W}),r.activeKey=j;}else o(r);}else o(r);return v})();if(y)return f;let m=f.finally(()=>{r.inflight===m&&(r.inflight=null);});return r.inflight=m,m}function i(){n.clear();}function o(s){s.cachedByKey.clear(),s.activeKey=null;}return {getToken:t,clear:i}}function He(e,n){let t=q$1(e),i=r(t.token);if(i.length===0||i.length>32*1024)throw new TypeError("Invalid token response.");if(!n)return {token:i,policyVersion:0};let o=q$1(t.template);if(!Number.isSafeInteger(o.policyVersion)||o.policyVersion<1)throw new TypeError("Invalid token response.");return {token:i,policyVersion:o.policyVersion}}function Ge(e){let n=B(e),t=h(e,n.clear,(a,l)=>j(a,l,se)),i=f$1(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),o=a=>(...l)=>(n.clear(),a(...l)),s={getConsentStatus:()=>K(e),acceptConsent:a=>z(e,a),getToken:n.getToken,waitlist:{join:(a,l)=>i.request("/waitlist",{method:"POST",body:a,fetchOptions:l,credentials:"omit"})},account:{...t.account,updateUnsafeMetadata:o(t.account.updateUnsafeMetadata),updateProfile:o(t.account.updateProfile),changeEmail:o(t.account.changeEmail),changePassword:o(t.account.changePassword),revokeSession:o(t.account.revokeSession),delete:o(t.account.delete)},signIn:{email:o(t.signIn.email),username:o(t.signIn.username),social:o(t.signIn.social),sso:t.signIn.sso,magicLink:t.signIn.magicLink,emailOtp:o(t.signIn.emailOtp),passkey:o(t.signIn.passkey)},signUp:{email:o(t.signUp.email)},emailOtp:{...t.emailOtp,verifyEmail:o(t.emailOtp.verifyEmail)},twoFactor:{enable:t.twoFactor.enable,disable:o(t.twoFactor.disable),verifyTotp:o(t.twoFactor.verifyTotp),verifyBackupCode:o(t.twoFactor.verifyBackupCode),sendOtp:t.twoFactor.sendOtp,verifyOtp:o(t.twoFactor.verifyOtp),generateBackupCodes:t.twoFactor.generateBackupCodes},phoneOtp:{prepare:t.phoneOtp.prepare,start:t.phoneOtp.start,verify:o(t.phoneOtp.verify)},signOut:o(t.signOut)};return {...t,...s}}async function Je(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let n=await We(),t=e.challengeRequired?await n.solvePow(e.challenge,e.difficulty):null,i=e.turnstile.required?await n.getTurnstileToken(je(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...t?{challengeToken:e.challengeToken,nonce:t.nonce}:{},...i?{turnstileToken:i}:{}}}async function We(){return import('@akedly/shield')}function je(e){if(!e)throw new Error("Akedly Shield did not provide a Turnstile site key.");return e}var T=class extends Error{constructor(t,i){super(t);this.cause=i;this.name="AuthOwlError";}cause},q=class extends T{constructor(t,i){super(`Rate limited. Retry after ${t}s.`,i);this.retryAfterSeconds=t;this.name="RateLimitedError";}retryAfterSeconds},H=class extends T{constructor(n="invalid publishable key",t){super(n,t),this.name="InvalidKeyError";}};
3
+ export{T as AuthOwlError,te as INVITATION_CLAIM_MAX_AGE_MS,N as INVITATION_QUERY_PARAM,H as InvalidKeyError,q as RateLimitedError,z as acceptConsent,Ne as captureInvitationClaim,E as clearInvitationClaim,Ge as createAuthOwlClient,B as createTokenClient,K as getConsentStatus,S as readInvitationClaim,Je as solvePhoneOtpChallenge};