@authowl/core 0.18.2 → 0.20.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.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { A as AuthConfig, D as DecodedPublishableKey, H as HasParams, O as OrganizationMembership, R as ResolvedAuthConfig, a as ResolvedAuthTarget, T as TransportError, b as TransportErrorKind, c as createMembershipHas, d as decodePublishableKey, m as membershipHas, e as membershipHasPermission, f as membershipHasRole, g as membershipHasTeam, r as resolveAuthTarget, h as resolveConfig, s as sessionCookieName } from './organization-membership-B05mzhtA.js';
2
- import { P as PhoneOtpChallengeData, A as AkedlyShieldStartProof } from './client-BfXYqxAr.js';
3
- export { a as AUTH_CHALLENGE_HEADER, b as AcceptOrganizationInvitationData, c as AccountClient, d as AccountSession, e as AccountStatusData, f as ActionFetchOptions, g as AddOrganizationTeamMemberOptions, h as AddPasskeyOptions, i as AuthActionResult, j as AuthClientError, k as AuthErrorContext, l as AuthOwlClient, m as AuthOwlErrorCode, n as AuthPasskey, o as AuthRequestContext, p as AuthResponseContext, q as AuthSession, r as AuthUser, C as ChangeEmailOptions, s as ChangePasswordData, t as ChangePasswordOptions, u as ConsentAcceptResult, v as ConsentStatus, w as CreateOrganizationOptions, x as CreateOrganizationTeamOptions, D as DeleteAccountData, y as DeleteAccountOptions, z as DeleteOrganizationOptions, B as DeletePasskeyData, E as DeletePasskeyOptions, F as DisableTwoFactorOptions, G as EmailAuthData, H as EmailOtpAuthData, I as EmailOtpSignInOptions, J as EmailOtpType, K as EmailSignInOptions, L as EmailSignUpData, M as EmailSignUpOptions, N as EnableTwoFactorOptions, O as EnvironmentType, Q as GenerateBackupCodesOptions, R as GetOrganizationInvitationOptions, S as GetOrganizationOptions, T as GetToken, U as GetTokenOptions, V as INVITATION_CLAIM_MAX_AGE_MS, W as INVITATION_QUERY_PARAM, X as InvitationClaim, Y as InvitationRecipientHint, Z as InviteOrganizationMemberOptions, _ as JsonObject, $ as JsonPrimitive, a0 as JsonValue, a1 as LeaveOrganizationOptions, a2 as LinkSocialData, a3 as LinkSocialOptions, a4 as ListOrganizationInvitationsOptions, a5 as ListOrganizationMembersOptions, a6 as ListOrganizationRolesOptions, a7 as ListOrganizationTeamMembersOptions, a8 as ListOrganizationTeamsOptions, a9 as MagicLinkData, aa as MagicLinkSignInOptions, ab as Organization, ac as OrganizationClient, ad as OrganizationDetails, ae as OrganizationFilterOperator, af as OrganizationInvitation, ag as OrganizationInvitationActionOptions, ah as OrganizationInvitationDetails, ai as OrganizationInvitationStatus, aj as OrganizationMember, ak as OrganizationMemberUser, al as OrganizationMemberWithUser, am as OrganizationMembersData, an as OrganizationRoleSummary, ao as OrganizationSelector, ap as OrganizationTeam, aq as OrganizationTeamMember, ar as OrganizationUserInvitation, as as PasskeyAuthData, at as PasskeySignInOptions, au as PasswordResetData, av as PhoneAuthUser, aw as PhoneOtpStartData, ax as PhoneOtpStartOptions, ay as PhoneOtpVerifyData, az as PhoneOtpVerifyOptions, aA as ProjectCapabilities, aB as PublicConfig, aC as RejectOrganizationInvitationData, aD as RemoveOrganizationMemberData, aE as RemoveOrganizationMemberOptions, aF as RemoveOrganizationTeamData, aG as RemoveOrganizationTeamMemberData, aH as RemoveOrganizationTeamMemberOptions, aI as RemoveOrganizationTeamOptions, aJ as RequestPasswordResetOptions, aK as ResetPasswordOptions, aL as RevokeSessionOptions, aM as SendOtpData, aN as SendTwoFactorOtpData, aO as SendTwoFactorOtpOptions, aP as SendVerificationOtpOptions, aQ as SessionState, aR as SessionStore, aS as SetActiveOrganizationOptions, aT as SetActiveTeamOptions, aU as SignOutData, aV as SocialAccount, aW as SocialAuthData, aX as SocialIdTokenOptions, aY as SocialSignInOptions, aZ as TokenClient, a_ as TwoFactorBackupCodesData, a$ as TwoFactorEnableData, b0 as TwoFactorRedirectData, b1 as TwoFactorStatusData, b2 as TwoFactorVerifyData, b3 as UnlinkSocialOptions, b4 as UpdateOrganizationMemberRoleOptions, b5 as UpdateOrganizationOptions, b6 as UpdateOrganizationTeamOptions, b7 as UpdatePasskeyData, b8 as UpdatePasskeyOptions, b9 as UpdateProfileOptions, ba as UpdateUnsafeMetadataOptions, bb as UserMetadata, bc as UsernameSignInOptions, bd as VerifyBackupCodeOptions, be as VerifyEmailOtpData, bf as VerifyEmailOtpOptions, bg as VerifyTotpOptions, bh as VerifyTwoFactorOtpOptions, bi as WaitlistJoinData, bj as WaitlistJoinOptions, bk as acceptConsent, bl as captureInvitationClaim, bm as clearInvitationClaim, bn as createAuthOwlClient, bo as createTokenClient, bp as getConsentStatus, bq as getPublicConfig, br as readInvitationClaim, bs as resolveProjectCapabilities } from './client-BfXYqxAr.js';
2
+ import { P as PhoneOtpChallengeData, A as AkedlyShieldStartProof } from './client-C76hiQOA.js';
3
+ export { a as AUTH_CHALLENGE_HEADER, b as AUTH_LOCALE_HEADER, c as AcceptOrganizationInvitationData, d as AccountClient, e as AccountSession, f as AccountStatusData, g as ActionFetchOptions, h as AddOrganizationTeamMemberOptions, i as AddPasskeyOptions, j as AuthActionResult, k as AuthClientError, l as AuthErrorContext, m as AuthOwlClient, n as AuthOwlErrorCode, o as AuthPasskey, p as AuthRequestContext, q as AuthResponseContext, r as AuthSession, s as AuthUser, C as ChangeEmailOptions, t as ChangePasswordData, u as ChangePasswordOptions, v as ConsentAcceptResult, w as ConsentStatus, x as CreateOrganizationOptions, y as CreateOrganizationTeamOptions, D as DeleteAccountData, z as DeleteAccountOptions, B as DeleteOrganizationOptions, E as DeletePasskeyData, F as DeletePasskeyOptions, G as DisableTwoFactorOptions, H as EmailAuthData, I as EmailOtpAuthData, J as EmailOtpSignInOptions, K as EmailOtpType, L as EmailSignInOptions, M as EmailSignUpData, N as EmailSignUpOptions, O as EnableTwoFactorOptions, Q as EnvironmentType, R as GenerateBackupCodesOptions, S as GetOrganizationInvitationOptions, T as GetOrganizationOptions, U as GetToken, V as GetTokenOptions, W as INVITATION_CLAIM_MAX_AGE_MS, X as INVITATION_QUERY_PARAM, Y as InvitationClaim, Z as InvitationRecipientHint, _ as InviteOrganizationMemberOptions, $ as JsonObject, a0 as JsonPrimitive, a1 as JsonValue, a2 as LeaveOrganizationOptions, a3 as LinkSocialData, a4 as LinkSocialOptions, a5 as ListOrganizationInvitationsOptions, a6 as ListOrganizationMembersOptions, a7 as ListOrganizationRolesOptions, a8 as ListOrganizationTeamMembersOptions, a9 as ListOrganizationTeamsOptions, aa as MagicLinkData, ab as MagicLinkSignInOptions, ac as Organization, ad as OrganizationClient, ae as OrganizationDetails, af as OrganizationFilterOperator, ag as OrganizationInvitation, ah as OrganizationInvitationActionOptions, ai as OrganizationInvitationDetails, aj as OrganizationInvitationStatus, ak as OrganizationMember, al as OrganizationMemberUser, am as OrganizationMemberWithUser, an as OrganizationMembersData, ao as OrganizationRoleSummary, ap as OrganizationSelector, aq as OrganizationTeam, ar as OrganizationTeamMember, as as OrganizationUserInvitation, at as PasskeyAuthData, au as PasskeySignInOptions, av as PasswordResetData, aw as PhoneAuthUser, ax as PhoneOtpStartData, ay as PhoneOtpStartOptions, az as PhoneOtpVerifyData, aA as PhoneOtpVerifyOptions, aB as ProjectCapabilities, aC as PublicConfig, aD as RejectOrganizationInvitationData, aE as RemoveOrganizationMemberData, aF as RemoveOrganizationMemberOptions, aG as RemoveOrganizationTeamData, aH as RemoveOrganizationTeamMemberData, aI as RemoveOrganizationTeamMemberOptions, aJ as RemoveOrganizationTeamOptions, aK as RequestPasswordResetOptions, aL as ResetPasswordOptions, aM as RevokeSessionOptions, aN as SendOtpData, aO as SendTwoFactorOtpData, aP as SendTwoFactorOtpOptions, aQ as SendVerificationOtpOptions, aR as SessionState, aS as SessionStore, aT as SetActiveOrganizationOptions, aU as SetActiveTeamOptions, aV as SignOutData, aW as SocialAccount, aX as SocialAuthData, aY as SocialIdTokenOptions, aZ as SocialSignInOptions, a_ as TokenClient, a$ as TwoFactorBackupCodesData, b0 as TwoFactorEnableData, b1 as TwoFactorRedirectData, b2 as TwoFactorStatusData, b3 as TwoFactorVerifyData, b4 as UnlinkSocialOptions, b5 as UpdateOrganizationMemberRoleOptions, b6 as UpdateOrganizationOptions, b7 as UpdateOrganizationTeamOptions, b8 as UpdatePasskeyData, b9 as UpdatePasskeyOptions, ba as UpdateProfileOptions, bb as UpdateUnsafeMetadataOptions, bc as UserMetadata, bd as UsernameSignInOptions, be as VerifyBackupCodeOptions, bf as VerifyEmailOtpData, bg as VerifyEmailOtpOptions, bh as VerifyTotpOptions, bi as VerifyTwoFactorOtpOptions, bj as WaitlistJoinData, bk as WaitlistJoinOptions, bl as acceptConsent, bm as captureInvitationClaim, bn as clearInvitationClaim, bo as createAuthOwlClient, bp as createTokenClient, bq as getConsentStatus, br as getPublicConfig, bs as readInvitationClaim, bt as resolveProjectCapabilities } from './client-C76hiQOA.js';
4
4
  export { S as SESSION_TOKEN_HEADER, a as SESSION_TRANSPORT_BEARER, b as SESSION_TRANSPORT_HEADER } from './session-transport-contract-HDPYRum8.js';
