@authowl/core 0.16.0 → 0.16.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/{chunk-QQA645UM.js → chunk-ULB5QRXB.js} +1 -1
- package/dist/chunk-V3MSLXXB.js +2 -0
- package/dist/index.cjs +3 -3
- package/dist/index.js +1 -1
- package/dist/native.cjs +1 -1
- package/dist/native.js +1 -1
- package/dist/server.cjs +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5REZDJ26.js +0 -2
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var zo=Object.defineProperty;var bt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Lo=(e,t)=>{for(var n in t)zo(e,n,{get:t[n],enumerable:true});};function le(){return typeof window<"u"&&typeof document<"u"&&typeof crypto<"u"&&typeof crypto.subtle?.digest=="function"}var Ye=bt(()=>{});var xe={};Lo(xe,{beginCrossSiteSignIn:()=>Ir,challengeFor:()=>lo,completeCrossSiteSignIn:()=>Pr,takeHandoffCode:()=>lt});function uo(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function lo(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return uo(new Uint8Array(t))}function kr(){return uo(crypto.getRandomValues(new Uint8Array(wr)))}function po(e,t){let n=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${co}=${e}; Path=/; Max-Age=${t}; SameSite=Lax${n}`;}function Tr(){for(let e of document.cookie.split(";")){let t=e.indexOf("=");if(!(t<0)&&e.slice(0,t).trim()===co)return e.slice(t+1).trim()||null}return null}function Er(){po("",0);}function ao(e){return new URL(e,window.location.href).toString()}async function Ir(e,t){let n=t.callbackURL?ao(t.callbackURL):null;if(n&&new URL(n).origin!==window.location.origin)return null;let o=kr(),i=new URL(`${e.projectBaseURL}/session/start`);if(i.searchParams.set("pk",e.publishableKey),i.searchParams.set("kind",t.kind),t.kind==="social")i.searchParams.set("provider",t.provider),t.scopes?.length&&i.searchParams.set("scopes",t.scopes.join(",")),t.loginHint&&i.searchParams.set("loginHint",t.loginHint),t.requestSignUp!==void 0&&i.searchParams.set("requestSignUp",t.requestSignUp?"1":"0");else for(let a of Sr){let c=t[a];c&&i.searchParams.set(a,c);}let s=`${window.location.origin}${window.location.pathname}${window.location.search}`;i.searchParams.set("cb",n??s);for(let[a,c]of [["err",t.errorCallbackURL],["new",t.newUserCallbackURL]])c&&i.searchParams.set(a,ao(c));return i.searchParams.set("challenge",await lo(o)),po(o,Rr),i.toString()}function lt(e){if(typeof window>"u")return null;let t=window.location.hash;if(!t.includes(ut))return null;let n=new URLSearchParams(t.replace(/^#/,"")),o=n.get(ut);if(!o||e!==void 0&&o!==e)return null;n.delete(ut);let i=n.toString();return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${i?`#${i}`:""}`),o}async function Pr(e,t,n){if(!le())return false;let o=n??lt();if(!o)return false;n&<(n);let i=Tr();if(Er(),!i)return false;t.beginSession({remember:true});let{error:s}=await e.request("/session/exchange",{method:"POST",body:{code:o,verifier:i}});return s===null}var co,ut,wr,Rr,Sr,ve=bt(()=>{Ye();co="authowl_handoff_verifier",ut="authowl_code",wr=32,Rr=900,Sr=["email","providerId","domain","organizationSlug"];});var Mo=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,Fo=/^sk_/i;function ze(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(Fo.test(e))throw new Error("A secret key was passed where a publishable key was expected. Never embed secret keys in client code.");let t=Mo.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1].toLowerCase(),env:t[2].toLowerCase(),projectId:t[3].toLowerCase()}}function Vo(e,t){let n=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}var wt=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function Le(e,t){throw new Error(`${e}: ${t}`)}function Rt(e,t){let n;try{n=new URL(String(e));}catch{throw new TypeError("Transport URL must be absolute.")}if(n.username||n.password||n.hash)throw new TypeError("Transport URL must not contain credentials or a fragment.");let o=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&wt.test(o)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function St(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&Le("apiUrl","origin required");let n;try{n=new URL(e);}catch{Le("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!wt.test(e))&&Le("apiUrl","HTTPS required except exact loopback"),n.origin}function G(e,t){try{return e?.getItem(t)??null}catch{return null}}function q(e,t,n){try{n===null?e?.removeItem(t):e?.setItem(t,n);}catch{}}function V(){try{return globalThis.localStorage}catch{return}}function Y(){try{return globalThis.sessionStorage}catch{return}}var Ho="authowl.session-challenge",qo=e=>`${Ho}.${e}`,Ko="set-auth-challenge",Me="x-authowl-challenge";function Bo(e){let t=e.get(Me);return re(t)?Et(t).some(([n,o])=>n.endsWith(".dont_remember")&&o.length>0):false}var Tt="INVALID_TWO_FACTOR_COOKIE",jo=2048,re=e=>e!==null&&e.length<=jo,kt=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function Et(e){let t=[];for(let n of e.split(";")){let o=n.trimStart(),i=o.indexOf("=");i<=0||t.push([o.slice(0,i).trimEnd(),o.slice(i+1)]);}return t}function It(e){let t=qo(e),n=new Map;function o(){return n.size===0?null:[...n].map(([c,r])=>`${c}=${r}`).join("; ")}function i(){let c=o();q(Y(),t,re(c)?c:null);}function s(c){for(let[r,d]of Et(c))kt.test(r)&&(d===""?n.delete(r):kt.test(d)&&n.set(r,d));}let a=G(Y(),t);return re(a)&&s(a),{presentOn(c){let r=o();c.delete(Me),re(r)&&c.set(Me,r);},observe(c){let r=c.get(Ko);re(r)&&(s(r),i());},clear(){n.clear(),i();}}}var Fe="set-auth-token",Ve="x-authowl-session-transport",He="bearer";var Jo="authowl.session-token",Go="authowl.cookie-transport",Ct="ok",xt="bearer",$o=e=>`${Jo}.${e}`,Wo=e=>`${Go}.${e}`;function Yo(e){return e===Ct?"cookies":e===xt?"bearer":"unknown"}function Xo(e){return e==="cookies"?Ct:e==="bearer"?xt:null}function Qo(e){let t=$o(e),n=Wo(e),o=It(e),i=null,s=false,a=null,c=Yo(G(V(),n)),r=()=>c==="unknown",d=0,l=null,h=false;function y(){let O=G(Y(),t);if(O!==null)return s=true,O;let x=G(V(),t);return x!==null?(s=false,x):null}i=y(),i!==null&&r()&&(h=true);function A(){if(!(!h||!l)){h=false;try{l();}catch{}}}function u(){let O=c==="bearer"?i:null,[x,ge]=s?[Y(),V()]:[V(),Y()];q(ge,t,null),q(x,t,O);}function f(O){O!==null&&a!==null&&(s=a,a=null),i=O,u(),O!==null&&r()&&(h=true,A());}function m(O){c=O,q(V(),n,Xo(O));}function w(){m("unknown"),h=false;}function S(){return i===null&&(i=y()),i}function N(){let O=y();return O!==null&&(i=O),i}function H(O){N()===O&&u();}function b(){d+=1,a=null,s=false,f(null),o.clear(),w();}let k=()=>c!=="cookies";return {hasToken:()=>S()!==null,declareOn(O){if(O.has("authorization"))return false;let x=S();return !x&&!k()?false:(x&&O.set("authorization",`Bearer ${x}`),O.set(Ve,He),o.presentOn(O),true)},wantsToken:k,needsProbe:r,observe(O){let x=O.get(Fe);x&&f(x),o.observe(O);},dropChallenge:o.clear,measureWith(O){l=O,A();},beginRead(){let O=S(),x=d;return {carriedToken:O!==null,endIfDead(){O!==null&&N()===O&&d===x&&b();},recordCookieVerdict(ge){if(d===x&&r()){if(m(ge?"cookies":"bearer"),ge){f(null);return}H(O);}}}},beginSession({remember:O}){d+=1,a=!O,o.clear(),w();},endSession:b}}var Pt=new Map;function vt(e){let t=Pt.get(e);if(t)return t;let n=Qo(e);return Pt.set(e,n),n}function Zo(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function Dt(e,t){let n=vt(e),o=(a,c)=>(t??globalThis.fetch)(a,c);return {fetch:async(a,c)=>{if(c?.credentials==="omit"||!n.wantsToken())return o(a,c);let r=Zo(a,c),d=n.declareOn(r),l=await o(a,{...c,headers:r});return d&&n.observe(l.headers),l},probe:o,tokens:n}}function _t(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=ze(e.publishableKey),n=St(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:n,decoded:t,projectBaseURL:`${n}/api/projects/${t.projectId}/auth`}}function ei(e){let t=_t(e),{fetch:n,...o}=Dt(t.decoded.projectId,e.fetch);return {...e,...t,fetch:n,session:o}}var qe="authowl_invitation",Ke="authowl.invitation-claim",Ut=/^[A-Za-z0-9_-]{1,128}$/,Nt=10080*60*1e3;function ti(e=Date.now()){if(typeof window>"u")return se(e);let t;try{t=new URL(window.location.href);}catch{return se(e)}let n=t.searchParams.get(qe);if(n===null)return se(e);t.searchParams.delete(qe);try{window.history.replaceState(window.history.state,"",t.toString());}catch{}if(!Ut.test(n))return se(e);let o={id:n,capturedAt:e};return q(V(),Ke,JSON.stringify(o)),o}function se(e=Date.now()){let t=G(V(),Ke);if(t===null)return null;let n;try{n=JSON.parse(t);}catch{return ae(),null}if(typeof n!="object"||n===null)return ae(),null;let{id:o,capturedAt:i}=n;return typeof o!="string"||!Ut.test(o)||typeof i!="number"||e-i>Nt?(ae(),null):{id:o,capturedAt:i}}function ae(){q(V(),Ke,null);}function ni(e){let t=e?.enabledMethods??["password"],n=t.includes("password"),o=t.includes("passkey"),i=e?.authentication,s=e?.mfa;return {emailSignUp:i?.email.signUp??t.some(a=>a==="password"||a==="magic_link"||a==="email_otp"),passwordSignUp:i?.password.signUp??n,phoneSignUp:i?.phone.signUp??t.includes("phone_otp"),passwordSignIn:i?.email.signIn.includes("password")??n,passwordMinLength:i?.password.minLength??8,passwordMaxLength:i?.password.maxLength??128,magicLinkSignIn:i?.email.signIn.includes("magic_link")??t.includes("magic_link"),emailOtpSignIn:i?.email.signIn.includes("email_otp")??t.includes("email_otp"),phoneSignIn:i?.phone.signIn??t.includes("phone_otp"),usernameSignIn:i?.username.signIn??false,collectUsername:i?.username.collectOnSignUp??false,passkeySignIn:i?.passkey.signIn??o,passkeyAdd:i?.passkey.add??o,firstLastName:e?.userModel?.firstLastName??false,emailChange:e===null?false:e.userModel?.emailChange??true,accountDeletion:e?.userModel?.accountDeletion??e?.accountDeletion??false,emailVerificationRequired:e?.emailVerification?.required??e?.requireEmailVerification??false,emailVerificationMethod:e?.emailVerification?.method??"link",totp:s?.totp??e?.twoFactor??false,mfaRequired:s?.required??e?.mfaRequired??false,backupCodes:s?.backupCodes??e?.twoFactor??false,legacyNameField:e?.authentication===void 0}}var oi=1e4,ii=1024*1024,D=class extends Error{kind;requestId;constructor(t,n){super(pi(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},Mt=new WeakSet;function _(e,t){let n=new D(e,t);return Mt.add(n),n}async function Ft({fetchImpl:e,url:t,init:n={},timeoutMs:o=oi,maxResponseBytes:i=ii,allowHttpLoopback:s=false,decode:a}){Lt(o,"timeoutMs"),Lt(i,"maxResponseBytes");let c=Rt(t,{allowHttpLoopback:s}),r=n.signal,d=new AbortController,l=null,h,y=new Promise(m=>{h=m;}),A=m=>{l===null&&(l=m,h({type:"abort",kind:m}),d.abort());},u=()=>A("aborted");r?.addEventListener("abort",u,{once:true});let f=setTimeout(()=>A("timeout"),o);r?.aborted&&u();try{if(l!==null)throw _(l);let m;try{m=await Promise.race([e(c.toString(),{...n,redirect:"error",signal:d.signal}).then(k=>({type:"response",response:k})),y]);}catch{throw _(l??"network")}if(m.type==="abort")throw _(m.kind);if(!ri(m.response))throw _("invalid_response");let w=m.response,S=di(w.headers),N=await si(w,i,y,()=>l,S),H=ui(w,N,S),b;try{b=w.ok&&a?a(H,Object.freeze({status:w.status})):H;}catch{throw _("invalid_response",S)}return {response:w,data:b,...S===void 0?{}:{requestId:S}}}catch(m){throw m instanceof D&&Mt.has(m)?m:_(l??"network")}finally{clearTimeout(f),r?.removeEventListener("abort",u);}}function ri(e){if(!e||typeof e!="object")return false;let t=e;return Number.isInteger(t.status)&&t.status>=0&&t.status<=599&&typeof t.statusText=="string"&&typeof t.ok=="boolean"&&typeof t.headers?.get=="function"&&(t.body===null||typeof t.body=="object"&&typeof t.body?.getReader=="function"&&typeof t.body.cancel=="function")}async function si(e,t,n,o,i){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw zt(e.body),_("invalid_response",i);if(Number(s)>t)throw zt(e.body),_("response_too_large",i)}if(!e.body)return "";let a;try{a=e.body.getReader();}catch{throw _("network",i)}let c=[],r=0,d=null;try{for(;;){let y;try{y=await Promise.race([a.read(),n]);}catch{d=_(o()??"network",i);break}if(ai(y)){d=_(y.kind,i);break}let{done:A,value:u}=y;if(A)break;if(u.byteLength!==0){if(r+=u.byteLength,r>t){d=_("response_too_large",i);break}c.push(u);}}}finally{d&&ci(a);try{a.releaseLock();}catch{}}if(d)throw d;let l=new Uint8Array(r),h=0;for(let y of c)l.set(y,h),h+=y.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw _("invalid_response",i)}}function ai(e){return "type"in e&&e.type==="abort"}function zt(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function ci(e){try{e.cancel().catch(()=>{});}catch{}}function ui(e,t,n){if(e.status===204||e.status===205)return null;let o=li(e.headers.get("content-type"));if(!e.ok&&(!o||t.length===0))return null;if(!o||t.length===0)throw _("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw _("invalid_response",n)}}function li(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function di(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Lt(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function pi(e){switch(e){case "aborted":return "The request was cancelled.";case "timeout":return "The request timed out.";case "response_too_large":return "The response exceeded the allowed size.";case "invalid_response":return "The service returned an invalid response.";case "network":return "The network request could not be completed."}}var me=class extends Error{status;requestId;constructor(t,n,o){super(`${t} request failed with status ${n.status}.`),this.name="AuthOwlHttpError",this.status=n.status,this.requestId=o;}};function K(e,t,n={}){let o=new Headers(n.init?.headers);return o.set("x-publishable-key",e.publishableKey),Ft({fetchImpl:e.fetch,url:t,init:{...n.init,headers:o},allowHttpLoopback:e.decoded.env==="test",...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.maxResponseBytes===void 0?{}:{maxResponseBytes:n.maxResponseBytes},...n.decode===void 0?{}:{decode:n.decode}})}function X(e,t){if(!e.response.ok)throw new me(t,e.response,e.requestId);return e.data}var qt="x-authowl-turnstile-token",fi=1e4,gi=32,mi=2e4;function ee(e,t){return {post:(n,o,i,s)=>e.request(n,{method:"POST",body:o,fetchOptions:i,decode:s}),mutation:async(n,o)=>{let i=await n;return i.error===null&&(o===void 0||i.data!==null&&o(i.data))&&t(),i}}}function ue(e,t=e.projectBaseURL){return {async request(n,o={}){let i=Ai(t,n,o.query),s=o.method??(o.body===void 0?"GET":"POST"),a=new Headers(o.fetchOptions?.headers);o.fetchOptions?.authChallengeToken&&a.set(qt,o.fetchOptions.authChallengeToken),o.body!==void 0&&a.set("content-type","application/json");let c={method:s,headers:a,credentials:o.credentials??"include",...o.body===void 0?{}:{body:JSON.stringify(o.body)}},r=Object.freeze({method:s,path:n});await o.fetchOptions?.onRequest?.(r);let d=yi(s,o.fetchOptions),l;try{l=await hi(e,i,{...c,signal:o.fetchOptions?.signal},d);}catch(m){let w=Ht(m);return await o.fetchOptions?.onError?.(Be(r,w,wi(m))),{data:null,error:w}}let{response:h,requestId:y}=l,A=ki(n,l.data),u=A;if(h.ok)try{u=Je(A),o.decode&&(u=o.decode(u));}catch{let m=Ht(new D("invalid_response",y));return await o.fetchOptions?.onError?.(Be(r,m,"invalid_response")),{data:null,error:m}}let f=Object.freeze({...r,status:h.status,...y===void 0?{}:{requestId:y}});if(await o.fetchOptions?.onResponse?.(f),!h.ok){let m=Oi(h,A,y);return m.code===Tt&&e.session.tokens.dropChallenge(),await o.fetchOptions?.onError?.(Be(r,m,"api")),{data:null,error:m}}return await o.fetchOptions?.onSuccess?.(f),{data:u,error:null}}}}async function hi(e,t,n,o){let i=Date.now()+fi;for(let s=0;s<o;s+=1){let a=i-Date.now();if(a<=0)throw new D("timeout");try{let c=await K(e,t,{init:n,timeoutMs:Math.max(1,Math.ceil(a))});if(c.response.status<500||s===o-1)return c}catch(c){if(s===o-1||!(c instanceof D)||c.kind!=="network")throw c}await Ri(50*2**s,n.signal,i);}throw new D("network")}function yi(e,t){if(e!=="GET"||t?.authChallengeToken)return 1;let n=t?.retry;return typeof n!="number"||!Number.isFinite(n)?1:Math.min(Math.max(Math.trunc(n),0),3)+1}function Ai(e,t,n){let o=new URL(`${e}${t.startsWith("/")?t:`/${t}`}`);for(let[i,s]of Object.entries(n??{}))s!==void 0&&o.searchParams.set(i,String(s));return o.toString()}function Oi(e,t,n){let o=ce(t)?t:{},i=bi(o,e.headers);return {status:e.status,statusText:e.statusText,code:typeof o.code=="string"?o.code:void 0,...n===void 0?{}:{requestId:n},...typeof o.current_version=="number"?{currentVersion:o.current_version}:{},...i!==void 0?{retryAfterSeconds:i}:{},message:typeof o.message=="string"?o.message:typeof o.error=="string"?o.error:typeof o.detail=="string"?o.detail:e.statusText||"Request failed"}}function bi(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??Vt(t.get("retry-after"))??Vt(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function Vt(e){if(!e)return;let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)?n:void 0}function Ht(e){let t=e instanceof D?e.kind:"network";return {status:0,...{aborted:{statusText:"ABORTED",code:"REQUEST_ABORTED",message:"The request was cancelled."},timeout:{statusText:"TIMEOUT",code:"REQUEST_TIMEOUT",message:"The request timed out."},response_too_large:{statusText:"INVALID_RESPONSE",code:"RESPONSE_TOO_LARGE",message:"The service response was too large."},invalid_response:{statusText:"INVALID_RESPONSE",code:"INVALID_RESPONSE",message:"The service returned an invalid response."},network:{statusText:"FETCH_ERROR",code:"FETCH_ERROR",message:"Network request failed."}}[t],...e instanceof D&&e.requestId?{requestId:e.requestId}:{}}}function Be(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function wi(e){return e instanceof D?e.kind:"network"}function Ri(e,t,n){return new Promise((o,i)=>{if(t?.aborted){i(new D("aborted"));return}let s=n-Date.now();if(s<=0){i(new D("timeout"));return}let a=Math.min(e,s),c=()=>{clearTimeout(r),i(new D("aborted"));},r=setTimeout(()=>{t?.removeEventListener("abort",c),Date.now()>=n?i(new D("timeout")):o();},a);t?.addEventListener("abort",c,{once:true}),t?.aborted&&c();})}function Je(e,t="",n=0,o={nodes:0}){if(o.nodes+=1,n>gi||o.nodes>mi)throw new Error("response traversal limit exceeded");if(typeof e=="string"&&/^(?:createdAt|updatedAt|expiresAt)$/.test(t)){let i=new Date(e);return Number.isNaN(i.getTime())?e:i}return Array.isArray(e)?e.map(i=>Je(i,"",n+1,o)):ce(e)?Object.fromEntries(Object.entries(e).map(([i,s])=>[i,Si(i)?s:Je(s,i,n+1,o)])):e}function Si(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function ki(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(i=>ce(i)?je(i):i);if(!ce(t))return t;let o=e==="/change-password"||e==="/passkey/verify-authentication"||e==="/phone-otp/verify"||e==="/sign-up/email"||e.startsWith("/sign-in/")||e.startsWith("/two-factor/verify-")?je(t):t;return e==="/sign-up/email"&&!("sessionCreated"in o)&&(o={...o,sessionCreated:typeof t.token=="string"&&t.token.length>0}),(e==="/get-session"||e==="/passkey/verify-authentication")&&ce(o.session)&&(o={...o,session:je(o.session)}),o}function je(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function ce(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}var Ti=new Set(["__proto__","constructor","prototype"]);function g(e){(!e||typeof e!="object"||Array.isArray(e))&&p();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&p(),e}function R(e){return typeof e!="string"&&p(),e}function T(e){return typeof e!="boolean"&&p(),e}function P(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&p(),e}function he(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&p(),[...e]}function I(e,t){let n=e[t];return n==null||typeof n=="string"?n:p()}function Kt(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:p()}function L(e){let t=g(e),n=t.email;return n!==null&&typeof n!="string"&&p(),{id:R(t.id),email:n,emailVerified:T(t.emailVerified),createdAt:P(t.createdAt),updatedAt:P(t.updatedAt),...z("phoneNumber",I(t,"phoneNumber")),...z("username",I(t,"username")),...z("displayUsername",I(t,"displayUsername")),...z("firstName",I(t,"firstName")),...z("lastName",I(t,"lastName")),...z("name",I(t,"name")),...z("image",I(t,"image")),...z("twoFactorEnabled",Kt(t,"twoFactorEnabled"))}}function ye(e){let t=g(e),n=t.membership;return {id:R(t.id),userId:R(t.userId),expiresAt:P(t.expiresAt),...z("activeOrganizationId",I(t,"activeOrganizationId")),...z("activeTeamId",I(t,"activeTeamId")),...z("membership",n==null?n:Ei(n)),...z("pendingMfaEnrollment",Kt(t,"pendingMfaEnrollment"))}}function p(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function B(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&p(),$e(e,t,n)}function $e(e,t=20,n=1e4){return Ge(e,0,{nodes:0},t,n)}function Ei(e){let t=g(e);return {role:R(t.role),permissions:he(t.permissions),...t.teams===void 0?{}:{teams:he(t.teams)}}}function Ge(e,t,n,o,i){if(n.nodes+=1,(t>o||n.nodes>i)&&p(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||p(),e;if(Array.isArray(e))return e.map(c=>Ge(c,t+1,n,o,i));(!e||typeof e!="object")&&p();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&p();let a={};for(let[c,r]of Object.entries(e))Ti.has(c)&&p(),a[c]=Ge(r,t+1,n,o,i);return a}function z(e,t){return t===void 0?{}:{[e]:t}}function Bt({http:e,probe:t,tokens:n,channelName:o}){let i=new Set,s=null,a=null,c=null,r=null,d=null,l,h=b=>{u(b);};l={data:null,isPending:true,isRefetching:false,error:null,refetch:h};function y(b){l=b;for(let k of i)k();}async function A(b){return e.request("/get-session",{query:b?.query,decode:We})}function u(b){if(b?.query?.disableCookieCache===true)return f(b);if(r)return r;let k=f(b).finally(()=>{r===k&&(r=null);});return r=k,k}async function f(b){c?.abort();let k=new AbortController;c=k,y({...l,isPending:l.data===null&&l.error===null,isRefetching:l.data!==null});let O=n.beginRead(),x=await e.request("/get-session",{query:b?.query,fetchOptions:{signal:k.signal},decode:We});if(c===k&&(c=null,y({data:x.data,error:x.error,isPending:false,isRefetching:false,refetch:h}),x.error===null)){if(x.data===null){O.endIfDead();return}await m(O);}}async function m(b){if(n.needsProbe()){if(!b.carriedToken){b.recordCookieVerdict(true);return}return d||w(b)}}function w(b){let k=t.request("/get-session",{query:{disableCookieCache:true},decode:We}).then(O=>{d===k&&O.error===null&&b.recordCookieVerdict(O.data!==null);}).finally(()=>{d===k&&(d=null);});return d=k,k}function S(){s?.postMessage({type:"session-changed"});}function N(){if(typeof window>"u"||a)return;let b=()=>{u();},k=()=>{document.visibilityState==="visible"&&u();};window.addEventListener("focus",b),document.addEventListener("visibilitychange",k),typeof BroadcastChannel<"u"&&(s=new BroadcastChannel(o),s.addEventListener("message",b)),a=()=>{window.removeEventListener("focus",b),document.removeEventListener("visibilitychange",k),s?.close(),s=null,a=null;};}function H(b){return i.add(b),i.size===1&&(N(),u()),()=>{if(i.delete(b),i.size===0){let k=c;c=null,r=null,k?.abort(),a?.();}}}return n.measureWith(()=>{n.needsProbe()&&w(n.beginRead());}),{store:{subscribe:H,getSnapshot:()=>l},getSession:A,notifyMutation(){S(),d&&d.catch(()=>{}).then(()=>{!n.needsProbe()&&n.hasToken()&&S();}),i.size>0&&u({query:{disableCookieCache:true}});}}}function We(e){if(e===null)return null;let t=g(e);return (t.session===void 0||t.user===void 0)&&p(),{session:ye(t.session),user:L(t.user)}}Ye();function Xe(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return `${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}async function jt(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:Gt})}async function Jt(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:Gt})}function Gt(e){let t=g(e),n=B(t.public_metadata),o=B(t.unsafe_metadata);if(!Number.isSafeInteger(t.metadata_version)||t.metadata_version<0)throw new TypeError("Invalid AuthOwl metadata response");return {publicMetadata:n,unsafeMetadata:o,metadataVersion:t.metadata_version}}function Wt(e,t){let{post:n,mutation:o}=ee(e,t);return {getMetadata:i=>jt(e,i),updateUnsafeMetadata:(i,s)=>Jt(e,i,s),updateProfile:(i,s)=>o(n("/update-user",i,s,de)),changeEmail:(i,s)=>o(n("/change-email",i,s,de)),changePassword:(i,s)=>o(n("/change-password",i,s,Ii)),listSessions:i=>e.request("/list-sessions",{fetchOptions:i,decode:Pi}),revokeSession:({sessionId:i},s)=>o(n("/revoke-session",{sessionId:i},s,de)),revokeOtherSessions:i=>o(n("/revoke-other-sessions",{},i,de)),listSocialAccounts:async i=>{let s=await e.request("/list-accounts",{fetchOptions:i,decode:Ci});if(!s.data)return {data:null,error:s.error};let a=s.data.length>1;return {...s,data:s.data.filter(c=>c.providerId!=="credential").map(c=>({...c,canUnlink:a}))}},linkSocial:(i,s)=>n("/link-social",i,s,xi),unlinkSocial:(i,s)=>o(n("/unlink-account",i,s,de)),delete:(i={},s)=>o(n("/delete-user",i,s,vi))}}function de(e){let t=g(e);return {status:T(t.status)}}function Ii(e){let t=g(e);return {user:L(t.user)}}function Pi(e){return Array.isArray(e)||p(),e.map(t=>{let n=g(t);return {id:R(n.id),userId:R(n.userId),createdAt:P(n.createdAt),updatedAt:P(n.updatedAt),expiresAt:P(n.expiresAt),...$t("ipAddress",I(n,"ipAddress")),...$t("userAgent",I(n,"userAgent"))}})}function Ci(e){return Array.isArray(e)||p(),e.map(t=>{let n=g(t);return {id:R(n.id),userId:R(n.userId),providerId:R(n.providerId),accountId:R(n.accountId),scopes:he(n.scopes),createdAt:P(n.createdAt),updatedAt:P(n.updatedAt)}})}function xi(e){let t=g(e);return {url:R(t.url),redirect:T(t.redirect)}}function vi(e){let t=g(e);return {success:T(t.success),message:R(t.message)}}function $t(e,t){return t===void 0?{}:{[e]:t}}function Ae(e,t){return !e||!t?false:e.permissions.includes(t)}function Yt(e,t){return !e||!t?false:e.teams?.includes(t)??false}function Xt(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function Oe(e,t){if(!e)return false;let{role:n,permission:o,teamId:i}=t;return !(n===void 0&&o===void 0&&i===void 0||n!==void 0&&!Xt(e,n)||o!==void 0&&!e.permissions.includes(o)||i!==void 0&&!Yt(e,i))}function Di(e){return {has:t=>Oe(e,t),hasPermission:t=>Ae(e,t.permission)}}var _i=new Set(["pending","accepted","rejected","canceled"]),Qe=1e4;function te(e,t,n){let o=g(e),i={id:C(o.id),name:C(o.name),slug:C(o.slug),createdAt:P(o.createdAt),...be("logo",I(o,"logo")),...be("metadata",o.metadata===void 0?void 0:$e(o.metadata))};return $(i.id,t),$(i.slug,n),i}function Qt(e){return W(e,te)}function Ze(e,t,n){return e===null?null:(t===null&&p(),te(e,t,n))}function Zt(e,t,n){if(e===null)return null;let o=g(e),i=te(o,t,n);return {...i,members:W(o.members,s=>fn(s,i.id)),invitations:W(o.invitations,s=>j(s,void 0,i.id))}}function en(e,t){let n=W(e,o=>pn(o));return Re(n.map(o=>o.organizationId),t),n}function tn(e,t,n){return e===null?null:(t===null&&p(),pn(e,t,n))}function nn(e,t){let n=g(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&p(),{members:Ui(n.members,t),total:n.total}}function j(e,t,n){let o=g(e),i=C(o.status);_i.has(i)||p();let s={id:C(o.id),organizationId:C(o.organizationId),email:we(o.email),role:C(o.role),status:i,inviterId:C(o.inviterId),expiresAt:P(o.expiresAt),createdAt:P(o.createdAt)};return $(s.id,t),$(s.organizationId,n),s}function on(e,t){let n=W(e,o=>j(o));return Re(n.map(o=>o.organizationId),t),n}function rn(e){return W(e,t=>{let n=g(t);return {...j(n),organizationName:we(n.organizationName)}})}function sn(e,t){let n=g(e);return {...j(n,t),organizationName:C(n.organizationName),organizationSlug:C(n.organizationSlug),inviterEmail:gn(n.inviterEmail)}}function an(e,t){let n=g(e),o=j(n.invitation,t);return {invitation:o,member:ne(n.member,void 0,o.organizationId)}}function cn(e,t){let n=g(e);return n.member!==null&&p(),{invitation:n.invitation===null?null:j(n.invitation,t),member:null}}function un(e,t){return e===null?null:j(e,t)}function ln(e,t,n){let o=g(e);return {member:ne(o.member,n,t)}}function ne(e,t,n){let o=g(e),i={id:C(o.id),organizationId:C(o.organizationId),userId:C(o.userId),role:C(o.role),createdAt:P(o.createdAt),...o.user===void 0?{}:{user:mn(o.user)}};return $(i.id,t),$(i.organizationId,n),i}function dn(e,t){let n=W(e,o=>{let i=g(o);return {organizationId:C(i.organizationId),data:{role:C(i.role),...be("permission",i.permission===void 0?void 0:Ni(i.permission))}}});return Re(n.map(o=>o.organizationId),t),n.map(o=>o.data)}function pn(e,t,n){let o=g(e),i=o.updatedAt,s={id:C(o.id),name:we(o.name),organizationId:C(o.organizationId),createdAt:P(o.createdAt),...i===void 0?{}:{updatedAt:P(i)}};return $(s.id,t),$(s.organizationId,n),s}function fn(e,t){let n=g(e);return {...ne(n,void 0,t),user:mn(n.user)}}function Ui(e,t){let n=W(e,o=>fn(o));return Re(n.map(o=>o.organizationId),t),n}function Ni(e){let t=g(e),n={};for(let[o,i]of Object.entries(t))(o==="__proto__"||o==="constructor"||o==="prototype"||o.length===0||o.length>Qe||!Array.isArray(i))&&p(),n[o]=i.map(s=>C(s));return n}function C(e){let t=R(e);return (t.length===0||t.length>Qe)&&p(),t}function we(e){if(e==null)return "";let t=R(e);return t.length>Qe&&p(),t}function gn(e){return e===null?null:C(e)}function $(e,t){t!==void 0&&e!==t&&p();}function Re(e,t){let n=t??e[0];n!==void 0&&e.some(o=>o!==n)&&p();}function mn(e){let t=g(e);return {id:C(t.id),name:we(t.name),email:gn(t.email),...be("image",I(t,"image"))}}function W(e,t){return Array.isArray(e)||p(),e.map(n=>t(n))}function be(e,t){return t===void 0?{}:{[e]:t}}function hn(e,t,n=()=>null){let{post:o,mutation:i}=ee(e,t),s=new Map,a=(r,d,l,h)=>{if(l)return e.request(r,{query:d,fetchOptions:l,decode:h});let y=`${r}\0${JSON.stringify(d??null)}`,A=s.get(y);if(A)return A;let u=e.request(r,{query:d,decode:h}).finally(()=>{s.delete(y);});return s.set(y,u),u},c=r=>i(r).finally(()=>s.clear());return {create:(r,d)=>c(o("/organization/create",r,d,te)),list:r=>a("/organization/list",void 0,r,Qt),get:(r={},d)=>a("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},d,l=>Zt(l,r.organizationId,r.organizationSlug)),setActive:(r,d)=>c(o("/organization/set-active",r,d,l=>Ze(l,r.organizationId,r.organizationSlug))),listTeams:(r={},d)=>a("/organization/list-teams",{organizationId:r.organizationId},d,l=>en(l,r.organizationId)),setActiveTeam:(r,d)=>c(o("/organization/set-active-team",r,d,l=>tn(l,r.teamId))),update:(r,d)=>c(o("/organization/update",r,d,l=>Ze(l,r.organizationId))),delete:(r,d)=>c(o("/organization/delete",r,d,l=>te(l,r.organizationId))),listMembers:(r={},d)=>a("/organization/list-members",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,limit:r.limit,offset:r.offset,sortBy:r.sortBy,sortDirection:r.sortDirection,filterField:r.filterField,filterValue:r.filterValue,filterOperator:r.filterOperator},d,l=>nn(l,r.organizationId)),inviteMember:(r,d)=>c(o("/organization/invite-member",r,d,l=>j(l,void 0,r.organizationId))),listInvitations:(r={},d)=>a("/organization/list-invitations",{organizationId:r.organizationId},d,l=>on(l,r.organizationId)),listUserInvitations:r=>a("/organization/list-user-invitations",void 0,r,rn),getInvitation:(r,d)=>a("/organization/get-invitation",{id:r.id},d,l=>sn(l,r.id)),acceptInvitation:(r,d)=>c(o("/organization/accept-invitation",r,d,l=>an(l,r.invitationId))),rejectInvitation:(r,d)=>c(o("/organization/reject-invitation",r,d,l=>cn(l,r.invitationId))),cancelInvitation:(r,d)=>c(o("/organization/cancel-invitation",r,d,l=>un(l,r.invitationId))),removeMember:(r,d)=>c(o("/organization/remove-member",r,d,l=>ln(l,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,d)=>c(o("/organization/update-member-role",r,d,l=>ne(l,r.memberId,r.organizationId))),leave:(r,d)=>c(o("/organization/leave",r,d,l=>ne(l,void 0,r.organizationId))),listRoles:(r={},d)=>a("/organization/list-roles",{organizationId:r.organizationId},d,l=>dn(l,r.organizationId)),has:r=>Oe(n(),r),hasPermission:r=>Ae(n(),r.permission)}}var yn=4096,zi=4096,Li=100,Mi=256,Fi=16,Vi=64,Hi=12;function tt(e){let t=g(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&p(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:Nn(t.twoFactorMethods,Fi,Vi)}}):(t.twoFactorRedirect!==void 0&&p(),{redirect:T(t.redirect),...Ji(t,"url"),user:L(t.user)})}function An(e){let t=g(e);return {user:L(t.user)}}function On(e){let t=g(e);return {sessionCreated:T(t.sessionCreated),user:L(t.user)}}function bn(e,t){let n=g(e),o=T(n.redirect);n.user===null&&p();let i=n.user!==void 0&&n.user!==null,s=n.url!==void 0&&n.url!==null;return o?((i||!s)&&p(),{redirect:true,url:et(n.url,t)}):(i===s&&p(),i?{redirect:false,user:L(n.user)}:{redirect:false,url:et(n.url,t)})}function wn(e,t){let n=g(e);return (n.redirect!==true||n.user!==void 0)&&p(),{redirect:true,url:et(n.url,t)}}function Rn(e){return {status:T(g(e).status)}}function Sn(e){return {success:T(g(e).success)}}function kn(e){return g(e).status!=="pending"&&p(),{status:"pending"}}function Tn(e){let t=g(e);if(t.kind==="authowl_turnstile")return {kind:"authowl_turnstile"};t.kind!=="akedly_shield_v1_2"&&p();let n=g(t.turnstile),o=n.siteKey===null?null:R(n.siteKey);return {kind:"akedly_shield_v1_2",connectionId:R(t.connectionId),challenge:R(t.challenge),difficulty:qi(t.difficulty),challengeToken:R(t.challengeToken),challengeRequired:T(t.challengeRequired),turnstile:{required:T(n.required),siteKey:o}}}function qi(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>Hi)&&p(),Number(e)}function En(e){let t=g(e);return (t.status!==true||t.sessionCreated!==true)&&p(),{status:true,sessionCreated:true,user:Ki(t.user)}}function nt(e){return {status:T(g(e).status)}}function In(e){return {status:T(g(e).status)}}function Pn(e){let t=g(e);return {status:T(t.status),user:L(t.user)}}function Cn(e){return {success:T(g(e).success)}}function xn(e){let t=g(e);return {totpURI:ji(t.totpURI),backupCodes:Un(t.backupCodes)}}function vn(e){return {status:T(g(e).status)}}function Se(e){return g(e).status!==true&&p(),{status:true}}function Dn(e){return {status:T(g(e).status)}}function _n(e){let t=g(e);return t.status!==void 0&&t.status!==true&&p(),{backupCodes:Un(t.backupCodes)}}function Ki(e){let t=g(e);return {id:oe(t.id,512),...Gi(t,"name",1024),phoneNumber:oe(t.phoneNumber,64),phoneNumberVerified:T(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:P(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:P(t.updatedAt)}}}function et(e,t){let n=oe(e,yn);/[\u0000-\u0020\u007f]/u.test(n)&&p();let o;try{o=new URL(n);}catch{return p()}return (o.username||o.password)&&p(),o.protocol==="https:"||t&&o.protocol==="http:"&&Bi(o.hostname)?o.href:p()}function Bi(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function ji(e){let t=oe(e,zi),n;try{n=new URL(t);}catch{return p()}let o=n.searchParams.get("secret");return (n.protocol!=="otpauth:"||n.hostname.toLowerCase()!=="totp"||n.username||n.password||n.hash||o===null||o.length===0||o.length>512||/\s/u.test(o))&&p(),t}function Un(e){return Nn(e,Li,Mi)}function Nn(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&p();let o=e.map(i=>oe(i,n));return o.some(i=>i.trim().length===0)&&p(),new Set(o).size!==o.length&&p(),o}function oe(e,t){let n=R(e);return (n.length===0||n.length>t)&&p(),n}function Ji(e,t){let n=e[t];return n==null?{}:{[t]:oe(n,yn)}}function Gi(e,t,n){let o=I(e,t);return o===void 0?{}:(o!==null&&o.length>n&&p(),{[t]:o})}var zn=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),ke=new Set([9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279]);function Te(e){if(e===void 0)return {valid:true,value:void 0};for(let n of e){let o=n.codePointAt(0);if(o===void 0||Mn(n,o)||Ln(o)||zn.has(o))return {valid:false}}let t=$i(e);return ot(t)?{valid:true,value:t}:{valid:false}}function ot(e){let t=0,n,o;for(let i of e){if(t+=1,t>256)return false;let s=i.codePointAt(0);if(s===void 0||Mn(i,s)||Ln(s)||zn.has(s))return false;n??=s,o=s;}return t>0&&n!==void 0&&o!==void 0&&!ke.has(n)&&!ke.has(o)}function Ee(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_PASSKEY_NAME",message:"Passkey names must contain 1 to 256 safe Unicode characters."}}}function $i(e){let t=0,n=e.length;for(;t<n;){let o=e.codePointAt(t);if(o===void 0||!ke.has(o))break;t+=o>65535?2:1;}for(;n>t;){let o=e.codePointAt(n-1);if(o===void 0)break;let s=o>=56320&&o<=57343?n-2:n-1,a=e.codePointAt(s);if(a===void 0||!ke.has(a))break;n=s;}return e.slice(t,n)}function Ln(e){return e>=0&&e<=31||e>=127&&e<=159}function Mn(e,t){return e.length===1&&t>=55296&&t<=57343}var Hn=12,qn=5e3,Wi=8,Yi=1e3,Xi=16,Fn=512,Kn=100,Bn=8192,Qi=32768,it=1024,Vn=256,st=64,Zi=6e5,er=/^[A-Za-z0-9_-]+$/u,tr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,nr=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,or=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,ir=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,jn=new Set(["discouraged","preferred","required"]),rr=new Set(["singleDevice","multiDevice"]),Jn=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),Gn=new Set(["hybrid","security-key","client-device"]),sr=new Set(["none","indirect","direct","enterprise"]),ar=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),cr=new Set(["platform","cross-platform"]),ur=new Set(["discouraged","preferred","required"]),lr=new Set([-8,-7,-257]);function $n(e){let t=B(e,Hn,qn);return {challenge:io(t.challenge),...v("timeout",no(t.timeout)),...v("rpId",ro(t.rpId)),...v("allowCredentials",to(t.allowCredentials)),...v("userVerification",pe(t.userVerification,jn)),...v("hints",Ie(t.hints,Gn)),...v("extensions",oo(t.extensions))}}function Wn(e){let t=B(e,Hn,qn);return {challenge:io(t.challenge),rp:dr(t.rp),user:pr(t.user),pubKeyCredParams:fr(t.pubKeyCredParams),...v("timeout",no(t.timeout)),...v("excludeCredentials",to(t.excludeCredentials)),...v("authenticatorSelection",gr(t.authenticatorSelection)),...v("attestation",pe(t.attestation,sr)),...v("attestationFormats",Ie(t.attestationFormats,ar)),...v("hints",Ie(t.hints,Gn)),...v("extensions",oo(t.extensions))}}function Yn(e){let t=g(e),n=ye(t.session),o=L(t.user);return n.userId!==o.id&&p(),{session:n,user:o}}function at(e){let t=g(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&p();let o=ct(t.deviceType,rr),i=T(t.backedUp);return i&&o!=="multiDevice"&&p(),{id:ie(t.id,Vn),...yr(t),publicKey:mr(t.publicKey,Qi),userId:ie(t.userId,Vn),credentialID:Ce(t.credentialID,Bn),counter:n,deviceType:o,backedUp:i,...Ar(t),createdAt:P(t.createdAt),...Or(t)}}function Xn(e,t,n){let o=at(e);return (o.credentialID!==t||(n===void 0?o.name!==void 0&&o.name!==null:o.name!==n))&&p(),o}function Qn(e){(!Array.isArray(e)||e.length>Kn)&&p();let t=e.map(at);return Pe(t.map(n=>n.id)),Pe(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&p(),t}function Zn(e,t,n){let o=g(e),i=at(o.passkey);return (i.id!==t||i.name!==n)&&p(),{passkey:i}}function eo(e){return g(e).status!==true&&p(),{status:true}}function dr(e){let t=g(e);return {name:rt(t.name,it),...v("id",ro(t.id))}}function pr(e){let t=g(e);return {id:Ce(t.id,128,1,64),name:rt(t.name,it),displayName:rt(t.displayName,it)}}function fr(e){(!Array.isArray(e)||e.length===0||e.length>st)&&p();let t=e.map(n=>{let o=g(n);return (o.type!=="public-key"||!Number.isSafeInteger(o.alg)||!lr.has(o.alg))&&p(),{type:"public-key",alg:o.alg}});return br(t.map(n=>n.alg)),t}function to(e){if(e===void 0)return;(!Array.isArray(e)||e.length>Kn)&&p();let t=e.map(n=>{let o=g(n);return o.type!=="public-key"&&p(),{type:"public-key",id:Ce(o.id,Bn),...v("transports",Ie(o.transports,Jn))}});return Pe(t.map(n=>n.id)),t}function gr(e){if(e===void 0)return;let t=g(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&p();let n=pe(t.residentKey,ur);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&p(),{...v("authenticatorAttachment",pe(t.authenticatorAttachment,cr)),...v("residentKey",n),...v("requireResidentKey",t.requireResidentKey),...v("userVerification",pe(t.userVerification,jn))}}function no(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>Zi)&&p(),e}function oo(e){return e===void 0?void 0:B(e,Wi,Yi)}function Ie(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>st)&&p();let n=e.map(o=>ct(o,t));return Pe(n),n}function pe(e,t){if(e!==void 0)return ct(e,t)}function io(e){return Ce(e,Math.ceil(Fn*4/3),Xi,Fn)}function Ce(e,t,n=1,o=Number.POSITIVE_INFINITY){let i=ie(e,t),s=i.length%4,a=hr(i.at(-1)??""),c=Math.floor(i.length*3/4);return (!er.test(i)||s===1||s===2&&(a&15)!==0||s===3&&(a&3)!==0||c<n||c>o)&&p(),i}function ie(e,t){let n=R(e);return (n.length===0||n.length>t)&&p(),n}function rt(e,t){let n=ie(e,t);return nr.test(n)&&p(),n}function ro(e){if(e===void 0)return;let t=ie(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!or.test(n)))&&p(),t}function mr(e,t){let n=ie(e,t),o=n.endsWith("=="),i=!o&&n.endsWith("="),s=n.at(o?-3:i?-2:-1)??"",a=so(s);return (n.length%4!==0||!tr.test(n)||o&&(a&15)!==0||i&&(a&3)!==0)&&p(),n}function hr(e){return so(e,true)}function so(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function yr(e){let t=I(e,"name");return t===void 0?{}:(t!==null&&!ot(t)&&p(),{name:t})}function Ar(e){let t=I(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>st||n.some(o=>!Jn.has(o))||new Set(n).size!==n.length)&&p(),{transports:t}}function Or(e){let t=I(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(ir.test(t)||p(),{aaguid:t})}function ct(e,t){let n=R(e);return t.has(n)||p(),n}function v(e,t){return t===void 0?{}:{[e]:t}}function Pe(e){new Set(e).size!==e.length&&p();}function br(e){new Set(e).size!==e.length&&p();}function Cr(e,t){if(!t)return e;let n=t.catch(()=>{});return n.then(()=>{n=null;}),{async request(o,i){return n&&await n,e.request(o,i)}}}var fo=new Map;function xr(e,t,n){let o=fo.get(n);if(!o){let i=new URLSearchParams(window.location.hash.slice(1)).get("authowl_code");if(!i)return;o=Promise.resolve().then(()=>(ve(),xe)).then(s=>s.completeCrossSiteSignIn(e,t,i)),fo.set(n,o);}return o}function go(e){return !le()||e.idToken||e.disableRedirect?"legacy":"first-party"}function ho(e,t=()=>{},n=vr){let o=ue(e),i=e.session.tokens,s=le()?xr(o,i,e.decoded.projectId):void 0,a=Cr(o,s),c=Bt({http:a,probe:ue({...e,fetch:e.session.probe}),tokens:i,channelName:`authowl:${e.decoded.projectId}`}),r=n(a,c.notifyMutation),d=()=>{c.notifyMutation(),t();},{post:l,mutation:h}=ee(a,d),y=e.decoded.env==="test",A=u=>{i.beginSession({remember:u?.rememberMe!==false});};return {sessionStore:c.store,getSession:c.getSession,account:Wt(a,d),organization:hn(a,d,()=>c.store.getSnapshot().data?.session.membership??null),signIn:{email:(u,f)=>(A(u),h(l("/sign-in/email",u,f,tt),m=>!("twoFactorRedirect"in m))),username:(u,f)=>(A(u),h(l("/sign-in/username",u,f,tt),m=>!("twoFactorRedirect"in m))),social:async(u,f)=>{if(A(),go(u)==="first-party"){let{beginCrossSiteSignIn:w}=await Promise.resolve().then(()=>(ve(),xe)),S=await w(e,{kind:"social",provider:u.provider,callbackURL:u.callbackURL,errorCallbackURL:u.errorCallbackURL,newUserCallbackURL:u.newUserCallbackURL,scopes:u.scopes,loginHint:u.loginHint,requestSignUp:u.requestSignUp});if(S)return window.location.assign(S),{data:{redirect:true,url:S},error:null}}let m=await h(l("/sign-in/social",u,f,w=>bn(w,y)),w=>"user"in w);return m.error!==null||m.data===null||"url"in m.data&&m.data.redirect&&!u.disableRedirect&&typeof window<"u"&&window.location.assign(m.data.url),m},sso:async(u,f)=>{if(go(u)==="first-party"){let{beginCrossSiteSignIn:w}=await Promise.resolve().then(()=>(ve(),xe)),S=await w(e,{kind:"sso",email:u.email,providerId:u.providerId,domain:u.domain,organizationSlug:u.organizationSlug,callbackURL:u.callbackURL,errorCallbackURL:u.errorCallbackURL,newUserCallbackURL:u.newUserCallbackURL});if(S)return window.location.assign(S),{data:{url:S,redirect:true},error:null}}let m=await l("/sign-in/sso",u,f,w=>wn(w,y));return m.error!==null||m.data===null||typeof window<"u"&&window.location.assign(m.data.url),m},magicLink:(u,f)=>l("/sign-in/magic-link",u,f,Rn),emailOtp:(u,f)=>(A(),h(l("/sign-in/email-otp",u,f,An))),passkey:(u,f)=>(A(),r.signIn(u,f))},signUp:{email:(u,f)=>(A(),h(l("/sign-up/email",u,f,On),m=>m.sessionCreated))},emailOtp:{sendVerificationOtp:(u,f)=>l("/email-otp/send-verification-otp",u,f,Sn),verifyEmail:(u,f)=>(A(),h(l("/email-otp/verify-email",u,f,Pn)))},phoneOtp:{prepare:u=>l("/phone-otp/challenge",{},u,Tn),start:(u,f)=>l("/phone-otp/start",{...u,idempotencyKey:u.idempotencyKey??Xe()},f,kn),verify:(u,f)=>(A(),h(l("/phone-otp/verify",u,f,En)))},requestPasswordReset:(u,f)=>l("/request-password-reset",u,f,nt),resetPassword:(u,f)=>l("/reset-password",u,f,nt),sendVerificationEmail:(u,f)=>l("/send-verification-email",u,f,In),passkey:{addPasskey:(u,f)=>r.add(u,f),listUserPasskeys:()=>a.request("/passkey/list-user-passkeys",{decode:Qn}),updatePasskey:async(u,f)=>{let m=Te(u.name);if(!m.valid||m.value===void 0)return Ee();let w=m.value;return l("/passkey/update-passkey",{...u,name:w},f,S=>Zn(S,u.id,w))},deletePasskey:(u,f)=>l("/passkey/delete-passkey",u,f,eo)},twoFactor:{enable:(u,f)=>l("/two-factor/enable",u,f,xn),disable:(u,f)=>h(l("/two-factor/disable",u,f,vn),m=>m.status),verifyTotp:(u,f)=>h(l("/two-factor/verify-totp",u,f,Se)),verifyBackupCode:(u,f)=>h(l("/two-factor/verify-backup-code",u,f,Se)),sendOtp:(u={},f)=>l("/two-factor/send-otp",u,f,Dn),verifyOtp:(u,f)=>h(l("/two-factor/verify-otp",u,f,Se)),generateBackupCodes:(u,f)=>l("/two-factor/generate-backup-codes",u,f,_n)},signOut:u=>h(a.request("/sign-out",{method:"POST",body:{},fetchOptions:u,decode:Cn}).then(f=>(i.endSession(),f)),f=>f.success)}}function vr(){return {signIn:()=>mo(),add:()=>mo()}}function mo(){return Promise.resolve({data:null,error:{status:400,statusText:"BAD_REQUEST",code:"PASSKEY_BROWSER_REQUIRED",message:"This passkey ceremony requires a browser with WebAuthn."}})}function Ro(e,t,n){let o=new Map;return {async signIn(i={},s){let a=await e.request("/passkey/generate-authenticate-options");if(!a.data)return Oo(a.error);let c;try{c=$n(a.data);}catch{return yo()}let r;try{r=await n.authenticate({optionsJSON:c,useBrowserAutofill:i.autoFill});}catch(A){return bo(n,A,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!Dr(r))return Ao();let{clientExtensionResults:d,...l}=r,h=o.get(r.id);if(h)return h;let y=(async()=>{let A=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:l},fetchOptions:s,decode:Yn});return A.data&&t(),A})();o.set(r.id,y);try{return await y}finally{o.get(r.id)===y&&o.delete(r.id);}},async add(i={},s){let a=Te(i.name);if(!a.valid)return Ee();let c=await e.request("/passkey/generate-register-options",{query:{name:a.value,authenticatorAttachment:i.authenticatorAttachment}});if(!c.data)return Oo(c.error);let r;try{r=Wn(c.data);}catch{return yo()}let d;try{d=await n.register({optionsJSON:r});}catch(A){return bo(n,A,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!_r(d))return Ao();let{clientExtensionResults:l,...h}=d,y=await e.request("/passkey/verify-registration",{method:"POST",body:{response:h,name:a.value},fetchOptions:s,decode:A=>Xn(A,d.id,a.value)});return y.data&&t(),y}}}function yo(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function Ao(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function So(e){if(!e||typeof e!="object")return false;let t=e;return typeof t.id=="string"&&t.id.length>0&&typeof t.rawId=="string"&&t.rawId.length>0&&t.type==="public-key"&&!!t.response&&typeof t.response=="object"}function Dr(e){if(!So(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.authenticatorData=="string"&&typeof t.signature=="string"&&(t.userHandle===void 0||typeof t.userHandle=="string")}function _r(e){if(!So(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function Oo(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function bo(e,t,n,o){let i=Nr(t,"page does not have focus"),s=e.errorCode?.(t),a=s!==void 0?s==="ERROR_CEREMONY_ABORTED":wo(t)==="AbortError",c=n!=="AUTH_CANCELLED",r=Ur(s,wo(t),c);return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:i?"PASSKEY_PAGE_NOT_FOCUSED":a?n:s??"PASSKEY_BROWSER_ERROR",message:i?"Keep this page focused while completing the passkey prompt.":a?o:r}}}function Ur(e,t,n){switch(e){case "ERROR_INVALID_DOMAIN":case "ERROR_INVALID_RP_ID":return "Passkeys are not set up for this site\u2019s domain.";case "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED":return "This device already has a passkey for this account.";case "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEY_ALGS":case "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT":case "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT":return "This device cannot create a passkey for this site.";}return t==="NotAllowedError"?n?"No passkey was created. The prompt was dismissed or timed out.":"No passkey was used. This device may not have one saved for this site yet, or the prompt was dismissed.":t==="SecurityError"?"Passkeys are not set up for this site\u2019s domain.":n?"Passkey registration did not complete.":"Passkey sign-in did not complete."}function wo(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function Nr(e,t){let n=t.toLowerCase(),o=new Set,i=e;for(;i&&typeof i=="object"&&!o.has(i);){if(o.add(i),"message"in i&&typeof i.message=="string"&&i.message.toLowerCase().includes(n))return true;i="cause"in i?i.cause:void 0;}return false}function M(e){let t=new Uint8Array(e),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Q(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,o=t.padEnd(t.length+n,"="),i=atob(o),s=new ArrayBuffer(i.length),a=new Uint8Array(s);for(let c=0;c<i.length;c++)a[c]=i.charCodeAt(c);return s}function Z(){return zr.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var zr={stubThis:e=>e};function De(e){let{id:t}=e;return {...e,id:Q(t),transports:e.transports}}function _e(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 E=class extends Error{constructor({message:t,code:n,cause:o,name:i}){super(t,{cause:o}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=i??o.name,this.code=n;}};function ko({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 E({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 E({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 E({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 E({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 E({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new E({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return n.pubKeyCredParams.filter(i=>i.type==="public-key").length===0?new E({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new E({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(_e(o)){if(n.rp.id!==o)return new E({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new E({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 E({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 E({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 dt=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;}}},Ue=new dt;var Lr=["cross-platform","platform"];function Ne(e){if(e&&!(Lr.indexOf(e)<0))return e}async function To(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(!Z())throw new Error("WebAuthn is not supported in this browser");let o={...t,challenge:Q(t.challenge),user:{...t.user,id:Q(t.user.id)},excludeCredentials:t.excludeCredentials?.map(De)},i={};n&&(i.mediation="conditional"),i.publicKey=o,i.signal=Ue.createNewAbortSignal();let s;try{s=await navigator.credentials.create(i);}catch(u){throw ko({error:u,options:i})}if(!s)throw new Error("Registration was not completed");let{id:a,rawId:c,response:r,type:d}=s,l;typeof r.getTransports=="function"&&(l=r.getTransports());let h;if(typeof r.getPublicKeyAlgorithm=="function")try{h=r.getPublicKeyAlgorithm();}catch(u){pt("getPublicKeyAlgorithm()",u);}let y;if(typeof r.getPublicKey=="function")try{let u=r.getPublicKey();u!==null&&(y=M(u));}catch(u){pt("getPublicKey()",u);}let A;if(typeof r.getAuthenticatorData=="function")try{A=M(r.getAuthenticatorData());}catch(u){pt("getAuthenticatorData()",u);}return {id:a,rawId:M(c),response:{attestationObject:M(r.attestationObject),clientDataJSON:M(r.clientDataJSON),transports:l,publicKeyAlgorithm:h,publicKey:y,authenticatorData:A},type:d,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:Ne(s.authenticatorAttachment)}}function pt(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 Eo(){if(!Z())return ft.stubThis(new Promise(t=>t(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?ft.stubThis(new Promise(t=>t(false))):ft.stubThis(e.isConditionalMediationAvailable())}var ft={stubThis:e=>e};function Io({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 E({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else {if(e.name==="NotAllowedError")return new E({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let o=globalThis.location.hostname;if(_e(o)){if(n.rpId!==o)return new E({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new E({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new E({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 Po(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(!Z())throw new Error("WebAuthn is not supported in this browser");let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(De));let s={...t,challenge:Q(t.challenge),allowCredentials:i},a={};if(n){if(!await Eo())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');a.mediation="conditional",s.allowCredentials=[];}a.publicKey=s,a.signal=Ue.createNewAbortSignal();let c;try{c=await navigator.credentials.get(a);}catch(A){throw Io({error:A,options:a})}if(!c)throw new Error("Authentication was not completed");let{id:r,rawId:d,response:l,type:h}=c,y;return l.userHandle&&(y=M(l.userHandle)),{id:r,rawId:M(d),response:{authenticatorData:M(l.authenticatorData),clientDataJSON:M(l.clientDataJSON),signature:M(l.signature),userHandle:y},type:h,clientExtensionResults:c.getClientExtensionResults(),authenticatorAttachment:Ne(c.authenticatorAttachment)}}var Co={authenticate:e=>Po(e),register:e=>To(e),errorCode:e=>e instanceof E?e.code:void 0};function vo(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function gt(e){let t=await K(e,vo(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:Mr});return t.response.status===401?{required:false}:X(t,"consent status")}async function mt(e,t){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Consent version must be a positive integer.");return X(await K(e,vo(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:t})},maxResponseBytes:64*1024,decode:Fr}),"consent accept")}function Mr(e){let t=g(e),n=T(t.required),o=Vr(t.needsConsent),i=Do(t.version),s=xo(t.termsUrl),a=xo(t.privacyUrl);return {required:n,...o===void 0?{}:{needsConsent:o},...i===void 0?{}:{version:i},...s===void 0?{}:{termsUrl:s},...a===void 0?{}:{privacyUrl:a}}}function Fr(e){let t=g(e),n=Do(t.version);return {ok:T(t.ok),...n===void 0?{}:{version:n}}}function Vr(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function Do(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function xo(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var Hr=30;function qr(e){return typeof e?.exp=="number"?e.exp:null}function Kr(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 ht(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 c=a??"",r=t.get(c);r||(r={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},t.set(c,r));let d=s.forceRefresh===true;if(!d){let u=r.activeKey?r.cachedByKey.get(r.activeKey):null;if(u&&u.exp-Date.now()/1e3>Hr)return u.token;if(r.inflight)return r.inflight}let l=++r.sequence,h=()=>t.get(c)===r&&r.sequence===l,y=(async()=>{let u=a?`${e.projectBaseURL}/token/${encodeURIComponent(a)}`:`${e.projectBaseURL}/token`,f=await K(e,u,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:b=>Br(b,a!==null)});if(f.response.status===401)return h()&&o(),null;let m=X(f,"token"),w=m.policyVersion,S=m.token,N=Kr(S),H=qr(N);if(h())if(H!==null){let b=typeof N?.sub=="string"?N.sub:null,k=typeof N?.org_id=="string"?N.org_id:null;if(!a||b){let O=JSON.stringify([e.projectBaseURL,b,k,a,w]);r.cachedByKey.clear(),r.cachedByKey.set(O,{token:S,exp:H}),r.activeKey=O;}else i(r);}else i(r);return S})();if(d)return y;let A=y.finally(()=>{r.inflight===A&&(r.inflight=null);});return r.inflight=A,A}function o(){t.clear();}function i(s){s.cachedByKey.clear(),s.activeKey=null;}return {getToken:n,clear:o}}function Br(e,t){let n=g(e),o=R(n.token);if(o.length===0||o.length>32*1024)throw new TypeError("Invalid token response.");if(!t)return {token:o,policyVersion:0};let i=g(n.template);if(!Number.isSafeInteger(i.policyVersion)||i.policyVersion<1)throw new TypeError("Invalid token response.");return {token:o,policyVersion:i.policyVersion}}function jr(e){let t=ht(e),n=ho(e,t.clear,(a,c)=>Ro(a,c,Co)),o=ue(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),i=a=>(...c)=>(t.clear(),a(...c)),s={getConsentStatus:()=>gt(e),acceptConsent:a=>mt(e,a),getToken:t.getToken,waitlist:{join:(a,c)=>o.request("/waitlist",{method:"POST",body:a,fetchOptions:c,credentials:"omit"})},account:{...n.account,updateUnsafeMetadata:i(n.account.updateUnsafeMetadata),updateProfile:i(n.account.updateProfile),changeEmail:i(n.account.changeEmail),changePassword:i(n.account.changePassword),revokeSession:i(n.account.revokeSession),delete:i(n.account.delete)},signIn:{email:i(n.signIn.email),username:i(n.signIn.username),social:i(n.signIn.social),sso:n.signIn.sso,magicLink:n.signIn.magicLink,emailOtp:i(n.signIn.emailOtp),passkey:i(n.signIn.passkey)},signUp:{email:i(n.signUp.email)},emailOtp:{...n.emailOtp,verifyEmail:i(n.emailOtp.verifyEmail)},twoFactor:{enable:n.twoFactor.enable,disable:i(n.twoFactor.disable),verifyTotp:i(n.twoFactor.verifyTotp),verifyBackupCode:i(n.twoFactor.verifyBackupCode),sendOtp:n.twoFactor.sendOtp,verifyOtp:i(n.twoFactor.verifyOtp),generateBackupCodes:n.twoFactor.generateBackupCodes},phoneOtp:{prepare:n.phoneOtp.prepare,start:n.phoneOtp.start,verify:i(n.phoneOtp.verify)},signOut:i(n.signOut)};return {...n,...s}}async function Jr(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let t=await Gr(),n=e.challengeRequired?await t.solvePow(e.challenge,e.difficulty):null,o=e.turnstile.required?await t.getTurnstileToken($r(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...n?{challengeToken:e.challengeToken,nonce:n.nonce}:{},...o?{turnstileToken:o}:{}}}async function Gr(){return import('@akedly/shield')}function $r(e){if(!e)throw new Error("Akedly Shield did not provide a Turnstile site key.");return e}async function Wr(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return X(await K(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:o=>Yr(o,e)}),"public-config")}function Yr(e,t){let n=B(e),o=n.environmentId,i=n.environmentType,s=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Xr(n.applicationId)||o!==t.decoded.projectId||i!=="development"&&i!=="production"||n.authBaseUrl!==s)throw F();let a=U(n.branding),c=U(n.legal);if(!yt(n.enabledMethods,64)||!yt(n.socialProviders,64)||!Uo(a,["appName","logoUrl","primaryColor"])||a.showAppName!==void 0&&typeof a.showAppName!="boolean"||a.alignment!==void 0&&a.alignment!=="left"&&a.alignment!=="center"&&a.alignment!=="right"||a.theme!==void 0&&a.theme!=="light"&&a.theme!=="dark"&&a.theme!=="system"||!Uo(c,["termsUrl","privacyUrl"])||!Number.isSafeInteger(c.version)||c.version<0||typeof c.required!="boolean")throw F();if(n.socialProviderClientIds!==void 0){let r=U(n.socialProviderClientIds);if(Object.keys(r).length>64||Object.values(r).some(d=>typeof d!="string"||d.length>2048))throw F()}if(!J(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!_o(n.turnstileSiteKey)||!_o(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw F();if(n.jwtIssuer!==null){let r=U(n.jwtIssuer);if(r.issuer!==s||r.jwksUrl!==`${s}/jwks`||r.aud!==t.decoded.projectId)throw F()}if(n.signUp!==void 0){let r=U(n.signUp).mode;if(typeof r!="string"||!["open","restricted","allowlist","waitlist"].includes(r))throw F()}if(n.authentication!==void 0&&Qr(n.authentication),n.emailVerification!==void 0){let r=U(n.emailVerification);if(!J(r,["required"])||r.method!=="link"&&r.method!=="code")throw F()}if(n.userModel!==void 0&&!J(U(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw F();if(n.mfa!==void 0){let r=U(n.mfa);if(!J(r,["totp","required","backupCodes"])||(r.required===true||r.backupCodes===true)&&r.totp!==true)throw F()}return n}function Xr(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function F(){return new TypeError("public-config returned an invalid response")}function U(e){if(!e||typeof e!="object"||Array.isArray(e))throw F();return e}function _o(e){return e===null||typeof e=="string"&&e.length<=4096}function Qr(e){let t=U(e),n=U(t.email),o=U(t.password),i=o.minLength!==void 0||o.maxLength!==void 0;if(!J(n,["signUp"])||!yt(n.signIn,3)||n.signIn.some(s=>s!=="password"&&s!=="magic_link"&&s!=="email_otp")||!J(U(t.phone),["signUp","signIn"])||!J(o,["signUp","add"])||i&&(!Number.isSafeInteger(o.minLength)||!Number.isSafeInteger(o.maxLength)||o.minLength<1||o.maxLength>4096||o.minLength>o.maxLength)||!J(U(t.passkey),["signIn","add"])||!Zr(U(t.passkey).relyingPartyId)||!J(U(t.username),["collectOnSignUp","signIn"]))throw F()}function Zr(e){return e==null||typeof e=="string"}function J(e,t){return t.every(n=>typeof e[n]=="boolean")}function Uo(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function yt(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length<=128)&&new Set(e).size===e.length}var fe=class extends Error{constructor(n,o){super(n);this.cause=o;this.name="AuthOwlError";}cause},At=class extends fe{constructor(n,o){super(`Rate limited. Retry after ${n}s.`,o);this.retryAfterSeconds=n;this.name="RateLimitedError";}retryAfterSeconds},Ot=class extends fe{constructor(t="invalid publishable key",n){super(t,n),this.name="InvalidKeyError";}};var No=["en","ar"];function es(e){return e==="ar"?"rtl":"ltr"}function ts(e){return typeof e=="string"&&No.includes(e)}
|
|
3
|
-
exports.AUTH_CHALLENGE_HEADER=qt;exports.AuthOwlError=
|
|
1
|
+
'use strict';var zo=Object.defineProperty;var bt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Lo=(e,t)=>{for(var n in t)zo(e,n,{get:t[n],enumerable:true});};function de(){return typeof window<"u"&&typeof document<"u"&&typeof crypto<"u"&&typeof crypto.subtle?.digest=="function"}var Ye=bt(()=>{});var xe={};Lo(xe,{beginCrossSiteSignIn:()=>Ir,challengeFor:()=>lo,completeCrossSiteSignIn:()=>Pr,takeHandoffCode:()=>lt});function uo(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function lo(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return uo(new Uint8Array(t))}function kr(){return uo(crypto.getRandomValues(new Uint8Array(wr)))}function po(e,t){let n=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${co}=${e}; Path=/; Max-Age=${t}; SameSite=Lax${n}`;}function Tr(){for(let e of document.cookie.split(";")){let t=e.indexOf("=");if(!(t<0)&&e.slice(0,t).trim()===co)return e.slice(t+1).trim()||null}return null}function Er(){po("",0);}function ao(e){return new URL(e,window.location.href).toString()}async function Ir(e,t){let n=t.callbackURL?ao(t.callbackURL):null;if(n&&new URL(n).origin!==window.location.origin)return null;let o=kr(),i=new URL(`${e.projectBaseURL}/session/start`);if(i.searchParams.set("pk",e.publishableKey),i.searchParams.set("kind",t.kind),t.kind==="social")i.searchParams.set("provider",t.provider),t.scopes?.length&&i.searchParams.set("scopes",t.scopes.join(",")),t.loginHint&&i.searchParams.set("loginHint",t.loginHint),t.requestSignUp!==void 0&&i.searchParams.set("requestSignUp",t.requestSignUp?"1":"0");else for(let a of Sr){let c=t[a];c&&i.searchParams.set(a,c);}let s=`${window.location.origin}${window.location.pathname}${window.location.search}`;i.searchParams.set("cb",n??s);for(let[a,c]of [["err",t.errorCallbackURL],["new",t.newUserCallbackURL]])c&&i.searchParams.set(a,ao(c));return i.searchParams.set("challenge",await lo(o)),po(o,Rr),i.toString()}function lt(e){if(typeof window>"u")return null;let t=window.location.hash;if(!t.includes(ut))return null;let n=new URLSearchParams(t.replace(/^#/,"")),o=n.get(ut);if(!o||e!==void 0&&o!==e)return null;n.delete(ut);let i=n.toString();return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${i?`#${i}`:""}`),o}async function Pr(e,t,n){if(!de())return false;let o=n??lt();if(!o)return false;n&<(n);let i=Tr();if(Er(),!i)return false;t.beginSession({remember:true});let{error:s}=await e.request("/session/exchange",{method:"POST",body:{code:o,verifier:i}});return s===null}var co,ut,wr,Rr,Sr,ve=bt(()=>{Ye();co="authowl_handoff_verifier",ut="authowl_code",wr=32,Rr=900,Sr=["email","providerId","domain","organizationSlug"];});var Mo=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,Fo=/^sk_/i;function ze(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(Fo.test(e))throw new Error("A secret key was passed where a publishable key was expected. Never embed secret keys in client code.");let t=Mo.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1].toLowerCase(),env:t[2].toLowerCase(),projectId:t[3].toLowerCase()}}function Vo(e,t){let n=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}var wt=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function Le(e,t){throw new Error(`${e}: ${t}`)}function Rt(e,t){let n;try{n=new URL(String(e));}catch{throw new TypeError("Transport URL must be absolute.")}if(n.username||n.password||n.hash)throw new TypeError("Transport URL must not contain credentials or a fragment.");let o=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&wt.test(o)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function St(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&Le("apiUrl","origin required");let n;try{n=new URL(e);}catch{Le("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!wt.test(e))&&Le("apiUrl","HTTPS required except exact loopback"),n.origin}function G(e,t){try{return e?.getItem(t)??null}catch{return null}}function q(e,t,n){try{n===null?e?.removeItem(t):e?.setItem(t,n);}catch{}}function V(){try{return globalThis.localStorage}catch{return}}function Y(){try{return globalThis.sessionStorage}catch{return}}var Ho="authowl.session-challenge",qo=e=>`${Ho}.${e}`,Ko="set-auth-challenge",Me="x-authowl-challenge";function Bo(e){let t=e.get(Me);return re(t)?Et(t).some(([n,o])=>n.endsWith(".dont_remember")&&o.length>0):false}var Tt="INVALID_TWO_FACTOR_COOKIE",jo=2048,re=e=>e!==null&&e.length<=jo,kt=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function Et(e){let t=[];for(let n of e.split(";")){let o=n.trimStart(),i=o.indexOf("=");i<=0||t.push([o.slice(0,i).trimEnd(),o.slice(i+1)]);}return t}function It(e){let t=qo(e),n=new Map;function o(){return n.size===0?null:[...n].map(([c,r])=>`${c}=${r}`).join("; ")}function i(){let c=o();q(Y(),t,re(c)?c:null);}function s(c){for(let[r,d]of Et(c))kt.test(r)&&(d===""?n.delete(r):kt.test(d)&&n.set(r,d));}let a=G(Y(),t);return re(a)&&s(a),{presentOn(c){let r=o();c.delete(Me),re(r)&&c.set(Me,r);},observe(c){let r=c.get(Ko);re(r)&&(s(r),i());},clear(){n.clear(),i();}}}var Fe="set-auth-token",Ve="x-authowl-session-transport",He="bearer";var Jo="authowl.session-token",Go="authowl.cookie-transport",Ct="ok",xt="bearer",$o=e=>`${Jo}.${e}`,Wo=e=>`${Go}.${e}`;function Yo(e){return e===Ct?"cookies":e===xt?"bearer":"unknown"}function Xo(e){return e==="cookies"?Ct:e==="bearer"?xt:null}function Qo(e){let t=$o(e),n=Wo(e),o=It(e),i=null,s=false,a=null,c=Yo(G(V(),n)),r=()=>c==="unknown",d=0,l=null,h=false;function y(){let O=G(Y(),t);if(O!==null)return s=true,O;let x=G(V(),t);return x!==null?(s=false,x):null}i=y(),i!==null&&r()&&(h=true);function A(){if(!(!h||!l)){h=false;try{l();}catch{}}}function u(){let O=c==="bearer"?i:null,[x,me]=s?[Y(),V()]:[V(),Y()];q(me,t,null),q(x,t,O);}function f(O){O!==null&&a!==null&&(s=a,a=null),i=O,u(),O!==null&&r()&&(h=true,A());}function m(O){c=O,q(V(),n,Xo(O));}function w(){m("unknown"),h=false;}function S(){return i===null&&(i=y()),i}function N(){let O=y();return O!==null&&(i=O),i}function H(O){N()===O&&u();}function b(){d+=1,a=null,s=false,f(null),o.clear(),w();}let k=()=>c!=="cookies";return {hasToken:()=>S()!==null,declareOn(O){if(O.has("authorization"))return false;let x=S();return !x&&!k()?false:(x&&O.set("authorization",`Bearer ${x}`),O.set(Ve,He),o.presentOn(O),true)},wantsToken:k,needsProbe:r,observe(O){let x=O.get(Fe);x&&f(x),o.observe(O);},dropChallenge:o.clear,measureWith(O){l=O,A();},beginRead(){let O=S(),x=d;return {carriedToken:O!==null,endIfDead(){O!==null&&N()===O&&d===x&&b();},recordCookieVerdict(me){if(d===x&&r()){if(m(me?"cookies":"bearer"),me){f(null);return}H(O);}}}},beginSession({remember:O}){d+=1,a=!O,o.clear(),w();},endSession:b}}var Pt=new Map;function vt(e){let t=Pt.get(e);if(t)return t;let n=Qo(e);return Pt.set(e,n),n}function Zo(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function Dt(e,t){let n=vt(e),o=(a,c)=>(t??globalThis.fetch)(a,c);return {fetch:async(a,c)=>{if(c?.credentials==="omit"||!n.wantsToken())return o(a,c);let r=Zo(a,c),d=n.declareOn(r),l=await o(a,{...c,headers:r});return d&&n.observe(l.headers),l},probe:o,tokens:n}}function _t(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=ze(e.publishableKey),n=St(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:n,decoded:t,projectBaseURL:`${n}/api/projects/${t.projectId}/auth`}}function ei(e){let t=_t(e),{fetch:n,...o}=Dt(t.decoded.projectId,e.fetch);return {...e,...t,fetch:n,session:o}}var qe="authowl_invitation",Ke="authowl.invitation-claim",Ut=/^[A-Za-z0-9_-]{1,128}$/,Nt=10080*60*1e3;function ti(e=Date.now()){if(typeof window>"u")return se(e);let t;try{t=new URL(window.location.href);}catch{return se(e)}let n=t.searchParams.get(qe);if(n===null)return se(e);t.searchParams.delete(qe);try{window.history.replaceState(window.history.state,"",t.toString());}catch{}if(!Ut.test(n))return se(e);let o={id:n,capturedAt:e};return q(V(),Ke,JSON.stringify(o)),o}function se(e=Date.now()){let t=G(V(),Ke);if(t===null)return null;let n;try{n=JSON.parse(t);}catch{return ae(),null}if(typeof n!="object"||n===null)return ae(),null;let{id:o,capturedAt:i}=n;return typeof o!="string"||!Ut.test(o)||typeof i!="number"||e-i>Nt?(ae(),null):{id:o,capturedAt:i}}function ae(){q(V(),Ke,null);}function ni(e){let t=e?.enabledMethods??["password"],n=t.includes("password"),o=t.includes("passkey"),i=e?.authentication,s=e?.mfa;return {emailSignUp:i?.email.signUp??t.some(a=>a==="password"||a==="magic_link"||a==="email_otp"),passwordSignUp:i?.password.signUp??n,phoneSignUp:i?.phone.signUp??t.includes("phone_otp"),passwordSignIn:i?.email.signIn.includes("password")??n,passwordMinLength:i?.password.minLength??8,passwordMaxLength:i?.password.maxLength??128,magicLinkSignIn:i?.email.signIn.includes("magic_link")??t.includes("magic_link"),emailOtpSignIn:i?.email.signIn.includes("email_otp")??t.includes("email_otp"),phoneSignIn:i?.phone.signIn??t.includes("phone_otp"),usernameSignIn:i?.username.signIn??false,collectUsername:i?.username.collectOnSignUp??false,passkeySignIn:i?.passkey.signIn??o,passkeyAdd:i?.passkey.add??o,firstLastName:e?.userModel?.firstLastName??false,emailChange:e===null?false:e.userModel?.emailChange??true,accountDeletion:e?.userModel?.accountDeletion??e?.accountDeletion??false,emailVerificationRequired:e?.emailVerification?.required??e?.requireEmailVerification??false,emailVerificationMethod:e?.emailVerification?.method??"link",totp:s?.totp??e?.twoFactor??false,mfaRequired:s?.required??e?.mfaRequired??false,backupCodes:s?.backupCodes??e?.twoFactor??false,legacyNameField:e?.authentication===void 0}}var oi=1e4,ii=1024*1024,D=class extends Error{kind;requestId;constructor(t,n){super(pi(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},Mt=new WeakSet;function _(e,t){let n=new D(e,t);return Mt.add(n),n}async function Ft({fetchImpl:e,url:t,init:n={},timeoutMs:o=oi,maxResponseBytes:i=ii,allowHttpLoopback:s=false,decode:a}){Lt(o,"timeoutMs"),Lt(i,"maxResponseBytes");let c=Rt(t,{allowHttpLoopback:s}),r=n.signal,d=new AbortController,l=null,h,y=new Promise(m=>{h=m;}),A=m=>{l===null&&(l=m,h({type:"abort",kind:m}),d.abort());},u=()=>A("aborted");r?.addEventListener("abort",u,{once:true});let f=setTimeout(()=>A("timeout"),o);r?.aborted&&u();try{if(l!==null)throw _(l);let m;try{m=await Promise.race([e(c.toString(),{...n,redirect:"error",signal:d.signal}).then(k=>({type:"response",response:k})),y]);}catch{throw _(l??"network")}if(m.type==="abort")throw _(m.kind);if(!ri(m.response))throw _("invalid_response");let w=m.response,S=di(w.headers),N=await si(w,i,y,()=>l,S),H=ui(w,N,S),b;try{b=w.ok&&a?a(H,Object.freeze({status:w.status})):H;}catch{throw _("invalid_response",S)}return {response:w,data:b,...S===void 0?{}:{requestId:S}}}catch(m){throw m instanceof D&&Mt.has(m)?m:_(l??"network")}finally{clearTimeout(f),r?.removeEventListener("abort",u);}}function ri(e){if(!e||typeof e!="object")return false;let t=e;return Number.isInteger(t.status)&&t.status>=0&&t.status<=599&&typeof t.statusText=="string"&&typeof t.ok=="boolean"&&typeof t.headers?.get=="function"&&(t.body===null||typeof t.body=="object"&&typeof t.body?.getReader=="function"&&typeof t.body.cancel=="function")}async function si(e,t,n,o,i){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw zt(e.body),_("invalid_response",i);if(Number(s)>t)throw zt(e.body),_("response_too_large",i)}if(!e.body)return "";let a;try{a=e.body.getReader();}catch{throw _("network",i)}let c=[],r=0,d=null;try{for(;;){let y;try{y=await Promise.race([a.read(),n]);}catch{d=_(o()??"network",i);break}if(ai(y)){d=_(y.kind,i);break}let{done:A,value:u}=y;if(A)break;if(u.byteLength!==0){if(r+=u.byteLength,r>t){d=_("response_too_large",i);break}c.push(u);}}}finally{d&&ci(a);try{a.releaseLock();}catch{}}if(d)throw d;let l=new Uint8Array(r),h=0;for(let y of c)l.set(y,h),h+=y.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw _("invalid_response",i)}}function ai(e){return "type"in e&&e.type==="abort"}function zt(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function ci(e){try{e.cancel().catch(()=>{});}catch{}}function ui(e,t,n){if(e.status===204||e.status===205)return null;let o=li(e.headers.get("content-type"));if(!e.ok&&(!o||t.length===0))return null;if(!o||t.length===0)throw _("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw _("invalid_response",n)}}function li(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function di(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Lt(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function pi(e){switch(e){case "aborted":return "The request was cancelled.";case "timeout":return "The request timed out.";case "response_too_large":return "The response exceeded the allowed size.";case "invalid_response":return "The service returned an invalid response.";case "network":return "The network request could not be completed."}}var he=class extends Error{status;requestId;constructor(t,n,o){super(`${t} request failed with status ${n.status}.`),this.name="AuthOwlHttpError",this.status=n.status,this.requestId=o;}};function K(e,t,n={}){let o=new Headers(n.init?.headers);return o.set("x-publishable-key",e.publishableKey),Ft({fetchImpl:e.fetch,url:t,init:{...n.init,headers:o},allowHttpLoopback:e.decoded.env==="test",...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.maxResponseBytes===void 0?{}:{maxResponseBytes:n.maxResponseBytes},...n.decode===void 0?{}:{decode:n.decode}})}function X(e,t){if(!e.response.ok)throw new he(t,e.response,e.requestId);return e.data}var qt="x-authowl-turnstile-token",fi=1e4,gi=32,mi=2e4;function ee(e,t){return {post:(n,o,i,s)=>e.request(n,{method:"POST",body:o,fetchOptions:i,decode:s}),mutation:async(n,o)=>{let i=await n;return i.error===null&&(o===void 0||i.data!==null&&o(i.data))&&t(),i}}}function ue(e,t=e.projectBaseURL){return {async request(n,o={}){let i=Ai(t,n,o.query),s=o.method??(o.body===void 0?"GET":"POST"),a=new Headers(o.fetchOptions?.headers);o.fetchOptions?.authChallengeToken&&a.set(qt,o.fetchOptions.authChallengeToken),o.body!==void 0&&a.set("content-type","application/json");let c={method:s,headers:a,credentials:o.credentials??"include",...o.body===void 0?{}:{body:JSON.stringify(o.body)}},r=Object.freeze({method:s,path:n});await o.fetchOptions?.onRequest?.(r);let d=yi(s,o.fetchOptions),l;try{l=await hi(e,i,{...c,signal:o.fetchOptions?.signal},d);}catch(m){let w=Ht(m);return await o.fetchOptions?.onError?.(Be(r,w,wi(m))),{data:null,error:w}}let{response:h,requestId:y}=l,A=ki(n,l.data),u=A;if(h.ok)try{u=Je(A),o.decode&&(u=o.decode(u));}catch{let m=Ht(new D("invalid_response",y));return await o.fetchOptions?.onError?.(Be(r,m,"invalid_response")),{data:null,error:m}}let f=Object.freeze({...r,status:h.status,...y===void 0?{}:{requestId:y}});if(await o.fetchOptions?.onResponse?.(f),!h.ok){let m=Oi(h,A,y);return m.code===Tt&&e.session.tokens.dropChallenge(),await o.fetchOptions?.onError?.(Be(r,m,"api")),{data:null,error:m}}return await o.fetchOptions?.onSuccess?.(f),{data:u,error:null}}}}async function hi(e,t,n,o){let i=Date.now()+fi;for(let s=0;s<o;s+=1){let a=i-Date.now();if(a<=0)throw new D("timeout");try{let c=await K(e,t,{init:n,timeoutMs:Math.max(1,Math.ceil(a))});if(c.response.status<500||s===o-1)return c}catch(c){if(s===o-1||!(c instanceof D)||c.kind!=="network")throw c}await Ri(50*2**s,n.signal,i);}throw new D("network")}function yi(e,t){if(e!=="GET"||t?.authChallengeToken)return 1;let n=t?.retry;return typeof n!="number"||!Number.isFinite(n)?1:Math.min(Math.max(Math.trunc(n),0),3)+1}function Ai(e,t,n){let o=new URL(`${e}${t.startsWith("/")?t:`/${t}`}`);for(let[i,s]of Object.entries(n??{}))s!==void 0&&o.searchParams.set(i,String(s));return o.toString()}function Oi(e,t,n){let o=ce(t)?t:{},i=bi(o,e.headers);return {status:e.status,statusText:e.statusText,code:typeof o.code=="string"?o.code:void 0,...n===void 0?{}:{requestId:n},...typeof o.current_version=="number"?{currentVersion:o.current_version}:{},...i!==void 0?{retryAfterSeconds:i}:{},message:typeof o.message=="string"?o.message:typeof o.error=="string"?o.error:typeof o.detail=="string"?o.detail:e.statusText||"Request failed"}}function bi(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??Vt(t.get("retry-after"))??Vt(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function Vt(e){if(!e)return;let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)?n:void 0}function Ht(e){let t=e instanceof D?e.kind:"network";return {status:0,...{aborted:{statusText:"ABORTED",code:"REQUEST_ABORTED",message:"The request was cancelled."},timeout:{statusText:"TIMEOUT",code:"REQUEST_TIMEOUT",message:"The request timed out."},response_too_large:{statusText:"INVALID_RESPONSE",code:"RESPONSE_TOO_LARGE",message:"The service response was too large."},invalid_response:{statusText:"INVALID_RESPONSE",code:"INVALID_RESPONSE",message:"The service returned an invalid response."},network:{statusText:"FETCH_ERROR",code:"FETCH_ERROR",message:"Network request failed."}}[t],...e instanceof D&&e.requestId?{requestId:e.requestId}:{}}}function Be(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function wi(e){return e instanceof D?e.kind:"network"}function Ri(e,t,n){return new Promise((o,i)=>{if(t?.aborted){i(new D("aborted"));return}let s=n-Date.now();if(s<=0){i(new D("timeout"));return}let a=Math.min(e,s),c=()=>{clearTimeout(r),i(new D("aborted"));},r=setTimeout(()=>{t?.removeEventListener("abort",c),Date.now()>=n?i(new D("timeout")):o();},a);t?.addEventListener("abort",c,{once:true}),t?.aborted&&c();})}function Je(e,t="",n=0,o={nodes:0}){if(o.nodes+=1,n>gi||o.nodes>mi)throw new Error("response traversal limit exceeded");if(typeof e=="string"&&/^(?:createdAt|updatedAt|expiresAt)$/.test(t)){let i=new Date(e);return Number.isNaN(i.getTime())?e:i}return Array.isArray(e)?e.map(i=>Je(i,"",n+1,o)):ce(e)?Object.fromEntries(Object.entries(e).map(([i,s])=>[i,Si(i)?s:Je(s,i,n+1,o)])):e}function Si(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function ki(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(i=>ce(i)?je(i):i);if(!ce(t))return t;let o=e==="/change-password"||e==="/passkey/verify-authentication"||e==="/phone-otp/verify"||e==="/sign-up/email"||e.startsWith("/sign-in/")||e.startsWith("/two-factor/verify-")?je(t):t;return e==="/sign-up/email"&&!("sessionCreated"in o)&&(o={...o,sessionCreated:typeof t.token=="string"&&t.token.length>0}),(e==="/get-session"||e==="/passkey/verify-authentication")&&ce(o.session)&&(o={...o,session:je(o.session)}),o}function je(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function ce(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}var Ti=new Set(["__proto__","constructor","prototype"]);function g(e){(!e||typeof e!="object"||Array.isArray(e))&&p();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&p(),e}function R(e){return typeof e!="string"&&p(),e}function T(e){return typeof e!="boolean"&&p(),e}function P(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&p(),e}function le(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&p(),[...e]}function I(e,t){let n=e[t];return n==null||typeof n=="string"?n:p()}function Kt(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:p()}function L(e){let t=g(e),n=t.email;return n!==null&&typeof n!="string"&&p(),{id:R(t.id),email:n,emailVerified:T(t.emailVerified),createdAt:P(t.createdAt),updatedAt:P(t.updatedAt),...z("phoneNumber",I(t,"phoneNumber")),...z("username",I(t,"username")),...z("displayUsername",I(t,"displayUsername")),...z("firstName",I(t,"firstName")),...z("lastName",I(t,"lastName")),...z("name",I(t,"name")),...z("image",I(t,"image")),...z("twoFactorEnabled",Kt(t,"twoFactorEnabled"))}}function ye(e){let t=g(e),n=t.membership;return {id:R(t.id),userId:R(t.userId),expiresAt:P(t.expiresAt),...z("activeOrganizationId",I(t,"activeOrganizationId")),...z("activeTeamId",I(t,"activeTeamId")),...z("membership",n==null?n:Ei(n)),...z("pendingMfaEnrollment",Kt(t,"pendingMfaEnrollment"))}}function p(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function B(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&p(),$e(e,t,n)}function $e(e,t=20,n=1e4){return Ge(e,0,{nodes:0},t,n)}function Ei(e){let t=g(e);return {role:R(t.role),...t.roles===void 0?{}:{roles:le(t.roles)},permissions:le(t.permissions),...t.teams===void 0?{}:{teams:le(t.teams)}}}function Ge(e,t,n,o,i){if(n.nodes+=1,(t>o||n.nodes>i)&&p(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||p(),e;if(Array.isArray(e))return e.map(c=>Ge(c,t+1,n,o,i));(!e||typeof e!="object")&&p();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&p();let a={};for(let[c,r]of Object.entries(e))Ti.has(c)&&p(),a[c]=Ge(r,t+1,n,o,i);return a}function z(e,t){return t===void 0?{}:{[e]:t}}function Bt({http:e,probe:t,tokens:n,channelName:o}){let i=new Set,s=null,a=null,c=null,r=null,d=null,l,h=b=>{u(b);};l={data:null,isPending:true,isRefetching:false,error:null,refetch:h};function y(b){l=b;for(let k of i)k();}async function A(b){return e.request("/get-session",{query:b?.query,decode:We})}function u(b){if(b?.query?.disableCookieCache===true)return f(b);if(r)return r;let k=f(b).finally(()=>{r===k&&(r=null);});return r=k,k}async function f(b){c?.abort();let k=new AbortController;c=k,y({...l,isPending:l.data===null&&l.error===null,isRefetching:l.data!==null});let O=n.beginRead(),x=await e.request("/get-session",{query:b?.query,fetchOptions:{signal:k.signal},decode:We});if(c===k&&(c=null,y({data:x.data,error:x.error,isPending:false,isRefetching:false,refetch:h}),x.error===null)){if(x.data===null){O.endIfDead();return}await m(O);}}async function m(b){if(n.needsProbe()){if(!b.carriedToken){b.recordCookieVerdict(true);return}return d||w(b)}}function w(b){let k=t.request("/get-session",{query:{disableCookieCache:true},decode:We}).then(O=>{d===k&&O.error===null&&b.recordCookieVerdict(O.data!==null);}).finally(()=>{d===k&&(d=null);});return d=k,k}function S(){s?.postMessage({type:"session-changed"});}function N(){if(typeof window>"u"||a)return;let b=()=>{u();},k=()=>{document.visibilityState==="visible"&&u();};window.addEventListener("focus",b),document.addEventListener("visibilitychange",k),typeof BroadcastChannel<"u"&&(s=new BroadcastChannel(o),s.addEventListener("message",b)),a=()=>{window.removeEventListener("focus",b),document.removeEventListener("visibilitychange",k),s?.close(),s=null,a=null;};}function H(b){return i.add(b),i.size===1&&(N(),u()),()=>{if(i.delete(b),i.size===0){let k=c;c=null,r=null,k?.abort(),a?.();}}}return n.measureWith(()=>{n.needsProbe()&&w(n.beginRead());}),{store:{subscribe:H,getSnapshot:()=>l},getSession:A,notifyMutation(){S(),d&&d.catch(()=>{}).then(()=>{!n.needsProbe()&&n.hasToken()&&S();}),i.size>0&&u({query:{disableCookieCache:true}});}}}function We(e){if(e===null)return null;let t=g(e);return (t.session===void 0||t.user===void 0)&&p(),{session:ye(t.session),user:L(t.user)}}Ye();function Xe(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return `${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}async function jt(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:Gt})}async function Jt(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:Gt})}function Gt(e){let t=g(e),n=B(t.public_metadata),o=B(t.unsafe_metadata);if(!Number.isSafeInteger(t.metadata_version)||t.metadata_version<0)throw new TypeError("Invalid AuthOwl metadata response");return {publicMetadata:n,unsafeMetadata:o,metadataVersion:t.metadata_version}}function Wt(e,t){let{post:n,mutation:o}=ee(e,t);return {getMetadata:i=>jt(e,i),updateUnsafeMetadata:(i,s)=>Jt(e,i,s),updateProfile:(i,s)=>o(n("/update-user",i,s,pe)),changeEmail:(i,s)=>o(n("/change-email",i,s,pe)),changePassword:(i,s)=>o(n("/change-password",i,s,Ii)),listSessions:i=>e.request("/list-sessions",{fetchOptions:i,decode:Pi}),revokeSession:({sessionId:i},s)=>o(n("/revoke-session",{sessionId:i},s,pe)),revokeOtherSessions:i=>o(n("/revoke-other-sessions",{},i,pe)),listSocialAccounts:async i=>{let s=await e.request("/list-accounts",{fetchOptions:i,decode:Ci});if(!s.data)return {data:null,error:s.error};let a=s.data.length>1;return {...s,data:s.data.filter(c=>c.providerId!=="credential").map(c=>({...c,canUnlink:a}))}},linkSocial:(i,s)=>n("/link-social",i,s,xi),unlinkSocial:(i,s)=>o(n("/unlink-account",i,s,pe)),delete:(i={},s)=>o(n("/delete-user",i,s,vi))}}function pe(e){let t=g(e);return {status:T(t.status)}}function Ii(e){let t=g(e);return {user:L(t.user)}}function Pi(e){return Array.isArray(e)||p(),e.map(t=>{let n=g(t);return {id:R(n.id),userId:R(n.userId),createdAt:P(n.createdAt),updatedAt:P(n.updatedAt),expiresAt:P(n.expiresAt),...$t("ipAddress",I(n,"ipAddress")),...$t("userAgent",I(n,"userAgent"))}})}function Ci(e){return Array.isArray(e)||p(),e.map(t=>{let n=g(t);return {id:R(n.id),userId:R(n.userId),providerId:R(n.providerId),accountId:R(n.accountId),scopes:le(n.scopes),createdAt:P(n.createdAt),updatedAt:P(n.updatedAt)}})}function xi(e){let t=g(e);return {url:R(t.url),redirect:T(t.redirect)}}function vi(e){let t=g(e);return {success:T(t.success),message:R(t.message)}}function $t(e,t){return t===void 0?{}:{[e]:t}}function Ae(e,t){return !e||!t?false:e.permissions.includes(t)}function Yt(e,t){return !e||!t?false:e.teams?.includes(t)??false}function Xt(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function Oe(e,t){if(!e)return false;let{role:n,permission:o,teamId:i}=t;return !(n===void 0&&o===void 0&&i===void 0||n!==void 0&&!Xt(e,n)||o!==void 0&&!e.permissions.includes(o)||i!==void 0&&!Yt(e,i))}function Di(e){return {has:t=>Oe(e,t),hasPermission:t=>Ae(e,t.permission)}}var _i=new Set(["pending","accepted","rejected","canceled"]),Qe=1e4;function te(e,t,n){let o=g(e),i={id:C(o.id),name:C(o.name),slug:C(o.slug),createdAt:P(o.createdAt),...be("logo",I(o,"logo")),...be("metadata",o.metadata===void 0?void 0:$e(o.metadata))};return $(i.id,t),$(i.slug,n),i}function Qt(e){return W(e,te)}function Ze(e,t,n){return e===null?null:(t===null&&p(),te(e,t,n))}function Zt(e,t,n){if(e===null)return null;let o=g(e),i=te(o,t,n);return {...i,members:W(o.members,s=>fn(s,i.id)),invitations:W(o.invitations,s=>j(s,void 0,i.id))}}function en(e,t){let n=W(e,o=>pn(o));return Re(n.map(o=>o.organizationId),t),n}function tn(e,t,n){return e===null?null:(t===null&&p(),pn(e,t,n))}function nn(e,t){let n=g(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&p(),{members:Ui(n.members,t),total:n.total}}function j(e,t,n){let o=g(e),i=C(o.status);_i.has(i)||p();let s={id:C(o.id),organizationId:C(o.organizationId),email:we(o.email),role:C(o.role),status:i,inviterId:C(o.inviterId),expiresAt:P(o.expiresAt),createdAt:P(o.createdAt)};return $(s.id,t),$(s.organizationId,n),s}function on(e,t){let n=W(e,o=>j(o));return Re(n.map(o=>o.organizationId),t),n}function rn(e){return W(e,t=>{let n=g(t);return {...j(n),organizationName:we(n.organizationName)}})}function sn(e,t){let n=g(e);return {...j(n,t),organizationName:C(n.organizationName),organizationSlug:C(n.organizationSlug),inviterEmail:gn(n.inviterEmail)}}function an(e,t){let n=g(e),o=j(n.invitation,t);return {invitation:o,member:ne(n.member,void 0,o.organizationId)}}function cn(e,t){let n=g(e);return n.member!==null&&p(),{invitation:n.invitation===null?null:j(n.invitation,t),member:null}}function un(e,t){return e===null?null:j(e,t)}function ln(e,t,n){let o=g(e);return {member:ne(o.member,n,t)}}function ne(e,t,n){let o=g(e),i={id:C(o.id),organizationId:C(o.organizationId),userId:C(o.userId),role:C(o.role),createdAt:P(o.createdAt),...o.user===void 0?{}:{user:mn(o.user)}};return $(i.id,t),$(i.organizationId,n),i}function dn(e,t){let n=W(e,o=>{let i=g(o);return {organizationId:C(i.organizationId),data:{role:C(i.role),...be("permission",i.permission===void 0?void 0:Ni(i.permission))}}});return Re(n.map(o=>o.organizationId),t),n.map(o=>o.data)}function pn(e,t,n){let o=g(e),i=o.updatedAt,s={id:C(o.id),name:we(o.name),organizationId:C(o.organizationId),createdAt:P(o.createdAt),...i===void 0?{}:{updatedAt:P(i)}};return $(s.id,t),$(s.organizationId,n),s}function fn(e,t){let n=g(e);return {...ne(n,void 0,t),user:mn(n.user)}}function Ui(e,t){let n=W(e,o=>fn(o));return Re(n.map(o=>o.organizationId),t),n}function Ni(e){let t=g(e),n={};for(let[o,i]of Object.entries(t))(o==="__proto__"||o==="constructor"||o==="prototype"||o.length===0||o.length>Qe||!Array.isArray(i))&&p(),n[o]=i.map(s=>C(s));return n}function C(e){let t=R(e);return (t.length===0||t.length>Qe)&&p(),t}function we(e){if(e==null)return "";let t=R(e);return t.length>Qe&&p(),t}function gn(e){return e===null?null:C(e)}function $(e,t){t!==void 0&&e!==t&&p();}function Re(e,t){let n=t??e[0];n!==void 0&&e.some(o=>o!==n)&&p();}function mn(e){let t=g(e);return {id:C(t.id),name:we(t.name),email:gn(t.email),...be("image",I(t,"image"))}}function W(e,t){return Array.isArray(e)||p(),e.map(n=>t(n))}function be(e,t){return t===void 0?{}:{[e]:t}}function hn(e,t,n=()=>null){let{post:o,mutation:i}=ee(e,t),s=new Map,a=(r,d,l,h)=>{if(l)return e.request(r,{query:d,fetchOptions:l,decode:h});let y=`${r}\0${JSON.stringify(d??null)}`,A=s.get(y);if(A)return A;let u=e.request(r,{query:d,decode:h}).finally(()=>{s.delete(y);});return s.set(y,u),u},c=r=>i(r).finally(()=>s.clear());return {create:(r,d)=>c(o("/organization/create",r,d,te)),list:r=>a("/organization/list",void 0,r,Qt),get:(r={},d)=>a("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},d,l=>Zt(l,r.organizationId,r.organizationSlug)),setActive:(r,d)=>c(o("/organization/set-active",r,d,l=>Ze(l,r.organizationId,r.organizationSlug))),listTeams:(r={},d)=>a("/organization/list-teams",{organizationId:r.organizationId},d,l=>en(l,r.organizationId)),setActiveTeam:(r,d)=>c(o("/organization/set-active-team",r,d,l=>tn(l,r.teamId))),update:(r,d)=>c(o("/organization/update",r,d,l=>Ze(l,r.organizationId))),delete:(r,d)=>c(o("/organization/delete",r,d,l=>te(l,r.organizationId))),listMembers:(r={},d)=>a("/organization/list-members",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,limit:r.limit,offset:r.offset,sortBy:r.sortBy,sortDirection:r.sortDirection,filterField:r.filterField,filterValue:r.filterValue,filterOperator:r.filterOperator},d,l=>nn(l,r.organizationId)),inviteMember:(r,d)=>c(o("/organization/invite-member",r,d,l=>j(l,void 0,r.organizationId))),listInvitations:(r={},d)=>a("/organization/list-invitations",{organizationId:r.organizationId},d,l=>on(l,r.organizationId)),listUserInvitations:r=>a("/organization/list-user-invitations",void 0,r,rn),getInvitation:(r,d)=>a("/organization/get-invitation",{id:r.id},d,l=>sn(l,r.id)),acceptInvitation:(r,d)=>c(o("/organization/accept-invitation",r,d,l=>an(l,r.invitationId))),rejectInvitation:(r,d)=>c(o("/organization/reject-invitation",r,d,l=>cn(l,r.invitationId))),cancelInvitation:(r,d)=>c(o("/organization/cancel-invitation",r,d,l=>un(l,r.invitationId))),removeMember:(r,d)=>c(o("/organization/remove-member",r,d,l=>ln(l,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,d)=>c(o("/organization/update-member-role",r,d,l=>ne(l,r.memberId,r.organizationId))),leave:(r,d)=>c(o("/organization/leave",r,d,l=>ne(l,void 0,r.organizationId))),listRoles:(r={},d)=>a("/organization/list-roles",{organizationId:r.organizationId},d,l=>dn(l,r.organizationId)),has:r=>Oe(n(),r),hasPermission:r=>Ae(n(),r.permission)}}var yn=4096,zi=4096,Li=100,Mi=256,Fi=16,Vi=64,Hi=12;function tt(e){let t=g(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&p(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:Nn(t.twoFactorMethods,Fi,Vi)}}):(t.twoFactorRedirect!==void 0&&p(),{redirect:T(t.redirect),...Ji(t,"url"),user:L(t.user)})}function An(e){let t=g(e);return {user:L(t.user)}}function On(e){let t=g(e);return {sessionCreated:T(t.sessionCreated),user:L(t.user)}}function bn(e,t){let n=g(e),o=T(n.redirect);n.user===null&&p();let i=n.user!==void 0&&n.user!==null,s=n.url!==void 0&&n.url!==null;return o?((i||!s)&&p(),{redirect:true,url:et(n.url,t)}):(i===s&&p(),i?{redirect:false,user:L(n.user)}:{redirect:false,url:et(n.url,t)})}function wn(e,t){let n=g(e);return (n.redirect!==true||n.user!==void 0)&&p(),{redirect:true,url:et(n.url,t)}}function Rn(e){return {status:T(g(e).status)}}function Sn(e){return {success:T(g(e).success)}}function kn(e){return g(e).status!=="pending"&&p(),{status:"pending"}}function Tn(e){let t=g(e);if(t.kind==="authowl_turnstile")return {kind:"authowl_turnstile"};t.kind!=="akedly_shield_v1_2"&&p();let n=g(t.turnstile),o=n.siteKey===null?null:R(n.siteKey);return {kind:"akedly_shield_v1_2",connectionId:R(t.connectionId),challenge:R(t.challenge),difficulty:qi(t.difficulty),challengeToken:R(t.challengeToken),challengeRequired:T(t.challengeRequired),turnstile:{required:T(n.required),siteKey:o}}}function qi(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>Hi)&&p(),Number(e)}function En(e){let t=g(e);return (t.status!==true||t.sessionCreated!==true)&&p(),{status:true,sessionCreated:true,user:Ki(t.user)}}function nt(e){return {status:T(g(e).status)}}function In(e){return {status:T(g(e).status)}}function Pn(e){let t=g(e);return {status:T(t.status),user:L(t.user)}}function Cn(e){return {success:T(g(e).success)}}function xn(e){let t=g(e);return {totpURI:ji(t.totpURI),backupCodes:Un(t.backupCodes)}}function vn(e){return {status:T(g(e).status)}}function Se(e){return g(e).status!==true&&p(),{status:true}}function Dn(e){return {status:T(g(e).status)}}function _n(e){let t=g(e);return t.status!==void 0&&t.status!==true&&p(),{backupCodes:Un(t.backupCodes)}}function Ki(e){let t=g(e);return {id:oe(t.id,512),...Gi(t,"name",1024),phoneNumber:oe(t.phoneNumber,64),phoneNumberVerified:T(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:P(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:P(t.updatedAt)}}}function et(e,t){let n=oe(e,yn);/[\u0000-\u0020\u007f]/u.test(n)&&p();let o;try{o=new URL(n);}catch{return p()}return (o.username||o.password)&&p(),o.protocol==="https:"||t&&o.protocol==="http:"&&Bi(o.hostname)?o.href:p()}function Bi(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function ji(e){let t=oe(e,zi),n;try{n=new URL(t);}catch{return p()}let o=n.searchParams.get("secret");return (n.protocol!=="otpauth:"||n.hostname.toLowerCase()!=="totp"||n.username||n.password||n.hash||o===null||o.length===0||o.length>512||/\s/u.test(o))&&p(),t}function Un(e){return Nn(e,Li,Mi)}function Nn(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&p();let o=e.map(i=>oe(i,n));return o.some(i=>i.trim().length===0)&&p(),new Set(o).size!==o.length&&p(),o}function oe(e,t){let n=R(e);return (n.length===0||n.length>t)&&p(),n}function Ji(e,t){let n=e[t];return n==null?{}:{[t]:oe(n,yn)}}function Gi(e,t,n){let o=I(e,t);return o===void 0?{}:(o!==null&&o.length>n&&p(),{[t]:o})}var zn=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),ke=new Set([9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279]);function Te(e){if(e===void 0)return {valid:true,value:void 0};for(let n of e){let o=n.codePointAt(0);if(o===void 0||Mn(n,o)||Ln(o)||zn.has(o))return {valid:false}}let t=$i(e);return ot(t)?{valid:true,value:t}:{valid:false}}function ot(e){let t=0,n,o;for(let i of e){if(t+=1,t>256)return false;let s=i.codePointAt(0);if(s===void 0||Mn(i,s)||Ln(s)||zn.has(s))return false;n??=s,o=s;}return t>0&&n!==void 0&&o!==void 0&&!ke.has(n)&&!ke.has(o)}function Ee(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_PASSKEY_NAME",message:"Passkey names must contain 1 to 256 safe Unicode characters."}}}function $i(e){let t=0,n=e.length;for(;t<n;){let o=e.codePointAt(t);if(o===void 0||!ke.has(o))break;t+=o>65535?2:1;}for(;n>t;){let o=e.codePointAt(n-1);if(o===void 0)break;let s=o>=56320&&o<=57343?n-2:n-1,a=e.codePointAt(s);if(a===void 0||!ke.has(a))break;n=s;}return e.slice(t,n)}function Ln(e){return e>=0&&e<=31||e>=127&&e<=159}function Mn(e,t){return e.length===1&&t>=55296&&t<=57343}var Hn=12,qn=5e3,Wi=8,Yi=1e3,Xi=16,Fn=512,Kn=100,Bn=8192,Qi=32768,it=1024,Vn=256,st=64,Zi=6e5,er=/^[A-Za-z0-9_-]+$/u,tr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,nr=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,or=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,ir=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,jn=new Set(["discouraged","preferred","required"]),rr=new Set(["singleDevice","multiDevice"]),Jn=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),Gn=new Set(["hybrid","security-key","client-device"]),sr=new Set(["none","indirect","direct","enterprise"]),ar=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),cr=new Set(["platform","cross-platform"]),ur=new Set(["discouraged","preferred","required"]),lr=new Set([-8,-7,-257]);function $n(e){let t=B(e,Hn,qn);return {challenge:io(t.challenge),...v("timeout",no(t.timeout)),...v("rpId",ro(t.rpId)),...v("allowCredentials",to(t.allowCredentials)),...v("userVerification",fe(t.userVerification,jn)),...v("hints",Ie(t.hints,Gn)),...v("extensions",oo(t.extensions))}}function Wn(e){let t=B(e,Hn,qn);return {challenge:io(t.challenge),rp:dr(t.rp),user:pr(t.user),pubKeyCredParams:fr(t.pubKeyCredParams),...v("timeout",no(t.timeout)),...v("excludeCredentials",to(t.excludeCredentials)),...v("authenticatorSelection",gr(t.authenticatorSelection)),...v("attestation",fe(t.attestation,sr)),...v("attestationFormats",Ie(t.attestationFormats,ar)),...v("hints",Ie(t.hints,Gn)),...v("extensions",oo(t.extensions))}}function Yn(e){let t=g(e),n=ye(t.session),o=L(t.user);return n.userId!==o.id&&p(),{session:n,user:o}}function at(e){let t=g(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&p();let o=ct(t.deviceType,rr),i=T(t.backedUp);return i&&o!=="multiDevice"&&p(),{id:ie(t.id,Vn),...yr(t),publicKey:mr(t.publicKey,Qi),userId:ie(t.userId,Vn),credentialID:Ce(t.credentialID,Bn),counter:n,deviceType:o,backedUp:i,...Ar(t),createdAt:P(t.createdAt),...Or(t)}}function Xn(e,t,n){let o=at(e);return (o.credentialID!==t||(n===void 0?o.name!==void 0&&o.name!==null:o.name!==n))&&p(),o}function Qn(e){(!Array.isArray(e)||e.length>Kn)&&p();let t=e.map(at);return Pe(t.map(n=>n.id)),Pe(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&p(),t}function Zn(e,t,n){let o=g(e),i=at(o.passkey);return (i.id!==t||i.name!==n)&&p(),{passkey:i}}function eo(e){return g(e).status!==true&&p(),{status:true}}function dr(e){let t=g(e);return {name:rt(t.name,it),...v("id",ro(t.id))}}function pr(e){let t=g(e);return {id:Ce(t.id,128,1,64),name:rt(t.name,it),displayName:rt(t.displayName,it)}}function fr(e){(!Array.isArray(e)||e.length===0||e.length>st)&&p();let t=e.map(n=>{let o=g(n);return (o.type!=="public-key"||!Number.isSafeInteger(o.alg)||!lr.has(o.alg))&&p(),{type:"public-key",alg:o.alg}});return br(t.map(n=>n.alg)),t}function to(e){if(e===void 0)return;(!Array.isArray(e)||e.length>Kn)&&p();let t=e.map(n=>{let o=g(n);return o.type!=="public-key"&&p(),{type:"public-key",id:Ce(o.id,Bn),...v("transports",Ie(o.transports,Jn))}});return Pe(t.map(n=>n.id)),t}function gr(e){if(e===void 0)return;let t=g(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&p();let n=fe(t.residentKey,ur);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&p(),{...v("authenticatorAttachment",fe(t.authenticatorAttachment,cr)),...v("residentKey",n),...v("requireResidentKey",t.requireResidentKey),...v("userVerification",fe(t.userVerification,jn))}}function no(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>Zi)&&p(),e}function oo(e){return e===void 0?void 0:B(e,Wi,Yi)}function Ie(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>st)&&p();let n=e.map(o=>ct(o,t));return Pe(n),n}function fe(e,t){if(e!==void 0)return ct(e,t)}function io(e){return Ce(e,Math.ceil(Fn*4/3),Xi,Fn)}function Ce(e,t,n=1,o=Number.POSITIVE_INFINITY){let i=ie(e,t),s=i.length%4,a=hr(i.at(-1)??""),c=Math.floor(i.length*3/4);return (!er.test(i)||s===1||s===2&&(a&15)!==0||s===3&&(a&3)!==0||c<n||c>o)&&p(),i}function ie(e,t){let n=R(e);return (n.length===0||n.length>t)&&p(),n}function rt(e,t){let n=ie(e,t);return nr.test(n)&&p(),n}function ro(e){if(e===void 0)return;let t=ie(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!or.test(n)))&&p(),t}function mr(e,t){let n=ie(e,t),o=n.endsWith("=="),i=!o&&n.endsWith("="),s=n.at(o?-3:i?-2:-1)??"",a=so(s);return (n.length%4!==0||!tr.test(n)||o&&(a&15)!==0||i&&(a&3)!==0)&&p(),n}function hr(e){return so(e,true)}function so(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function yr(e){let t=I(e,"name");return t===void 0?{}:(t!==null&&!ot(t)&&p(),{name:t})}function Ar(e){let t=I(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>st||n.some(o=>!Jn.has(o))||new Set(n).size!==n.length)&&p(),{transports:t}}function Or(e){let t=I(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(ir.test(t)||p(),{aaguid:t})}function ct(e,t){let n=R(e);return t.has(n)||p(),n}function v(e,t){return t===void 0?{}:{[e]:t}}function Pe(e){new Set(e).size!==e.length&&p();}function br(e){new Set(e).size!==e.length&&p();}function Cr(e,t){if(!t)return e;let n=t.catch(()=>{});return n.then(()=>{n=null;}),{async request(o,i){return n&&await n,e.request(o,i)}}}var fo=new Map;function xr(e,t,n){let o=fo.get(n);if(!o){let i=new URLSearchParams(window.location.hash.slice(1)).get("authowl_code");if(!i)return;o=Promise.resolve().then(()=>(ve(),xe)).then(s=>s.completeCrossSiteSignIn(e,t,i)),fo.set(n,o);}return o}function go(e){return !de()||e.idToken||e.disableRedirect?"legacy":"first-party"}function ho(e,t=()=>{},n=vr){let o=ue(e),i=e.session.tokens,s=de()?xr(o,i,e.decoded.projectId):void 0,a=Cr(o,s),c=Bt({http:a,probe:ue({...e,fetch:e.session.probe}),tokens:i,channelName:`authowl:${e.decoded.projectId}`}),r=n(a,c.notifyMutation),d=()=>{c.notifyMutation(),t();},{post:l,mutation:h}=ee(a,d),y=e.decoded.env==="test",A=u=>{i.beginSession({remember:u?.rememberMe!==false});};return {sessionStore:c.store,getSession:c.getSession,account:Wt(a,d),organization:hn(a,d,()=>c.store.getSnapshot().data?.session.membership??null),signIn:{email:(u,f)=>(A(u),h(l("/sign-in/email",u,f,tt),m=>!("twoFactorRedirect"in m))),username:(u,f)=>(A(u),h(l("/sign-in/username",u,f,tt),m=>!("twoFactorRedirect"in m))),social:async(u,f)=>{if(A(),go(u)==="first-party"){let{beginCrossSiteSignIn:w}=await Promise.resolve().then(()=>(ve(),xe)),S=await w(e,{kind:"social",provider:u.provider,callbackURL:u.callbackURL,errorCallbackURL:u.errorCallbackURL,newUserCallbackURL:u.newUserCallbackURL,scopes:u.scopes,loginHint:u.loginHint,requestSignUp:u.requestSignUp});if(S)return window.location.assign(S),{data:{redirect:true,url:S},error:null}}let m=await h(l("/sign-in/social",u,f,w=>bn(w,y)),w=>"user"in w);return m.error!==null||m.data===null||"url"in m.data&&m.data.redirect&&!u.disableRedirect&&typeof window<"u"&&window.location.assign(m.data.url),m},sso:async(u,f)=>{if(go(u)==="first-party"){let{beginCrossSiteSignIn:w}=await Promise.resolve().then(()=>(ve(),xe)),S=await w(e,{kind:"sso",email:u.email,providerId:u.providerId,domain:u.domain,organizationSlug:u.organizationSlug,callbackURL:u.callbackURL,errorCallbackURL:u.errorCallbackURL,newUserCallbackURL:u.newUserCallbackURL});if(S)return window.location.assign(S),{data:{url:S,redirect:true},error:null}}let m=await l("/sign-in/sso",u,f,w=>wn(w,y));return m.error!==null||m.data===null||typeof window<"u"&&window.location.assign(m.data.url),m},magicLink:(u,f)=>l("/sign-in/magic-link",u,f,Rn),emailOtp:(u,f)=>(A(),h(l("/sign-in/email-otp",u,f,An))),passkey:(u,f)=>(A(),r.signIn(u,f))},signUp:{email:(u,f)=>(A(),h(l("/sign-up/email",u,f,On),m=>m.sessionCreated))},emailOtp:{sendVerificationOtp:(u,f)=>l("/email-otp/send-verification-otp",u,f,Sn),verifyEmail:(u,f)=>(A(),h(l("/email-otp/verify-email",u,f,Pn)))},phoneOtp:{prepare:u=>l("/phone-otp/challenge",{},u,Tn),start:(u,f)=>l("/phone-otp/start",{...u,idempotencyKey:u.idempotencyKey??Xe()},f,kn),verify:(u,f)=>(A(),h(l("/phone-otp/verify",u,f,En)))},requestPasswordReset:(u,f)=>l("/request-password-reset",u,f,nt),resetPassword:(u,f)=>l("/reset-password",u,f,nt),sendVerificationEmail:(u,f)=>l("/send-verification-email",u,f,In),passkey:{addPasskey:(u,f)=>r.add(u,f),listUserPasskeys:()=>a.request("/passkey/list-user-passkeys",{decode:Qn}),updatePasskey:async(u,f)=>{let m=Te(u.name);if(!m.valid||m.value===void 0)return Ee();let w=m.value;return l("/passkey/update-passkey",{...u,name:w},f,S=>Zn(S,u.id,w))},deletePasskey:(u,f)=>l("/passkey/delete-passkey",u,f,eo)},twoFactor:{enable:(u,f)=>l("/two-factor/enable",u,f,xn),disable:(u,f)=>h(l("/two-factor/disable",u,f,vn),m=>m.status),verifyTotp:(u,f)=>h(l("/two-factor/verify-totp",u,f,Se)),verifyBackupCode:(u,f)=>h(l("/two-factor/verify-backup-code",u,f,Se)),sendOtp:(u={},f)=>l("/two-factor/send-otp",u,f,Dn),verifyOtp:(u,f)=>h(l("/two-factor/verify-otp",u,f,Se)),generateBackupCodes:(u,f)=>l("/two-factor/generate-backup-codes",u,f,_n)},signOut:u=>h(a.request("/sign-out",{method:"POST",body:{},fetchOptions:u,decode:Cn}).then(f=>(i.endSession(),f)),f=>f.success)}}function vr(){return {signIn:()=>mo(),add:()=>mo()}}function mo(){return Promise.resolve({data:null,error:{status:400,statusText:"BAD_REQUEST",code:"PASSKEY_BROWSER_REQUIRED",message:"This passkey ceremony requires a browser with WebAuthn."}})}function Ro(e,t,n){let o=new Map;return {async signIn(i={},s){let a=await e.request("/passkey/generate-authenticate-options");if(!a.data)return Oo(a.error);let c;try{c=$n(a.data);}catch{return yo()}let r;try{r=await n.authenticate({optionsJSON:c,useBrowserAutofill:i.autoFill});}catch(A){return bo(n,A,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!Dr(r))return Ao();let{clientExtensionResults:d,...l}=r,h=o.get(r.id);if(h)return h;let y=(async()=>{let A=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:l},fetchOptions:s,decode:Yn});return A.data&&t(),A})();o.set(r.id,y);try{return await y}finally{o.get(r.id)===y&&o.delete(r.id);}},async add(i={},s){let a=Te(i.name);if(!a.valid)return Ee();let c=await e.request("/passkey/generate-register-options",{query:{name:a.value,authenticatorAttachment:i.authenticatorAttachment}});if(!c.data)return Oo(c.error);let r;try{r=Wn(c.data);}catch{return yo()}let d;try{d=await n.register({optionsJSON:r});}catch(A){return bo(n,A,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!_r(d))return Ao();let{clientExtensionResults:l,...h}=d,y=await e.request("/passkey/verify-registration",{method:"POST",body:{response:h,name:a.value},fetchOptions:s,decode:A=>Xn(A,d.id,a.value)});return y.data&&t(),y}}}function yo(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function Ao(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function So(e){if(!e||typeof e!="object")return false;let t=e;return typeof t.id=="string"&&t.id.length>0&&typeof t.rawId=="string"&&t.rawId.length>0&&t.type==="public-key"&&!!t.response&&typeof t.response=="object"}function Dr(e){if(!So(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.authenticatorData=="string"&&typeof t.signature=="string"&&(t.userHandle===void 0||typeof t.userHandle=="string")}function _r(e){if(!So(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function Oo(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function bo(e,t,n,o){let i=Nr(t,"page does not have focus"),s=e.errorCode?.(t),a=s!==void 0?s==="ERROR_CEREMONY_ABORTED":wo(t)==="AbortError",c=n!=="AUTH_CANCELLED",r=Ur(s,wo(t),c);return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:i?"PASSKEY_PAGE_NOT_FOCUSED":a?n:s??"PASSKEY_BROWSER_ERROR",message:i?"Keep this page focused while completing the passkey prompt.":a?o:r}}}function Ur(e,t,n){switch(e){case "ERROR_INVALID_DOMAIN":case "ERROR_INVALID_RP_ID":return "Passkeys are not set up for this site\u2019s domain.";case "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED":return "This device already has a passkey for this account.";case "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEY_ALGS":case "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT":case "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT":return "This device cannot create a passkey for this site.";}return t==="NotAllowedError"?n?"No passkey was created. The prompt was dismissed or timed out.":"No passkey was used. This device may not have one saved for this site yet, or the prompt was dismissed.":t==="SecurityError"?"Passkeys are not set up for this site\u2019s domain.":n?"Passkey registration did not complete.":"Passkey sign-in did not complete."}function wo(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function Nr(e,t){let n=t.toLowerCase(),o=new Set,i=e;for(;i&&typeof i=="object"&&!o.has(i);){if(o.add(i),"message"in i&&typeof i.message=="string"&&i.message.toLowerCase().includes(n))return true;i="cause"in i?i.cause:void 0;}return false}function M(e){let t=new Uint8Array(e),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Q(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,o=t.padEnd(t.length+n,"="),i=atob(o),s=new ArrayBuffer(i.length),a=new Uint8Array(s);for(let c=0;c<i.length;c++)a[c]=i.charCodeAt(c);return s}function Z(){return zr.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var zr={stubThis:e=>e};function De(e){let{id:t}=e;return {...e,id:Q(t),transports:e.transports}}function _e(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 E=class extends Error{constructor({message:t,code:n,cause:o,name:i}){super(t,{cause:o}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=i??o.name,this.code=n;}};function ko({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 E({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 E({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 E({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 E({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 E({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new E({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return n.pubKeyCredParams.filter(i=>i.type==="public-key").length===0?new E({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new E({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(_e(o)){if(n.rp.id!==o)return new E({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new E({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 E({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 E({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 dt=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;}}},Ue=new dt;var Lr=["cross-platform","platform"];function Ne(e){if(e&&!(Lr.indexOf(e)<0))return e}async function To(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(!Z())throw new Error("WebAuthn is not supported in this browser");let o={...t,challenge:Q(t.challenge),user:{...t.user,id:Q(t.user.id)},excludeCredentials:t.excludeCredentials?.map(De)},i={};n&&(i.mediation="conditional"),i.publicKey=o,i.signal=Ue.createNewAbortSignal();let s;try{s=await navigator.credentials.create(i);}catch(u){throw ko({error:u,options:i})}if(!s)throw new Error("Registration was not completed");let{id:a,rawId:c,response:r,type:d}=s,l;typeof r.getTransports=="function"&&(l=r.getTransports());let h;if(typeof r.getPublicKeyAlgorithm=="function")try{h=r.getPublicKeyAlgorithm();}catch(u){pt("getPublicKeyAlgorithm()",u);}let y;if(typeof r.getPublicKey=="function")try{let u=r.getPublicKey();u!==null&&(y=M(u));}catch(u){pt("getPublicKey()",u);}let A;if(typeof r.getAuthenticatorData=="function")try{A=M(r.getAuthenticatorData());}catch(u){pt("getAuthenticatorData()",u);}return {id:a,rawId:M(c),response:{attestationObject:M(r.attestationObject),clientDataJSON:M(r.clientDataJSON),transports:l,publicKeyAlgorithm:h,publicKey:y,authenticatorData:A},type:d,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:Ne(s.authenticatorAttachment)}}function pt(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 Eo(){if(!Z())return ft.stubThis(new Promise(t=>t(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?ft.stubThis(new Promise(t=>t(false))):ft.stubThis(e.isConditionalMediationAvailable())}var ft={stubThis:e=>e};function Io({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 E({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else {if(e.name==="NotAllowedError")return new E({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let o=globalThis.location.hostname;if(_e(o)){if(n.rpId!==o)return new E({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new E({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new E({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 Po(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(!Z())throw new Error("WebAuthn is not supported in this browser");let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(De));let s={...t,challenge:Q(t.challenge),allowCredentials:i},a={};if(n){if(!await Eo())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');a.mediation="conditional",s.allowCredentials=[];}a.publicKey=s,a.signal=Ue.createNewAbortSignal();let c;try{c=await navigator.credentials.get(a);}catch(A){throw Io({error:A,options:a})}if(!c)throw new Error("Authentication was not completed");let{id:r,rawId:d,response:l,type:h}=c,y;return l.userHandle&&(y=M(l.userHandle)),{id:r,rawId:M(d),response:{authenticatorData:M(l.authenticatorData),clientDataJSON:M(l.clientDataJSON),signature:M(l.signature),userHandle:y},type:h,clientExtensionResults:c.getClientExtensionResults(),authenticatorAttachment:Ne(c.authenticatorAttachment)}}var Co={authenticate:e=>Po(e),register:e=>To(e),errorCode:e=>e instanceof E?e.code:void 0};function vo(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function gt(e){let t=await K(e,vo(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:Mr});return t.response.status===401?{required:false}:X(t,"consent status")}async function mt(e,t){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Consent version must be a positive integer.");return X(await K(e,vo(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:t})},maxResponseBytes:64*1024,decode:Fr}),"consent accept")}function Mr(e){let t=g(e),n=T(t.required),o=Vr(t.needsConsent),i=Do(t.version),s=xo(t.termsUrl),a=xo(t.privacyUrl);return {required:n,...o===void 0?{}:{needsConsent:o},...i===void 0?{}:{version:i},...s===void 0?{}:{termsUrl:s},...a===void 0?{}:{privacyUrl:a}}}function Fr(e){let t=g(e),n=Do(t.version);return {ok:T(t.ok),...n===void 0?{}:{version:n}}}function Vr(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function Do(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function xo(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var Hr=30;function qr(e){return typeof e?.exp=="number"?e.exp:null}function Kr(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 ht(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 c=a??"",r=t.get(c);r||(r={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},t.set(c,r));let d=s.forceRefresh===true;if(!d){let u=r.activeKey?r.cachedByKey.get(r.activeKey):null;if(u&&u.exp-Date.now()/1e3>Hr)return u.token;if(r.inflight)return r.inflight}let l=++r.sequence,h=()=>t.get(c)===r&&r.sequence===l,y=(async()=>{let u=a?`${e.projectBaseURL}/token/${encodeURIComponent(a)}`:`${e.projectBaseURL}/token`,f=await K(e,u,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:b=>Br(b,a!==null)});if(f.response.status===401)return h()&&o(),null;let m=X(f,"token"),w=m.policyVersion,S=m.token,N=Kr(S),H=qr(N);if(h())if(H!==null){let b=typeof N?.sub=="string"?N.sub:null,k=typeof N?.org_id=="string"?N.org_id:null;if(!a||b){let O=JSON.stringify([e.projectBaseURL,b,k,a,w]);r.cachedByKey.clear(),r.cachedByKey.set(O,{token:S,exp:H}),r.activeKey=O;}else i(r);}else i(r);return S})();if(d)return y;let A=y.finally(()=>{r.inflight===A&&(r.inflight=null);});return r.inflight=A,A}function o(){t.clear();}function i(s){s.cachedByKey.clear(),s.activeKey=null;}return {getToken:n,clear:o}}function Br(e,t){let n=g(e),o=R(n.token);if(o.length===0||o.length>32*1024)throw new TypeError("Invalid token response.");if(!t)return {token:o,policyVersion:0};let i=g(n.template);if(!Number.isSafeInteger(i.policyVersion)||i.policyVersion<1)throw new TypeError("Invalid token response.");return {token:o,policyVersion:i.policyVersion}}function jr(e){let t=ht(e),n=ho(e,t.clear,(a,c)=>Ro(a,c,Co)),o=ue(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),i=a=>(...c)=>(t.clear(),a(...c)),s={getConsentStatus:()=>gt(e),acceptConsent:a=>mt(e,a),getToken:t.getToken,waitlist:{join:(a,c)=>o.request("/waitlist",{method:"POST",body:a,fetchOptions:c,credentials:"omit"})},account:{...n.account,updateUnsafeMetadata:i(n.account.updateUnsafeMetadata),updateProfile:i(n.account.updateProfile),changeEmail:i(n.account.changeEmail),changePassword:i(n.account.changePassword),revokeSession:i(n.account.revokeSession),delete:i(n.account.delete)},signIn:{email:i(n.signIn.email),username:i(n.signIn.username),social:i(n.signIn.social),sso:n.signIn.sso,magicLink:n.signIn.magicLink,emailOtp:i(n.signIn.emailOtp),passkey:i(n.signIn.passkey)},signUp:{email:i(n.signUp.email)},emailOtp:{...n.emailOtp,verifyEmail:i(n.emailOtp.verifyEmail)},twoFactor:{enable:n.twoFactor.enable,disable:i(n.twoFactor.disable),verifyTotp:i(n.twoFactor.verifyTotp),verifyBackupCode:i(n.twoFactor.verifyBackupCode),sendOtp:n.twoFactor.sendOtp,verifyOtp:i(n.twoFactor.verifyOtp),generateBackupCodes:n.twoFactor.generateBackupCodes},phoneOtp:{prepare:n.phoneOtp.prepare,start:n.phoneOtp.start,verify:i(n.phoneOtp.verify)},signOut:i(n.signOut)};return {...n,...s}}async function Jr(e){if(typeof window>"u")throw new Error("Akedly Shield challenges must be solved in a browser.");let t=await Gr(),n=e.challengeRequired?await t.solvePow(e.challenge,e.difficulty):null,o=e.turnstile.required?await t.getTurnstileToken($r(e.turnstile.siteKey)):void 0;return {connectionId:e.connectionId,...n?{challengeToken:e.challengeToken,nonce:n.nonce}:{},...o?{turnstileToken:o}:{}}}async function Gr(){return import('@akedly/shield')}function $r(e){if(!e)throw new Error("Akedly Shield did not provide a Turnstile site key.");return e}async function Wr(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return X(await K(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:o=>Yr(o,e)}),"public-config")}function Yr(e,t){let n=B(e),o=n.environmentId,i=n.environmentType,s=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Xr(n.applicationId)||o!==t.decoded.projectId||i!=="development"&&i!=="production"||n.authBaseUrl!==s)throw F();let a=U(n.branding),c=U(n.legal);if(!yt(n.enabledMethods,64)||!yt(n.socialProviders,64)||!Uo(a,["appName","logoUrl","primaryColor"])||a.showAppName!==void 0&&typeof a.showAppName!="boolean"||a.alignment!==void 0&&a.alignment!=="left"&&a.alignment!=="center"&&a.alignment!=="right"||a.theme!==void 0&&a.theme!=="light"&&a.theme!=="dark"&&a.theme!=="system"||!Uo(c,["termsUrl","privacyUrl"])||!Number.isSafeInteger(c.version)||c.version<0||typeof c.required!="boolean")throw F();if(n.socialProviderClientIds!==void 0){let r=U(n.socialProviderClientIds);if(Object.keys(r).length>64||Object.values(r).some(d=>typeof d!="string"||d.length>2048))throw F()}if(!J(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!_o(n.turnstileSiteKey)||!_o(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw F();if(n.jwtIssuer!==null){let r=U(n.jwtIssuer);if(r.issuer!==s||r.jwksUrl!==`${s}/jwks`||r.aud!==t.decoded.projectId)throw F()}if(n.signUp!==void 0){let r=U(n.signUp).mode;if(typeof r!="string"||!["open","restricted","allowlist","waitlist"].includes(r))throw F()}if(n.authentication!==void 0&&Qr(n.authentication),n.emailVerification!==void 0){let r=U(n.emailVerification);if(!J(r,["required"])||r.method!=="link"&&r.method!=="code")throw F()}if(n.userModel!==void 0&&!J(U(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw F();if(n.mfa!==void 0){let r=U(n.mfa);if(!J(r,["totp","required","backupCodes"])||(r.required===true||r.backupCodes===true)&&r.totp!==true)throw F()}return n}function Xr(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function F(){return new TypeError("public-config returned an invalid response")}function U(e){if(!e||typeof e!="object"||Array.isArray(e))throw F();return e}function _o(e){return e===null||typeof e=="string"&&e.length<=4096}function Qr(e){let t=U(e),n=U(t.email),o=U(t.password),i=o.minLength!==void 0||o.maxLength!==void 0;if(!J(n,["signUp"])||!yt(n.signIn,3)||n.signIn.some(s=>s!=="password"&&s!=="magic_link"&&s!=="email_otp")||!J(U(t.phone),["signUp","signIn"])||!J(o,["signUp","add"])||i&&(!Number.isSafeInteger(o.minLength)||!Number.isSafeInteger(o.maxLength)||o.minLength<1||o.maxLength>4096||o.minLength>o.maxLength)||!J(U(t.passkey),["signIn","add"])||!Zr(U(t.passkey).relyingPartyId)||!J(U(t.username),["collectOnSignUp","signIn"]))throw F()}function Zr(e){return e==null||typeof e=="string"}function J(e,t){return t.every(n=>typeof e[n]=="boolean")}function Uo(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function yt(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length<=128)&&new Set(e).size===e.length}var ge=class extends Error{constructor(n,o){super(n);this.cause=o;this.name="AuthOwlError";}cause},At=class extends ge{constructor(n,o){super(`Rate limited. Retry after ${n}s.`,o);this.retryAfterSeconds=n;this.name="RateLimitedError";}retryAfterSeconds},Ot=class extends ge{constructor(t="invalid publishable key",n){super(t,n),this.name="InvalidKeyError";}};var No=["en","ar"];function es(e){return e==="ar"?"rtl":"ltr"}function ts(e){return typeof e=="string"&&No.includes(e)}
|
|
3
|
+
exports.AUTH_CHALLENGE_HEADER=qt;exports.AuthOwlError=ge;exports.AuthOwlHttpError=he;exports.INVITATION_CLAIM_MAX_AGE_MS=Nt;exports.INVITATION_QUERY_PARAM=qe;exports.InvalidKeyError=Ot;exports.LOCALES=No;exports.RateLimitedError=At;exports.SESSION_TOKEN_HEADER=Fe;exports.SESSION_TRANSPORT_BEARER=He;exports.SESSION_TRANSPORT_HEADER=Ve;exports.TransportError=D;exports.acceptConsent=mt;exports.captureInvitationClaim=ti;exports.clearInvitationClaim=ae;exports.createAuthOwlClient=jr;exports.createIdempotencyKey=Xe;exports.createMembershipHas=Di;exports.createTokenClient=ht;exports.decodePublishableKey=ze;exports.directionFor=es;exports.getConsentStatus=gt;exports.getPublicConfig=Wr;exports.isLocale=ts;exports.membershipHas=Oe;exports.membershipHasPermission=Ae;exports.membershipHasRole=Xt;exports.membershipHasTeam=Yt;exports.readInvitationClaim=se;exports.resolveAuthTarget=_t;exports.resolveConfig=ei;exports.resolveProjectCapabilities=ni;exports.sessionChallengeIsEphemeral=Bo;exports.sessionCookieName=Vo;exports.solvePhoneOtpChallenge=Jr;
|
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-
|
|
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
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
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};
|