@authowl/core 0.24.0 → 0.24.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
- import {c as c$1,d,k,m as m$1,i,j as j$1}from'./chunk-LBCOMERN.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-LBCOMERN.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,r,t,s}from'./chunk-YL2FF2VS.js';export{j as SESSION_TOKEN_HEADER,l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,p as TransportError,G as createMembershipHas,a as decodePublishableKey,F as membershipHas,C as membershipHasPermission,E as membershipHasRole,D as membershipHasTeam,n as resolveAuthTarget,o as resolveConfig,h as sessionChallengeIsEphemeral,b as sessionCookieName,m as withSessionTransportIntegration}from'./chunk-YL2FF2VS.js';import'./chunk-T5SH3ZZP.js';var M="authowl_invitation",V="authowl.invitation-claim",re=/^[A-Za-z0-9_-]{1,128}$/,ae=10080*60*1e3;function Je(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(!re.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"||!re.test(o)||typeof a!="number"||e$1-a>ae?(P(),null):{id:o,capturedAt:a}}function P(){f(g(),V,null);}var se="authowl.last-used-method",We=/^(password|username|magic-link|email-otp|phone-otp|passkey|sso|social:[a-z0-9][a-z0-9_-]{0,63})$/,K=e=>`${se}.${e}`;function D(e){return We.test(e)}function $e(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=>`${se}.pending.${e}`;function Ye(e,t){D(t)&&f(g(),x(e),t);}function Qe(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);}var Xe="authowl.passkey-offer",ce="done",Ze=720*60*60*1e3,z=(e,t)=>`${Xe}.${e}.${t}`;function et(e$1,t,n=Date.now()){let o=e(g(),z(e$1,t));if(o===null)return true;if(o===ce)return false;let a=Number(o);if(!Number.isFinite(a))return true;let i=n-a;return i<0||i>=Ze}function tt(e,t,n=Date.now()){f(g(),z(e,t),String(n));}function nt(e,t){f(g(),z(e,t),ce);}function m(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 A(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 b(){return ot.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var ot={stubThis:e=>e};function v(e){let{id:t}=e;return {...e,id:A(t),transports:e.transports}}function _(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 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:"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(_(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 B=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;}}},U=new B;var it=["cross-platform","platform"];function N(e){if(e&&!(it.indexOf(e)<0))return e}async function pe(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(!b())throw new Error("WebAuthn is not supported in this browser");let o={...t,challenge:A(t.challenge),user:{...t.user,id:A(t.user.id)},excludeCredentials:t.excludeCredentials?.map(v)},a={};n&&(a.mediation="conditional"),a.publicKey=o,a.signal=U.createNewAbortSignal();let i;try{i=await navigator.credentials.create(a);}catch(p){throw le({error:p,options:a})}if(!i)throw new Error("Registration was not completed");let{id:l,rawId:s,response:r,type:R}=i,f;typeof r.getTransports=="function"&&(f=r.getTransports());let y;if(typeof r.getPublicKeyAlgorithm=="function")try{y=r.getPublicKeyAlgorithm();}catch(p){q("getPublicKeyAlgorithm()",p);}let h;if(typeof r.getPublicKey=="function")try{let p=r.getPublicKey();p!==null&&(h=m(p));}catch(p){q("getPublicKey()",p);}let g;if(typeof r.getAuthenticatorData=="function")try{g=m(r.getAuthenticatorData());}catch(p){q("getAuthenticatorData()",p);}return {id:l,rawId:m(s),response:{attestationObject:m(r.attestationObject),clientDataJSON:m(r.clientDataJSON),transports:f,publicKeyAlgorithm:y,publicKey:h,authenticatorData:g},type:R,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:N(i.authenticatorAttachment)}}function q(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 ue(){if(!b())return H.stubThis(new Promise(t=>t(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?H.stubThis(new Promise(t=>t(false))):H.stubThis(e.isConditionalMediationAvailable())}var H={stubThis:e=>e};function de({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(_(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 me(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(!b())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:A(t.challenge),allowCredentials:a},l={};if(n){if(!await ue())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=U.createNewAbortSignal();let s;try{s=await navigator.credentials.get(l);}catch(g){throw de({error:g,options:l})}if(!s)throw new Error("Authentication was not completed");let{id:r,rawId:R,response:f,type:y}=s,h;return f.userHandle&&(h=m(f.userHandle)),{id:r,rawId:m(R),response:{authenticatorData:m(f.authenticatorData),clientDataJSON:m(f.clientDataJSON),signature:m(f.signature),userHandle:h},type:y,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:N(s.authenticatorAttachment)}}var fe={authenticate:e=>me(e),register:e=>pe(e),errorCode:e=>e instanceof c?e.code:void 0};function he(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function G(e){let t=await c$1(e,he(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:rt});return t.response.status===401?{required:false}:d(t,"consent status")}async function J(e,t){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Consent version must be a positive integer.");return d(await c$1(e,he(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:t})},maxResponseBytes:64*1024,decode:at}),"consent accept")}function rt(e){let t$1=r(e),n=t(t$1.required),o=st(t$1.needsConsent),a=ye(t$1.version),i=ge(t$1.termsUrl),l=ge(t$1.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 at(e){let t$1=r(e),n=ye(t$1.version);return {ok:t(t$1.ok),...n===void 0?{}:{version:n}}}function st(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function ye(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function ge(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var ct=30;function lt(e){return typeof e?.exp=="number"?e.exp:null}function pt(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 W(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 R=i.forceRefresh===true;if(!R){let p=r.activeKey?r.cachedByKey.get(r.activeKey):null;if(p&&p.exp-Date.now()/1e3>ct)return p.token;if(r.inflight)return r.inflight}let f=++r.sequence,y=()=>t.get(s)===r&&r.sequence===f,h=(async()=>{let p=l?`${e.projectBaseURL}/token/${encodeURIComponent(l)}`:`${e.projectBaseURL}/token`,Y=await c$1(e,p,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:k=>ut(k,l!==null)});if(Y.response.status===401)return y()&&o(),null;let Q=d(Y,"token"),Oe=Q.policyVersion,F=Q.token,S=pt(F),X=lt(S);if(y())if(X!==null){let k=typeof S?.sub=="string"?S.sub:null,Ae=typeof S?.org_id=="string"?S.org_id:null;if(!l||k){let Z=JSON.stringify([e.projectBaseURL,k,Ae,l,Oe]);r.cachedByKey.clear(),r.cachedByKey.set(Z,{token:F,exp:X}),r.activeKey=Z;}else a(r);}else a(r);return F})();if(R)return h;let g=h.finally(()=>{r.inflight===g&&(r.inflight=null);});return r.inflight=g,g}function o(){t.clear();}function a(i){i.cachedByKey.clear(),i.activeKey=null;}return {getToken:n,clear:o}}function ut(e,t){let n=r(e),o=s(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=r(n.template);if(!Number.isSafeInteger(a.policyVersion)||a.policyVersion<1)throw new TypeError("Invalid token response.");return {token:o,policyVersion:a.policyVersion}}function dt(e){let t=W(e),n=k(e,t.clear,(s,r)=>m$1(s,r,fe)),o=i(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),a=j$1(o),i$1=s=>(...r)=>(t.clear(),s(...r)),l={getConsentStatus:()=>G(e),acceptConsent:s=>J(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 mt(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let t=await ft(),n=e.challengeRequired?await t.solvePow(e.challenge,e.difficulty):null,o=e.turnstile.required?await t.getTurnstileToken(gt(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...n?{challengeToken:e.challengeToken,nonce:n.nonce}:{},...o?{turnstileToken:o}:{}}}async function ft(){return import('@akedly/shield')}function gt(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},$=class extends I{constructor(n,o){super(`Rate limited. Retry after ${n}s.`,o);this.retryAfterSeconds=n;this.name="RateLimitedError";}retryAfterSeconds},j=class extends I{constructor(t="invalid publishable key",n){super(t,n),this.name="InvalidKeyError";}};
3
- export{I as AuthOwlError,ae as INVITATION_CLAIM_MAX_AGE_MS,M as INVITATION_QUERY_PARAM,j as InvalidKeyError,$ as RateLimitedError,J as acceptConsent,Je as captureInvitationClaim,P as clearInvitationClaim,dt as createAuthOwlClient,W as createTokenClient,G as getConsentStatus,et as passkeyOfferIsDue,C as readInvitationClaim,$e as readLastUsedSignInMethod,je as recordLastUsedSignInMethod,tt as recordPasskeyOfferDismissed,nt as recordPasskeyOfferSettled,Ye as rememberPendingSignInMethod,Qe as settlePendingSignInMethod,mt as solvePhoneOtpChallenge};
1
+ import {c as c$1,d,m as m$1,o,i,l}from'./chunk-QC2AVTUB.js';export{g as AUTH_CHALLENGE_HEADER,h as AUTH_LOCALE_HEADER,b as AuthOwlHttpError,j as PRIVACY_RIGHT_TYPES,f as activeLocale,p as getPublicConfig,k as offeredRightTypes,a as resolveProjectCapabilities,e as setActiveLocale}from'./chunk-QC2AVTUB.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,r,t,s}from'./chunk-YL2FF2VS.js';export{j as SESSION_TOKEN_HEADER,l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,p as TransportError,G as createMembershipHas,a as decodePublishableKey,F as membershipHas,C as membershipHasPermission,E as membershipHasRole,D as membershipHasTeam,n as resolveAuthTarget,o as resolveConfig,h as sessionChallengeIsEphemeral,b as sessionCookieName,m as withSessionTransportIntegration}from'./chunk-YL2FF2VS.js';import'./chunk-T5SH3ZZP.js';var M="authowl_invitation",V="authowl.invitation-claim",re=/^[A-Za-z0-9_-]{1,128}$/,se=10080*60*1e3;function $e(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(!re.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:s}=n;return typeof o!="string"||!re.test(o)||typeof s!="number"||e$1-s>se?(P(),null):{id:o,capturedAt:s}}function P(){f(g(),V,null);}var ae="authowl.last-used-method",Ye=/^(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 Ye.test(e)}function je(e$1){let t=e(g(),K(e$1));return t===null||!D(t)?null:t}function Qe(e,t){D(t)&&(f(g(),x(e),null),f(g(),K(e),t));}var x=e=>`${ae}.pending.${e}`;function Xe(e,t){D(t)&&f(g(),x(e),t);}function Ze(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);}var et="authowl.passkey-offer",ce="done",tt=720*60*60*1e3,z=(e,t)=>`${et}.${e}.${t}`;function nt(e$1,t,n=Date.now()){let o=e(g(),z(e$1,t));if(o===null)return true;if(o===ce)return false;let s=Number(o);if(!Number.isFinite(s))return true;let i=n-s;return i<0||i>=tt}function ot(e,t,n=Date.now()){f(g(),z(e,t),String(n));}function it(e,t){f(g(),z(e,t),ce);}function m(e){let t=new Uint8Array(e),n="";for(let s of t)n+=String.fromCharCode(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function A(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,o=t.padEnd(t.length+n,"="),s=atob(o),i=new ArrayBuffer(s.length),l=new Uint8Array(i);for(let a=0;a<s.length;a++)l[a]=s.charCodeAt(a);return i}function b(){return rt.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var rt={stubThis:e=>e};function v(e){let{id:t}=e;return {...e,id:A(t),transports:e.transports}}function _(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:s}){super(t,{cause:o}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=s??o.name,this.code=n;}};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:"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(s=>s.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(_(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 B=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;}}},U=new B;var st=["cross-platform","platform"];function N(e){if(e&&!(st.indexOf(e)<0))return e}async function pe(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(!b())throw new Error("WebAuthn is not supported in this browser");let o={...t,challenge:A(t.challenge),user:{...t.user,id:A(t.user.id)},excludeCredentials:t.excludeCredentials?.map(v)},s={};n&&(s.mediation="conditional"),s.publicKey=o,s.signal=U.createNewAbortSignal();let i;try{i=await navigator.credentials.create(s);}catch(p){throw le({error:p,options:s})}if(!i)throw new Error("Registration was not completed");let{id:l,rawId:a,response:r,type:R}=i,f;typeof r.getTransports=="function"&&(f=r.getTransports());let y;if(typeof r.getPublicKeyAlgorithm=="function")try{y=r.getPublicKeyAlgorithm();}catch(p){q("getPublicKeyAlgorithm()",p);}let h;if(typeof r.getPublicKey=="function")try{let p=r.getPublicKey();p!==null&&(h=m(p));}catch(p){q("getPublicKey()",p);}let g;if(typeof r.getAuthenticatorData=="function")try{g=m(r.getAuthenticatorData());}catch(p){q("getAuthenticatorData()",p);}return {id:l,rawId:m(a),response:{attestationObject:m(r.attestationObject),clientDataJSON:m(r.clientDataJSON),transports:f,publicKeyAlgorithm:y,publicKey:h,authenticatorData:g},type:R,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:N(i.authenticatorAttachment)}}function q(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 ue(){if(!b())return H.stubThis(new Promise(t=>t(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?H.stubThis(new Promise(t=>t(false))):H.stubThis(e.isConditionalMediationAvailable())}var H={stubThis:e=>e};function de({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(_(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 me(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(!b())throw new Error("WebAuthn is not supported in this browser");let s;t.allowCredentials?.length!==0&&(s=t.allowCredentials?.map(v));let i={...t,challenge:A(t.challenge),allowCredentials:s},l={};if(n){if(!await ue())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=U.createNewAbortSignal();let a;try{a=await navigator.credentials.get(l);}catch(g){throw de({error:g,options:l})}if(!a)throw new Error("Authentication was not completed");let{id:r,rawId:R,response:f,type:y}=a,h;return f.userHandle&&(h=m(f.userHandle)),{id:r,rawId:m(R),response:{authenticatorData:m(f.authenticatorData),clientDataJSON:m(f.clientDataJSON),signature:m(f.signature),userHandle:h},type:y,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:N(a.authenticatorAttachment)}}var fe={authenticate:e=>me(e),register:e=>pe(e),errorCode:e=>e instanceof c?e.code:void 0};function he(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function G(e){let t=await c$1(e,he(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:at});return t.response.status===401?{required:false}:d(t,"consent status")}async function J(e,t){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Consent version must be a positive integer.");return d(await c$1(e,he(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:t})},maxResponseBytes:64*1024,decode:ct}),"consent accept")}function at(e){let t$1=r(e),n=t(t$1.required),o=lt(t$1.needsConsent),s=ye(t$1.version),i=ge(t$1.termsUrl),l=ge(t$1.privacyUrl);return {required:n,...o===void 0?{}:{needsConsent:o},...s===void 0?{}:{version:s},...i===void 0?{}:{termsUrl:i},...l===void 0?{}:{privacyUrl:l}}}function ct(e){let t$1=r(e),n=ye(t$1.version);return {ok:t(t$1.ok),...n===void 0?{}:{version:n}}}function lt(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function ye(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function ge(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var pt=30;function ut(e){return typeof e?.exp=="number"?e.exp:null}function dt(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 W(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 a=l??"",r=t.get(a);r||(r={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},t.set(a,r));let R=i.forceRefresh===true;if(!R){let p=r.activeKey?r.cachedByKey.get(r.activeKey):null;if(p&&p.exp-Date.now()/1e3>pt)return p.token;if(r.inflight)return r.inflight}let f=++r.sequence,y=()=>t.get(a)===r&&r.sequence===f,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=>mt(k,l!==null)});if(j.response.status===401)return y()&&o(),null;let Q=d(j,"token"),Oe=Q.policyVersion,F=Q.token,S=dt(F),X=ut(S);if(y())if(X!==null){let k=typeof S?.sub=="string"?S.sub:null,Ae=typeof S?.org_id=="string"?S.org_id:null;if(!l||k){let Z=JSON.stringify([e.projectBaseURL,k,Ae,l,Oe]);r.cachedByKey.clear(),r.cachedByKey.set(Z,{token:F,exp:X}),r.activeKey=Z;}else s(r);}else s(r);return F})();if(R)return h;let g=h.finally(()=>{r.inflight===g&&(r.inflight=null);});return r.inflight=g,g}function o(){t.clear();}function s(i){i.cachedByKey.clear(),i.activeKey=null;}return {getToken:n,clear:o}}function mt(e,t){let n=r(e),o=s(n.token);if(o.length===0||o.length>32*1024)throw new TypeError("Invalid token response.");if(!t)return {token:o,policyVersion:0};let s$1=r(n.template);if(!Number.isSafeInteger(s$1.policyVersion)||s$1.policyVersion<1)throw new TypeError("Invalid token response.");return {token:o,policyVersion:s$1.policyVersion}}function ft(e){let t=W(e),n=m$1(e,t.clear,(a,r)=>o(a,r,fe)),o$1=i(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),s=l(o$1),i$1=a=>(...r)=>(t.clear(),a(...r)),l$1={getConsentStatus:()=>G(e),acceptConsent:a=>J(e,a),getToken:t.getToken,privacy:s,waitlist:{join:(a,r)=>o$1.request("/waitlist",{method:"POST",body:a,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$1}}async function gt(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let t=await ht(),n=e.challengeRequired?await t.solvePow(e.challenge,e.difficulty):null,o=e.turnstile.required?await t.getTurnstileToken(yt(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...n?{challengeToken:e.challengeToken,nonce:n.nonce}:{},...o?{turnstileToken:o}:{}}}async function ht(){return import('@akedly/shield')}function yt(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},$=class extends I{constructor(n,o){super(`Rate limited. Retry after ${n}s.`,o);this.retryAfterSeconds=n;this.name="RateLimitedError";}retryAfterSeconds},Y=class extends I{constructor(t="invalid publishable key",n){super(t,n),this.name="InvalidKeyError";}};
3
+ export{I as AuthOwlError,se as INVITATION_CLAIM_MAX_AGE_MS,M as INVITATION_QUERY_PARAM,Y as InvalidKeyError,$ as RateLimitedError,J as acceptConsent,$e as captureInvitationClaim,P as clearInvitationClaim,ft as createAuthOwlClient,W as createTokenClient,G as getConsentStatus,nt as passkeyOfferIsDue,C as readInvitationClaim,je as readLastUsedSignInMethod,Qe as recordLastUsedSignInMethod,ot as recordPasskeyOfferDismissed,it as recordPasskeyOfferSettled,Xe as rememberPendingSignInMethod,Ze as settlePendingSignInMethod,gt as solvePhoneOtpChallenge};