5
5
  export { L as LOCALES, a as Locale, d as directionFor, i as isLocale } from './index-hIdXOzRp.js';
6
6
 
@@ -10,6 +10,80 @@ export { L as LOCALES, a as Locale, d as directionFor, i as isLocale } from './i
10
10
  */
11
11
  declare function sessionChallengeIsEphemeral(headers: Headers): boolean;
12
12
 
13
+ /**
14
+ * Which sign-in method last worked IN THIS BROWSER.
15
+ *
16
+ * A returning user usually has one habit, and a form that shows five equal
17
+ * options makes them re-derive it every visit. Remembering it is a small thing
18
+ * that removes a real hesitation.
19
+ *
20
+ * WHY THIS IS NOT THE `last-login-method` PLUGIN. That plugin sets a
21
+ * non-httpOnly cookie and reads it from `document.cookie`. In AuthOwl's SPA
22
+ * architecture that cookie lands on the ENGINE's domain, invisible to the
23
+ * tenant's page; in the server architecture it lands on the tenant server's
24
+ * fetch, which the session bridge does not forward. Unreadable in both. The SDK
25
+ * does not need it told anyway - it executed the call, so it already knows.
26
+ *
27
+ * THE LINE THIS MUST NOT CROSS. What is stored is a property of this BROWSER,
28
+ * never of an address. Nothing here may be keyed by, derived from, or exposed
29
+ * alongside an email or username: "which method does a@b.com use" is an account
30
+ * enumeration and targeted-phishing surface, and answering it before
31
+ * authentication would hand an attacker the cheapest possible reconnaissance.
32
+ * The value is written only AFTER a method has already succeeded here, so it
33
+ * reveals nothing that this browser did not already do.
34
+ *
35
+ * Best-effort storage, deliberately: a browser refusing `localStorage` degrades
36
+ * to "no badge", which is invisible, rather than to a sign-in that throws.
37
+ */
38
+ /**
39
+ * The methods worth remembering, as a closed set.
40
+ *
41
+ * A closed set rather than a free string because this value is read back from
42
+ * storage a user can edit, and it decides what a form highlights. An unknown
43
+ * value is discarded rather than rendered.
44
+ *
45
+ * Social providers collapse to `social:<id>` so a returning Google user is
46
+ * pointed at the Google button rather than at "social" generally.
47
+ */
48
+ type LastUsedSignInMethod = 'password' | 'username' | 'magic-link' | 'email-otp' | 'phone-otp' | 'passkey' | 'sso' | `social:${string}`;
49
+ /**
50
+ * Read what last worked here, or null.
51
+ *
52
+ * Null covers every uncertainty identically - never used, storage refused,
53
+ * value unrecognised, value tampered with - because a caller has exactly one
54
+ * sensible response to all of them, which is to show no badge.
55
+ */
56
+ declare function readLastUsedSignInMethod(projectId: string): LastUsedSignInMethod | null;
57
+ /**
58
+ * Record a method that JUST SUCCEEDED.
59
+ *
60
+ * Never call this at the start of an attempt for a method that completes
61
+ * in-page: a failed password attempt would then teach the form to recommend
62
+ * the method that just did not work.
63
+ *
64
+ * Redirect methods are the exception and are handled by
65
+ * `rememberPendingSignInMethod`, because the page that would record success is
66
+ * one the browser leaves before reaching.
67
+ */
68
+ declare function recordLastUsedSignInMethod(projectId: string, method: LastUsedSignInMethod): void;
69
+ /**
70
+ * Note that a REDIRECT method is being attempted, without recording it as used.
71
+ *
72
+ * Social and SSO leave the page before anything can observe success, so the
73
+ * attempt is parked here and promoted only once the user comes back signed in.
74
+ * Kept separate from the recorded value on purpose: a user who bounces off a
75
+ * provider's consent screen and returns unauthenticated must not be told that
76
+ * provider is what worked last, because it did not.
77
+ */
78
+ declare function rememberPendingSignInMethod(projectId: string, method: LastUsedSignInMethod): void;
79
+ /**
80
+ * Settle a parked redirect attempt once the returning session has loaded.
81
+ *
82
+ * A signed-in return promotes it. A signed-out return clears it, so a cancelled
83
+ * redirect cannot be mistaken for an unrelated sign-in later.
84
+ */
85
+ declare function settlePendingSignInMethod(projectId: string, signedIn: boolean): void;
86
+
13
87
  /**
14
88
  * Complete Akedly Shield's browser-only proof ceremony. The provider package is
15
89
  * lazy-loaded only when the server-selected route requires it.
@@ -40,4 +114,7 @@ declare class AuthOwlHttpError extends Error {
40
114
  constructor(label: string, response: Response, requestId?: string);
41
115
  }
42
116
 
43
- export { AkedlyShieldStartProof, AuthOwlError, AuthOwlHttpError, InvalidKeyError, PhoneOtpChallengeData, RateLimitedError, createIdempotencyKey, sessionChallengeIsEphemeral, solvePhoneOtpChallenge };
117
+ declare function setActiveLocale(projectId: string, locale: string | null): () => void;
118
+ declare function activeLocale(projectId: string): string | null;
119
+
120
+ export { AkedlyShieldStartProof, AuthOwlError, AuthOwlHttpError, InvalidKeyError, type LastUsedSignInMethod, PhoneOtpChallengeData, RateLimitedError, activeLocale, createIdempotencyKey, readLastUsedSignInMethod, recordLastUsedSignInMethod, rememberPendingSignInMethod, sessionChallengeIsEphemeral, setActiveLocale, settlePendingSignInMethod, solvePhoneOtpChallenge };
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-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};
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};