@authowl/core 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +231 -0
- package/THIRD_PARTY_NOTICES.md +33 -0
- package/dist/chunk-KPXCQZUX.js +2 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +1282 -0
- package/dist/index.d.ts +1282 -0
- package/dist/index.js +3 -0
- package/dist/server.cjs +2 -0
- package/dist/server.d.cts +2757 -0
- package/dist/server.d.ts +2757 -0
- package/dist/server.js +1 -0
- package/dist/transport-BObDKlIh.d.cts +131 -0
- package/dist/transport-BObDKlIh.d.ts +131 -0
- package/package.json +66 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {g,f,h,j,i,p,n,s,u,k,r,m,l,o,q as q$1}from'./chunk-KPXCQZUX.js';export{f as TransportError,v as createMembershipHas,a as decodePublishableKey,u as membershipHas,s as membershipHasPermission,t as membershipHasTeam,e as resolveConfig,b as sessionCookieName}from'./chunk-KPXCQZUX.js';var Je="x-authowl-turnstile-token",Cn=1e4,vn=32,zn=2e4;function V(e,t){return {post:(n,i,o,a)=>e.request(n,{method:"POST",body:i,fetchOptions:o,decode:a}),mutation:async(n,i)=>{let o=await n;return o.error===null&&(i===void 0||o.data!==null&&i(o.data))&&t(),o}}}function ee(e,t=e.projectBaseURL){return {async request(n,i={}){let o=_n(t,n,i.query),a=i.method??(i.body===void 0?"GET":"POST"),r=new Headers(i.fetchOptions?.headers);r.set("x-publishable-key",e.publishableKey),i.fetchOptions?.authChallengeToken&&r.set(Je,i.fetchOptions.authChallengeToken),i.body!==void 0&&r.set("content-type","application/json");let s={method:a,headers:r,credentials:i.credentials??"include",...i.body===void 0?{}:{body:JSON.stringify(i.body)}},c=Object.freeze({method:a,path:n});await i.fetchOptions?.onRequest?.(c);let l=Nn(a,i.fetchOptions),u;try{u=await Un(e,o,{...s,signal:i.fetchOptions?.signal},l);}catch(D){let Y=Ge(D);return await i.fetchOptions?.onError?.(Oe(c,Y,Ln(D))),{data:null,error:Y}}let{response:f$1,requestId:g}=u,m=Kn(n,u.data),h=m;if(f$1.ok)try{h=be(m),i.decode&&(h=i.decode(h));}catch{let D=Ge(new f("invalid_response",g));return await i.fetchOptions?.onError?.(Oe(c,D,"invalid_response")),{data:null,error:D}}let z=Object.freeze({...c,status:f$1.status,...g===void 0?{}:{requestId:g}});if(await i.fetchOptions?.onResponse?.(z),!f$1.ok){let D=Fn(f$1,m,g);return await i.fetchOptions?.onError?.(Oe(c,D,"api")),{data:null,error:D}}return await i.fetchOptions?.onSuccess?.(z),{data:h,error:null}}}}async function Un(e,t,n,i){let o=Date.now()+Cn;for(let a=0;a<i;a+=1){let r=o-Date.now();if(r<=0)throw new f("timeout");try{let s=await g({fetchImpl:e.fetch??fetch,url:t,init:n,timeoutMs:Math.max(1,Math.ceil(r)),allowHttpLoopback:e.decoded.env==="test"});if(s.response.status<500||a===i-1)return s}catch(s){if(a===i-1||!(s instanceof f)||s.kind!=="network")throw s}await Vn(50*2**a,n.signal,o);}throw new f("network")}function Nn(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 _n(e,t,n){let i=new URL(`${e}${t.startsWith("/")?t:`/${t}`}`);for(let[o,a]of Object.entries(n??{}))a!==void 0&&i.searchParams.set(o,String(a));return i.toString()}function Fn(e,t,n){let i=G(t)?t:{},o=Mn(i,e.headers);return {status:e.status,statusText:e.statusText,code:typeof i.code=="string"?i.code:void 0,...n===void 0?{}:{requestId:n},...typeof i.current_version=="number"?{currentVersion:i.current_version}:{},...o!==void 0?{retryAfterSeconds:o}:{},message:typeof i.message=="string"?i.message:typeof i.error=="string"?i.error:typeof i.detail=="string"?i.detail:e.statusText||"Request failed"}}function Mn(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??je(t.get("retry-after"))??je(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function je(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 Ge(e){let t=e instanceof f?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 f&&e.requestId?{requestId:e.requestId}:{}}}function Oe(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function Ln(e){return e instanceof f?e.kind:"network"}function Vn(e,t,n){return new Promise((i,o)=>{if(t?.aborted){o(new f("aborted"));return}let a=n-Date.now();if(a<=0){o(new f("timeout"));return}let r=Math.min(e,a),s=()=>{clearTimeout(c),o(new f("aborted"));},c=setTimeout(()=>{t?.removeEventListener("abort",s),Date.now()>=n?o(new f("timeout")):i();},r);t?.addEventListener("abort",s,{once:true}),t?.aborted&&s();})}function be(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>vn||i.nodes>zn)throw new Error("response traversal limit exceeded");if(typeof e=="string"&&/^(?:createdAt|updatedAt|expiresAt)$/.test(t)){let o=new Date(e);return Number.isNaN(o.getTime())?e:o}return Array.isArray(e)?e.map(o=>be(o,"",n+1,i)):G(e)?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,qn(o)?a:be(a,o,n+1,i)])):e}function qn(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function Kn(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>G(o)?ye(o):o);if(!G(t))return t;let i=e==="/change-password"||e==="/passkey/verify-authentication"||e==="/phone-otp/verify"||e==="/sign-up/email"||e.startsWith("/sign-in/")||e.startsWith("/two-factor/verify-")?ye(t):t;return e==="/sign-up/email"&&!("sessionCreated"in i)&&(i={...i,sessionCreated:typeof t.token=="string"&&t.token.length>0}),(e==="/get-session"||e==="/passkey/verify-authentication")&&G(i.session)&&(i={...i,session:ye(i.session)}),i}function ye(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function G(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function E(e){let t=new Uint8Array(e),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function _(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,i=t.padEnd(t.length+n,"="),o=atob(i),a=new ArrayBuffer(o.length),r=new Uint8Array(a);for(let s=0;s<o.length;s++)r[s]=o.charCodeAt(s);return a}function F(){return Bn.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var Bn={stubThis:e=>e};function te(e){let{id:t}=e;return {...e,id:_(t),transports:e.transports}}function ne(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 O=class extends Error{constructor({message:t,code:n,cause:i,name:o}){super(t,{cause:i}),Object.defineProperty(this,"code",{enumerable:true,configurable:true,writable:true,value:void 0}),this.name=o??i.name,this.code=n;}};function We({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 O({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 O({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 O({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 O({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 O({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new O({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return n.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new O({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new O({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(ne(i)){if(n.rp.id!==i)return new O({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new O({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 O({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 O({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 we=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;}}},ie=new we;var Hn=["cross-platform","platform"];function oe(e){if(e&&!(Hn.indexOf(e)<0))return e}async function $e(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(!F())throw new Error("WebAuthn is not supported in this browser");let i={...t,challenge:_(t.challenge),user:{...t.user,id:_(t.user.id)},excludeCredentials:t.excludeCredentials?.map(te)},o={};n&&(o.mediation="conditional"),o.publicKey=i,o.signal=ie.createNewAbortSignal();let a;try{a=await navigator.credentials.create(o);}catch(h){throw We({error:h,options:o})}if(!a)throw new Error("Registration was not completed");let{id:r,rawId:s,response:c,type:l}=a,u;typeof c.getTransports=="function"&&(u=c.getTransports());let f;if(typeof c.getPublicKeyAlgorithm=="function")try{f=c.getPublicKeyAlgorithm();}catch(h){Re("getPublicKeyAlgorithm()",h);}let g;if(typeof c.getPublicKey=="function")try{let h=c.getPublicKey();h!==null&&(g=E(h));}catch(h){Re("getPublicKey()",h);}let m;if(typeof c.getAuthenticatorData=="function")try{m=E(c.getAuthenticatorData());}catch(h){Re("getAuthenticatorData()",h);}return {id:r,rawId:E(s),response:{attestationObject:E(c.attestationObject),clientDataJSON:E(c.clientDataJSON),transports:u,publicKeyAlgorithm:f,publicKey:g,authenticatorData:m},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:oe(a.authenticatorAttachment)}}function Re(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 Ye(){if(!F())return Se.stubThis(new Promise(t=>t(false)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?Se.stubThis(new Promise(t=>t(false))):Se.stubThis(e.isConditionalMediationAvailable())}var Se={stubThis:e=>e};function Xe({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 O({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else {if(e.name==="NotAllowedError")return new O({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let i=globalThis.location.hostname;if(ne(i)){if(n.rpId!==i)return new O({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new O({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new O({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 Qe(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=false,verifyBrowserAutofillInput:i=true}=e;if(!F())throw new Error("WebAuthn is not supported in this browser");let o;t.allowCredentials?.length!==0&&(o=t.allowCredentials?.map(te));let a={...t,challenge:_(t.challenge),allowCredentials:o},r={};if(n){if(!await Ye())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');r.mediation="conditional",a.allowCredentials=[];}r.publicKey=a,r.signal=ie.createNewAbortSignal();let s;try{s=await navigator.credentials.get(r);}catch(m){throw Xe({error:m,options:r})}if(!s)throw new Error("Authentication was not completed");let{id:c,rawId:l,response:u,type:f}=s,g;return u.userHandle&&(g=E(u.userHandle)),{id:c,rawId:E(l),response:{authenticatorData:E(u.authenticatorData),clientDataJSON:E(u.clientDataJSON),signature:E(u.signature),userHandle:g},type:f,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:oe(s.authenticatorAttachment)}}var Ze=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),re=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 ae(e){if(e===void 0)return {valid:true,value:void 0};for(let n of e){let i=n.codePointAt(0);if(i===void 0||tt(n,i)||et(i)||Ze.has(i))return {valid:false}}let t=jn(e);return ke(t)?{valid:true,value:t}:{valid:false}}function ke(e){let t=0,n,i;for(let o of e){if(t+=1,t>256)return false;let a=o.codePointAt(0);if(a===void 0||tt(o,a)||et(a)||Ze.has(a))return false;n??=a,i=a;}return t>0&&n!==void 0&&i!==void 0&&!re.has(n)&&!re.has(i)}function se(){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 jn(e){let t=0,n=e.length;for(;t<n;){let i=e.codePointAt(t);if(i===void 0||!re.has(i))break;t+=i>65535?2:1;}for(;n>t;){let i=e.codePointAt(n-1);if(i===void 0)break;let a=i>=56320&&i<=57343?n-2:n-1,r=e.codePointAt(a);if(r===void 0||!re.has(r))break;n=a;}return e.slice(t,n)}function et(e){return e>=0&&e<=31||e>=127&&e<=159}function tt(e,t){return e.length===1&&t>=55296&&t<=57343}var ot=12,rt=5e3,Gn=8,Jn=1e3,Wn=16,nt=512,at=100,st=8192,$n=32768,Te=1024,it=256,Ee=64,Yn=6e5,Xn=/^[A-Za-z0-9_-]+$/u,Qn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,Zn=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,ei=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,ti=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,ct=new Set(["discouraged","preferred","required"]),ni=new Set(["singleDevice","multiDevice"]),ut=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),lt=new Set(["hybrid","security-key","client-device"]),ii=new Set(["none","indirect","direct","enterprise"]),oi=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),ri=new Set(["platform","cross-platform"]),ai=new Set(["discouraged","preferred","required"]),si=new Set([-8,-7,-257]);function dt(e){let t=q$1(e,ot,rt);return {challenge:wt(t.challenge),...b("timeout",yt(t.timeout)),...b("rpId",Rt(t.rpId)),...b("allowCredentials",Ot(t.allowCredentials)),...b("userVerification",J(t.userVerification,ct)),...b("hints",ce(t.hints,lt)),...b("extensions",bt(t.extensions))}}function pt(e){let t=q$1(e,ot,rt);return {challenge:wt(t.challenge),rp:ci(t.rp),user:ui(t.user),pubKeyCredParams:li(t.pubKeyCredParams),...b("timeout",yt(t.timeout)),...b("excludeCredentials",Ot(t.excludeCredentials)),...b("authenticatorSelection",di(t.authenticatorSelection)),...b("attestation",J(t.attestation,ii)),...b("attestationFormats",ce(t.attestationFormats,oi)),...b("hints",ce(t.hints,lt)),...b("extensions",bt(t.extensions))}}function ft(e){let t=h(e),n$1=o(t.session),i=n(t.user);return n$1.userId!==i.id&&p(),{session:n$1,user:i}}function xe(e){let t=h(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&p();let i=De(t.deviceType,ni),o=j(t.backedUp);return o&&i!=="multiDevice"&&p(),{id:q(t.id,it),...gi(t),publicKey:pi(t.publicKey,$n),userId:q(t.userId,it),credentialID:le(t.credentialID,st),counter:n,deviceType:i,backedUp:o,...mi(t),createdAt:k(t.createdAt),...hi(t)}}function gt(e,t,n){let i=xe(e);return (i.credentialID!==t||(n===void 0?i.name!==void 0&&i.name!==null:i.name!==n))&&p(),i}function mt(e){(!Array.isArray(e)||e.length>at)&&p();let t=e.map(xe);return ue(t.map(n=>n.id)),ue(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&p(),t}function ht(e,t,n){let i=h(e),o=xe(i.passkey);return (o.id!==t||o.name!==n)&&p(),{passkey:o}}function At(e){return h(e).status!==true&&p(),{status:true}}function ci(e){let t=h(e);return {name:Ie(t.name,Te),...b("id",Rt(t.id))}}function ui(e){let t=h(e);return {id:le(t.id,128,1,64),name:Ie(t.name,Te),displayName:Ie(t.displayName,Te)}}function li(e){(!Array.isArray(e)||e.length===0||e.length>Ee)&&p();let t=e.map(n=>{let i=h(n);return (i.type!=="public-key"||!Number.isSafeInteger(i.alg)||!si.has(i.alg))&&p(),{type:"public-key",alg:i.alg}});return Ai(t.map(n=>n.alg)),t}function Ot(e){if(e===void 0)return;(!Array.isArray(e)||e.length>at)&&p();let t=e.map(n=>{let i=h(n);return i.type!=="public-key"&&p(),{type:"public-key",id:le(i.id,st),...b("transports",ce(i.transports,ut))}});return ue(t.map(n=>n.id)),t}function di(e){if(e===void 0)return;let t=h(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&p();let n=J(t.residentKey,ai);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&p(),{...b("authenticatorAttachment",J(t.authenticatorAttachment,ri)),...b("residentKey",n),...b("requireResidentKey",t.requireResidentKey),...b("userVerification",J(t.userVerification,ct))}}function yt(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>Yn)&&p(),e}function bt(e){return e===void 0?void 0:q$1(e,Gn,Jn)}function ce(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>Ee)&&p();let n=e.map(i=>De(i,t));return ue(n),n}function J(e,t){if(e!==void 0)return De(e,t)}function wt(e){return le(e,Math.ceil(nt*4/3),Wn,nt)}function le(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=q(e,t),a=o.length%4,r=fi(o.at(-1)??""),s=Math.floor(o.length*3/4);return (!Xn.test(o)||a===1||a===2&&(r&15)!==0||a===3&&(r&3)!==0||s<n||s>i)&&p(),o}function q(e,t){let n=i(e);return (n.length===0||n.length>t)&&p(),n}function Ie(e,t){let n=q(e,t);return Zn.test(n)&&p(),n}function Rt(e){if(e===void 0)return;let t=q(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!ei.test(n)))&&p(),t}function pi(e,t){let n=q(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",r=St(a);return (n.length%4!==0||!Qn.test(n)||i&&(r&15)!==0||o&&(r&3)!==0)&&p(),n}function fi(e){return St(e,true)}function St(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function gi(e){let t=m(e,"name");return t===void 0?{}:(t!==null&&!ke(t)&&p(),{name:t})}function mi(e){let t=m(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>Ee||n.some(i=>!ut.has(i))||new Set(n).size!==n.length)&&p(),{transports:t}}function hi(e){let t=m(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(ti.test(t)||p(),{aaguid:t})}function De(e,t){let n=i(e);return t.has(n)||p(),n}function b(e,t){return t===void 0?{}:{[e]:t}}function ue(e){new Set(e).size!==e.length&&p();}function Ai(e){new Set(e).size!==e.length&&p();}function Et(e,t){let n=new Map;return {async signIn(i={},o){let a=await e.request("/passkey/generate-authenticate-options");if(!a.data)return Tt(a.error);let r;try{r=dt(a.data);}catch{return kt()}let s;try{s=await Qe({optionsJSON:r,useBrowserAutofill:i.autoFill});}catch(g){return It(g,"AUTH_CANCELLED","Passkey authentication was cancelled.")}let{clientExtensionResults:c,...l}=s,u=n.get(s.id);if(u)return u;let f=(async()=>{let g=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:l},fetchOptions:o,decode:ft});return g.data&&t(),g})();n.set(s.id,f);try{return await f}finally{n.get(s.id)===f&&n.delete(s.id);}},async add(i={},o){let a=ae(i.name);if(!a.valid)return se();let r=await e.request("/passkey/generate-register-options",{query:{name:a.value,authenticatorAttachment:i.authenticatorAttachment}});if(!r.data)return Tt(r.error);let s;try{s=pt(r.data);}catch{return kt()}let c;try{c=await $e({optionsJSON:s});}catch(g){return It(g,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}let{clientExtensionResults:l,...u}=c,f=await e.request("/passkey/verify-registration",{method:"POST",body:{response:u,name:a.value},fetchOptions:o,decode:g=>gt(g,c.id,a.value)});return f.data&&t(),f}}}function kt(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function Tt(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function It(e,t,n){let i=yi(e,"page does not have focus"),o=e instanceof O?e.code==="ERROR_CEREMONY_ABORTED":Oi(e)==="AbortError",a=t==="AUTH_CANCELLED"?"Passkey authentication could not be completed by this browser.":"Passkey registration could not be completed by this browser.";return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:i?"PASSKEY_PAGE_NOT_FOCUSED":o?t:e instanceof O?e.code:"PASSKEY_BROWSER_ERROR",message:i?"Keep this page focused while completing the passkey prompt.":o?n:a}}}function Oi(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function yi(e,t){let n=t.toLowerCase(),i=new Set,o=e;for(;o&&typeof o=="object"&&!i.has(o);){if(i.add(o),"message"in o&&typeof o.message=="string"&&o.message.toLowerCase().includes(n))return true;o="cause"in o?o.cause:void 0;}return false}function Dt(e,t){let n=new Set,i=null,o=null,a=null,r,s=m=>{u(m);};r={data:null,isPending:true,isRefetching:false,error:null,refetch:s};function c(m){r=m;for(let h of n)h();}async function l(m){return e.request("/get-session",{query:m?.query,decode:xt})}async function u(m){a?.abort();let h=new AbortController;a=h,c({...r,isPending:r.data===null&&r.error===null,isRefetching:r.data!==null});let z=await e.request("/get-session",{query:m?.query,fetchOptions:{signal:h.signal},decode:xt});a===h&&(a=null,c({data:z.data,error:z.error,isPending:false,isRefetching:false,refetch:s}));}function f(){if(typeof window>"u"||o)return;let m=()=>{u();},h=()=>{document.visibilityState==="visible"&&u();};window.addEventListener("focus",m),document.addEventListener("visibilitychange",h),typeof BroadcastChannel<"u"&&(i=new BroadcastChannel(`authowl:${t}`),i.addEventListener("message",m)),o=()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",h),i?.close(),i=null,o=null;};}function g(m){return n.add(m),n.size===1&&(f(),u()),()=>{n.delete(m),n.size===0&&(a?.abort(),a=null,o?.());}}return {store:{subscribe:g,getSnapshot:()=>r},getSession:l,notifyMutation(){i?.postMessage({type:"session-changed"}),n.size>0&&u({query:{disableCookieCache:true}});}}}function xt(e){if(e===null)return null;let t=h(e);return (t.session===void 0||t.user===void 0)&&p(),{session:o(t.session),user:n(t.user)}}function Pe(){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 Pt(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:vt})}async function Ct(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:vt})}function vt(e){let t=h(e),n=q$1(t.public_metadata),i=q$1(t.unsafe_metadata);if(!Number.isSafeInteger(t.metadata_version)||t.metadata_version<0)throw new TypeError("Invalid AuthOwl metadata response");return {publicMetadata:n,unsafeMetadata:i,metadataVersion:t.metadata_version}}function Ut(e,t){let{post:n,mutation:i}=V(e,t);return {getMetadata:o=>Pt(e,o),updateUnsafeMetadata:(o,a)=>Ct(e,o,a),updateProfile:(o,a)=>i(n("/update-user",o,a,W)),changeEmail:(o,a)=>i(n("/change-email",o,a,W)),changePassword:(o,a)=>i(n("/change-password",o,a,bi)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:wi}),revokeSession:({sessionId:o},a)=>i(n("/revoke-session",{sessionId:o},a,W)),revokeOtherSessions:o=>i(n("/revoke-other-sessions",{},o,W)),listSocialAccounts:async o=>{let a=await e.request("/list-accounts",{fetchOptions:o,decode:Ri});if(!a.data)return {data:null,error:a.error};let r=a.data.length>1;return {...a,data:a.data.filter(s=>s.providerId!=="credential").map(s=>({...s,canUnlink:r}))}},linkSocial:(o,a)=>n("/link-social",o,a,Si),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,W)),delete:(o={},a)=>i(n("/delete-user",o,a,ki))}}function W(e){let t=h(e);return {status:j(t.status)}}function bi(e){let t=h(e);return {user:n(t.user)}}function wi(e){return Array.isArray(e)||p(),e.map(t=>{let n=h(t);return {id:i(n.id),userId:i(n.userId),createdAt:k(n.createdAt),updatedAt:k(n.updatedAt),expiresAt:k(n.expiresAt),...zt("ipAddress",m(n,"ipAddress")),...zt("userAgent",m(n,"userAgent"))}})}function Ri(e){return Array.isArray(e)||p(),e.map(t=>{let n=h(t);return {id:i(n.id),userId:i(n.userId),providerId:i(n.providerId),accountId:i(n.accountId),scopes:l(n.scopes),createdAt:k(n.createdAt),updatedAt:k(n.updatedAt)}})}function Si(e){let t=h(e);return {url:i(t.url),redirect:j(t.redirect)}}function ki(e){let t=h(e);return {success:j(t.success),message:i(t.message)}}function zt(e,t){return t===void 0?{}:{[e]:t}}var Ti=new Set(["pending","accepted","rejected","canceled"]),Nt=1e4;function K(e,t,n){let i=h(e),o={id:A(i.id),name:A(i.name),slug:A(i.slug),createdAt:k(i.createdAt),...de("logo",m(i,"logo")),...de("metadata",i.metadata===void 0?void 0:r(i.metadata))};return U(o.id,t),U(o.slug,n),o}function _t(e){return N(e,K)}function Ce(e,t,n){return e===null?null:(t===null&&p(),K(e,t,n))}function Ft(e,t,n){if(e===null)return null;let i=h(e),o=K(i,t,n);return {...o,members:N(i.members,a=>Yt(a,o.id)),invitations:N(i.invitations,a=>C(a,void 0,o.id))}}function Mt(e,t){let n=N(e,i=>$t(i));return pe(n.map(i=>i.organizationId),t),n}function Lt(e,t,n){return e===null?null:(t===null&&p(),$t(e,t,n))}function Vt(e,t){let n=h(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&p(),{members:Ii(n.members,t),total:n.total}}function C(e,t,n){let i=h(e),o=A(i.status);Ti.has(o)||p();let a={id:A(i.id),organizationId:A(i.organizationId),email:A(i.email),role:A(i.role),status:o,inviterId:A(i.inviterId),expiresAt:k(i.expiresAt),createdAt:k(i.createdAt)};return U(a.id,t),U(a.organizationId,n),a}function qt(e,t){let n=N(e,i=>C(i));return pe(n.map(i=>i.organizationId),t),n}function Kt(e){return N(e,t=>{let n=h(t);return {...C(n),organizationName:A(n.organizationName)}})}function Bt(e,t){let n=h(e);return {...C(n,t),organizationName:A(n.organizationName),organizationSlug:A(n.organizationSlug),inviterEmail:A(n.inviterEmail)}}function Ht(e,t){let n=h(e),i=C(n.invitation,t);return {invitation:i,member:B(n.member,void 0,i.organizationId)}}function jt(e,t){let n=h(e);return n.member!==null&&p(),{invitation:n.invitation===null?null:C(n.invitation,t),member:null}}function Gt(e,t){return e===null?null:C(e,t)}function Jt(e,t,n){let i=h(e);return {member:B(i.member,n,t)}}function B(e,t,n){let i=h(e),o={id:A(i.id),organizationId:A(i.organizationId),userId:A(i.userId),role:A(i.role),createdAt:k(i.createdAt),...i.user===void 0?{}:{user:Xt(i.user)}};return U(o.id,t),U(o.organizationId,n),o}function Wt(e,t){let n=N(e,i=>{let o=h(i);return {organizationId:A(o.organizationId),data:{role:A(o.role),...de("permission",o.permission===void 0?void 0:Ei(o.permission))}}});return pe(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function $t(e,t,n){let i=h(e),o=i.updatedAt,a={id:A(i.id),name:A(i.name),organizationId:A(i.organizationId),createdAt:k(i.createdAt),...o===void 0?{}:{updatedAt:k(o)}};return U(a.id,t),U(a.organizationId,n),a}function Yt(e,t){let n=h(e);return {...B(n,void 0,t),user:Xt(n.user)}}function Ii(e,t){let n=N(e,i=>Yt(i));return pe(n.map(i=>i.organizationId),t),n}function Ei(e){let t=h(e),n={};for(let[i,o]of Object.entries(t))(i==="__proto__"||i==="constructor"||i==="prototype"||i.length===0||i.length>Nt||!Array.isArray(o))&&p(),n[i]=o.map(a=>A(a));return n}function A(e){let t=i(e);return (t.length===0||t.length>Nt)&&p(),t}function U(e,t){t!==void 0&&e!==t&&p();}function pe(e,t){let n=t??e[0];n!==void 0&&e.some(i=>i!==n)&&p();}function Xt(e){let t=h(e);return {id:A(t.id),name:A(t.name),email:A(t.email),...de("image",m(t,"image"))}}function N(e,t){return Array.isArray(e)||p(),e.map(n=>t(n))}function de(e,t){return t===void 0?{}:{[e]:t}}function Qt(e,t,n=()=>null){let{post:i,mutation:o}=V(e,t),a=(r,s,c,l)=>e.request(r,{query:s,fetchOptions:c,decode:l});return {create:(r,s)=>o(i("/organization/create",r,s,K)),list:r=>a("/organization/list",void 0,r,_t),get:(r={},s)=>a("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},s,c=>Ft(c,r.organizationId,r.organizationSlug)),setActive:(r,s)=>o(i("/organization/set-active",r,s,c=>Ce(c,r.organizationId,r.organizationSlug))),listTeams:(r={},s)=>a("/organization/list-teams",{organizationId:r.organizationId},s,c=>Mt(c,r.organizationId)),setActiveTeam:(r,s)=>o(i("/organization/set-active-team",r,s,c=>Lt(c,r.teamId))),update:(r,s)=>o(i("/organization/update",r,s,c=>Ce(c,r.organizationId))),delete:(r,s)=>o(i("/organization/delete",r,s,c=>K(c,r.organizationId))),listMembers:(r={},s)=>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},s,c=>Vt(c,r.organizationId)),inviteMember:(r,s)=>o(i("/organization/invite-member",r,s,c=>C(c,void 0,r.organizationId))),listInvitations:(r={},s)=>a("/organization/list-invitations",{organizationId:r.organizationId},s,c=>qt(c,r.organizationId)),listUserInvitations:r=>a("/organization/list-user-invitations",void 0,r,Kt),getInvitation:(r,s)=>a("/organization/get-invitation",{id:r.id},s,c=>Bt(c,r.id)),acceptInvitation:(r,s)=>o(i("/organization/accept-invitation",r,s,c=>Ht(c,r.invitationId))),rejectInvitation:(r,s)=>o(i("/organization/reject-invitation",r,s,c=>jt(c,r.invitationId))),cancelInvitation:(r,s)=>o(i("/organization/cancel-invitation",r,s,c=>Gt(c,r.invitationId))),removeMember:(r,s)=>o(i("/organization/remove-member",r,s,c=>Jt(c,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,s)=>o(i("/organization/update-member-role",r,s,c=>B(c,r.memberId,r.organizationId))),leave:(r,s)=>o(i("/organization/leave",r,s,c=>B(c,void 0,r.organizationId))),listRoles:(r={},s)=>a("/organization/list-roles",{organizationId:r.organizationId},s,c=>Wt(c,r.organizationId)),has:r=>u(n(),r),hasPermission:r=>s(n(),r.permission)}}var Zt=4096,xi=4096,Di=100,Pi=256,Ci=16,vi=64;function ze(e){let t=h(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:An(t.twoFactorMethods,Ci,vi)}}):(t.twoFactorRedirect!==void 0&&p(),{redirect:j(t.redirect),..._i(t,"url"),user:n(t.user)})}function en(e){let t=h(e);return {user:n(t.user)}}function tn(e){let t=h(e);return {sessionCreated:j(t.sessionCreated),user:n(t.user)}}function nn(e,t){let n$1=h(e),i=j(n$1.redirect);n$1.user===null&&p();let o=n$1.user!==void 0&&n$1.user!==null,a=n$1.url!==void 0&&n$1.url!==null;return i?((o||!a)&&p(),{redirect:true,url:ve(n$1.url,t)}):(o===a&&p(),o?{redirect:false,user:n(n$1.user)}:{redirect:false,url:ve(n$1.url,t)})}function on(e,t){let n=h(e);return (n.redirect!==true||n.user!==void 0)&&p(),{redirect:true,url:ve(n.url,t)}}function rn(e){return {status:j(h(e).status)}}function an(e){return {success:j(h(e).success)}}function sn(e){return h(e).status!=="pending"&&p(),{status:"pending"}}function cn(e){let t=h(e);return (t.status!==true||t.sessionCreated!==true)&&p(),{status:true,sessionCreated:true,user:zi(t.user)}}function Ue(e){return {status:j(h(e).status)}}function un(e){return {status:j(h(e).status)}}function ln(e){let t=h(e);return {status:j(t.status),user:n(t.user)}}function dn(e){return {success:j(h(e).success)}}function pn(e){let t=h(e);return {totpURI:Ni(t.totpURI),backupCodes:hn(t.backupCodes)}}function fn(e){return {status:j(h(e).status)}}function fe(e){return h(e).status!==true&&p(),{status:true}}function gn(e){return {status:j(h(e).status)}}function mn(e){let t=h(e);return t.status!==void 0&&t.status!==true&&p(),{backupCodes:hn(t.backupCodes)}}function zi(e){let t=h(e);return {id:H(t.id,512),...Fi(t,"name",1024),phoneNumber:H(t.phoneNumber,64),phoneNumberVerified:j(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:k(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:k(t.updatedAt)}}}function ve(e,t){let n=H(e,Zt);/[\u0000-\u0020\u007f]/u.test(n)&&p();let i;try{i=new URL(n);}catch{return p()}return (i.username||i.password)&&p(),i.protocol==="https:"||t&&i.protocol==="http:"&&Ui(i.hostname)?i.href:p()}function Ui(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Ni(e){let t=H(e,xi),n;try{n=new URL(t);}catch{return p()}let i=n.searchParams.get("secret");return (n.protocol!=="otpauth:"||n.hostname.toLowerCase()!=="totp"||n.username||n.password||n.hash||i===null||i.length===0||i.length>512||/\s/u.test(i))&&p(),t}function hn(e){return An(e,Di,Pi)}function An(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&p();let i=e.map(o=>H(o,n));return i.some(o=>o.trim().length===0)&&p(),new Set(i).size!==i.length&&p(),i}function H(e,t){let n=i(e);return (n.length===0||n.length>t)&&p(),n}function _i(e,t){let n=e[t];return n==null?{}:{[t]:H(n,Zt)}}function Fi(e,t,n){let i=m(e,t);return i===void 0?{}:(i!==null&&i.length>n&&p(),{[t]:i})}function On(e,t=()=>{}){let n=ee(e),i=Dt(n,e.decoded.projectId),o=Et(n,i.notifyMutation),a=()=>{i.notifyMutation(),t();},{post:r,mutation:s}=V(n,a),c=e.decoded.env==="test";return {sessionStore:i.store,getSession:i.getSession,account:Ut(n,a),organization:Qt(n,a,()=>i.store.getSnapshot().data?.session.membership??null),signIn:{email:(l,u)=>s(r("/sign-in/email",l,u,ze),f=>!("twoFactorRedirect"in f)),username:(l,u)=>s(r("/sign-in/username",l,u,ze),f=>!("twoFactorRedirect"in f)),social:async(l,u)=>{let f=await s(r("/sign-in/social",l,u,g=>nn(g,c)),g=>"user"in g);return f.error!==null||f.data===null||"url"in f.data&&f.data.redirect&&!l.disableRedirect&&typeof window<"u"&&window.location.assign(f.data.url),f},sso:async(l,u)=>{let f=await r("/sign-in/sso",l,u,g=>on(g,c));return f.error!==null||f.data===null||typeof window<"u"&&window.location.assign(f.data.url),f},magicLink:(l,u)=>r("/sign-in/magic-link",l,u,rn),emailOtp:(l,u)=>s(r("/sign-in/email-otp",l,u,en)),passkey:(l,u)=>o.signIn(l,u)},signUp:{email:(l,u)=>s(r("/sign-up/email",l,u,tn),f=>f.sessionCreated)},emailOtp:{sendVerificationOtp:(l,u)=>r("/email-otp/send-verification-otp",l,u,an),verifyEmail:(l,u)=>s(r("/email-otp/verify-email",l,u,ln))},phoneOtp:{start:(l,u)=>r("/phone-otp/start",{...l,idempotencyKey:l.idempotencyKey??Pe()},u,sn),verify:(l,u)=>s(r("/phone-otp/verify",l,u,cn))},requestPasswordReset:(l,u)=>r("/request-password-reset",l,u,Ue),resetPassword:(l,u)=>r("/reset-password",l,u,Ue),sendVerificationEmail:(l,u)=>r("/send-verification-email",l,u,un),passkey:{addPasskey:(l,u)=>o.add(l,u),listUserPasskeys:()=>n.request("/passkey/list-user-passkeys",{decode:mt}),updatePasskey:async(l,u)=>{let f=ae(l.name);if(!f.valid||f.value===void 0)return se();let g=f.value;return r("/passkey/update-passkey",{...l,name:g},u,m=>ht(m,l.id,g))},deletePasskey:(l,u)=>r("/passkey/delete-passkey",l,u,At)},twoFactor:{enable:(l,u)=>r("/two-factor/enable",l,u,pn),disable:(l,u)=>s(r("/two-factor/disable",l,u,fn),f=>f.status),verifyTotp:(l,u)=>s(r("/two-factor/verify-totp",l,u,fe)),verifyBackupCode:(l,u)=>s(r("/two-factor/verify-backup-code",l,u,fe)),sendOtp:(l={},u)=>r("/two-factor/send-otp",l,u,gn),verifyOtp:(l,u)=>s(r("/two-factor/verify-otp",l,u,fe)),generateBackupCodes:(l,u)=>r("/two-factor/generate-backup-codes",l,u,mn)},signOut:l=>s(n.request("/sign-out",{method:"POST",body:{},fetchOptions:l,decode:dn}),u=>u.success)}}var ge=class extends Error{status;requestId;constructor(t,n,i){super(`${t} request failed with status ${n.status}.`),this.name="AuthOwlHttpError",this.status=n.status,this.requestId=i;}};function M(e,t,n={}){let i=new Headers(n.init?.headers);return i.set("x-publishable-key",e.publishableKey),g({fetchImpl:e.fetch??fetch,url:t,init:{...n.init,headers:i},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 L(e,t){if(!e.response.ok)throw new ge(t,e.response,e.requestId);return e.data}function bn(e){return `${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/consent`}async function Ne(e){let t=await M(e,bn(e),{init:{method:"GET",credentials:"include"},maxResponseBytes:65536,decode:Mi});return t.response.status===401?{required:false}:L(t,"consent status")}async function _e(e,t){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Consent version must be a positive integer.");return L(await M(e,bn(e),{init:{method:"POST",headers:{"content-type":"application/json"},credentials:"include",body:JSON.stringify({version:t})},maxResponseBytes:64*1024,decode:Li}),"consent accept")}function Mi(e){let t=h(e),n=j(t.required),i=Vi(t.needsConsent),o=wn(t.version),a=yn(t.termsUrl),r=yn(t.privacyUrl);return {required:n,...i===void 0?{}:{needsConsent:i},...o===void 0?{}:{version:o},...a===void 0?{}:{termsUrl:a},...r===void 0?{}:{privacyUrl:r}}}function Li(e){let t=h(e),n=wn(t.version);return {ok:j(t.ok),...n===void 0?{}:{version:n}}}function Vi(e){if(e===void 0||typeof e=="boolean")return e;throw new TypeError("Invalid consent response.")}function wn(e){if(e===void 0||Number.isSafeInteger(e)&&e>=1)return e;throw new TypeError("Invalid consent response.")}function yn(e){if(e===void 0||typeof e=="string"&&e.length<=4096)return e;throw new TypeError("Invalid consent response.")}var qi=30;function Ki(e){return typeof e?.exp=="number"?e.exp:null}function Bi(e){let t=e.split(".")[1];if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(n));return typeof i=="object"&&i!==null?i:null}catch{return null}}function Fe(e){let t=new Map;async function n(a={}){let r=a.template===void 0?null:a.template.trim().toLowerCase();if(r==="")throw new TypeError("Template missing");let s=r??"",c=t.get(s);c||(c={activeKey:null,cachedByKey:new Map,inflight:null,sequence:0},t.set(s,c));let l=a.forceRefresh===true;if(!l){let h=c.activeKey?c.cachedByKey.get(c.activeKey):null;if(h&&h.exp-Date.now()/1e3>qi)return h.token;if(c.inflight)return c.inflight}let u=++c.sequence,f=()=>t.get(s)===c&&c.sequence===u,g=(async()=>{let h=r?`${e.projectBaseURL}/token/${encodeURIComponent(r)}`:`${e.projectBaseURL}/token`,z=await M(e,h,{init:{method:"GET",credentials:"include"},maxResponseBytes:64*1024,decode:X=>Hi(X,r!==null)});if(z.response.status===401)return f()&&i(),null;let D=L(z,"token"),Y=D.policyVersion,me=D.token,j=Bi(me),qe=Ki(j);if(f())if(qe!==null){let X=typeof j?.sub=="string"?j.sub:null,Tn=typeof j?.org_id=="string"?j.org_id:null;if(!r||X){let Ke=JSON.stringify([e.projectBaseURL,X,Tn,r,Y]);c.cachedByKey.clear(),c.cachedByKey.set(Ke,{token:me,exp:qe}),c.activeKey=Ke;}else o(c);}else o(c);return me})();if(l)return g;let m=g.finally(()=>{c.inflight===m&&(c.inflight=null);});return c.inflight=m,m}function i(){t.clear();}function o(a){a.cachedByKey.clear(),a.activeKey=null;}return {getToken:n,clear:i}}function Hi(e,t){let n=h(e),i$1=i(n.token);if(i$1.length===0||i$1.length>32*1024)throw new TypeError("Invalid token response.");if(!t)return {token:i$1,policyVersion:0};let o=h(n.template);if(!Number.isSafeInteger(o.policyVersion)||o.policyVersion<1)throw new TypeError("Invalid token response.");return {token:i$1,policyVersion:o.policyVersion}}function ji(e){let t=Fe(e),n=On(e,t.clear),i=ee(e,`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}`),o=r=>(...s)=>(t.clear(),r(...s)),a={getConsentStatus:()=>Ne(e),acceptConsent:r=>_e(e,r),getToken:t.getToken,waitlist:{join:(r,s)=>i.request("/waitlist",{method:"POST",body:r,fetchOptions:s,credentials:"omit"})},account:{...n.account,updateUnsafeMetadata:o(n.account.updateUnsafeMetadata),updateProfile:o(n.account.updateProfile),changeEmail:o(n.account.changeEmail),changePassword:o(n.account.changePassword),revokeSession:o(n.account.revokeSession),delete:o(n.account.delete)},signIn:{email:o(n.signIn.email),username:o(n.signIn.username),social:o(n.signIn.social),sso:n.signIn.sso,magicLink:n.signIn.magicLink,emailOtp:o(n.signIn.emailOtp),passkey:o(n.signIn.passkey)},signUp:{email:o(n.signUp.email)},emailOtp:{...n.emailOtp,verifyEmail:o(n.emailOtp.verifyEmail)},twoFactor:{enable:n.twoFactor.enable,disable:o(n.twoFactor.disable),verifyTotp:o(n.twoFactor.verifyTotp),verifyBackupCode:o(n.twoFactor.verifyBackupCode),sendOtp:n.twoFactor.sendOtp,verifyOtp:o(n.twoFactor.verifyOtp),generateBackupCodes:n.twoFactor.generateBackupCodes},phoneOtp:{start:n.phoneOtp.start,verify:o(n.phoneOtp.verify)},signOut:o(n.signOut)};return {...n,...a}}async function Gi(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return L(await M(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>Ji(i,e)}),"public-config")}function Ji(e,t){let n=q$1(e),i=n.environmentId,o=n.environmentType,a=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Wi(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==a)throw x();let r=S(n.branding),s=S(n.legal);if(!Me(n.enabledMethods,64)||!Me(n.socialProviders,64)||!Sn(r,["appName","logoUrl","primaryColor"])||r.theme!==void 0&&r.theme!=="light"&&r.theme!=="dark"&&r.theme!=="system"||!Sn(s,["termsUrl","privacyUrl"])||!Number.isSafeInteger(s.version)||s.version<0||typeof s.required!="boolean")throw x();if(n.socialProviderClientIds!==void 0){let c=S(n.socialProviderClientIds);if(Object.keys(c).length>64||Object.values(c).some(l=>typeof l!="string"||l.length>2048))throw x()}if(!v(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!Rn(n.turnstileSiteKey)||!Rn(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw x();if(n.jwtIssuer!==null){let c=S(n.jwtIssuer);if(c.issuer!==a||c.jwksUrl!==`${a}/jwks`||c.aud!==t.decoded.projectId)throw x()}if(n.signUp!==void 0){let c=S(n.signUp).mode;if(typeof c!="string"||!["open","restricted","allowlist","waitlist"].includes(c))throw x()}if(n.authentication!==void 0&&$i(n.authentication),n.emailVerification!==void 0){let c=S(n.emailVerification);if(!v(c,["required"])||c.method!=="link"&&c.method!=="code")throw x()}if(n.userModel!==void 0&&!v(S(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw x();if(n.mfa!==void 0){let c=S(n.mfa);if(!v(c,["totp","required","backupCodes"])||(c.required===true||c.backupCodes===true)&&c.totp!==true)throw x()}return n}function Wi(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 x(){return new TypeError("public-config returned an invalid response")}function S(e){if(!e||typeof e!="object"||Array.isArray(e))throw x();return e}function Rn(e){return e===null||typeof e=="string"&&e.length<=4096}function $i(e){let t=S(e),n=S(t.email),i=S(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!v(n,["signUp"])||!Me(n.signIn,3)||n.signIn.some(a=>a!=="password"&&a!=="magic_link"&&a!=="email_otp")||!v(S(t.phone),["signUp","signIn"])||!v(i,["signUp","add"])||o&&(!Number.isSafeInteger(i.minLength)||!Number.isSafeInteger(i.maxLength)||i.minLength<1||i.maxLength>4096||i.minLength>i.maxLength)||!v(S(t.passkey),["signIn","add"])||!v(S(t.username),["collectOnSignUp","signIn"]))throw x()}function v(e,t){return t.every(n=>typeof e[n]=="boolean")}function Sn(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function Me(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 $=class extends Error{constructor(n,i){super(n);this.cause=i;this.name="AuthOwlError";}cause},Le=class extends ${constructor(n,i){super(`Rate limited. Retry after ${n}s.`,i);this.retryAfterSeconds=n;this.name="RateLimitedError";}retryAfterSeconds},Ve=class extends ${constructor(t="invalid publishable key",n){super(t,n),this.name="InvalidKeyError";}};var kn=["en","ar"];function Yi(e){return e==="ar"?"rtl":"ltr"}function Xi(e){return typeof e=="string"&&kn.includes(e)}
|
|
3
|
+
export{Je as AUTH_CHALLENGE_HEADER,$ as AuthOwlError,ge as AuthOwlHttpError,Ve as InvalidKeyError,kn as LOCALES,Le as RateLimitedError,_e as acceptConsent,ji as createAuthOwlClient,Pe as createIdempotencyKey,Fe as createTokenClient,Yi as directionFor,Ne as getConsentStatus,Gi as getPublicConfig,Xi as isLocale};
|
package/dist/server.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var me=new Set(["__proto__","constructor","prototype"]);function S(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function V(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&S(),le(e,t,n)}function le(e,t=20,n=1e4){return N(e,0,{nodes:0},t,n)}function N(e,t,n,r,o){if(n.nodes+=1,(t>r||n.nodes>o)&&S(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||S(),e;if(Array.isArray(e))return e.map(c=>N(c,t+1,n,r,o));(!e||typeof e!="object")&&S();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&S();let i={};for(let[c,d]of Object.entries(e))me.has(c)&&S(),i[c]=N(d,t+1,n,r,o);return i}var C=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function b(e,t){throw new Error(`${e}: ${t}`)}function fe(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function q(e,{label:t,allowHttpLoopback:n}){(typeof e!="string"||e.length===0)&&b(t,"required"),e!==e.trim()&&b(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&b(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&b(t,"path must be unencoded");let r;try{r=new URL(e);}catch{b(t,"absolute URL required");}return (r.username||r.password)&&b(t,"credentials forbidden"),r.protocol!=="https:"&&r.protocol!=="http:"&&b(t,"HTTPS required"),r.protocol==="http:"&&(!n||!C.test(e))&&b(t,"HTTPS required except exact loopback"),r}function L(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 r=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&C.test(r)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function B(e,t,n){let r=fe(e);(r.includes("//")||r.split("/").some(o=>o==="."||o==="..")||r!==""&&r!==t.pathname)&&b(n,"path traversal or duplicate separator");}function H(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&b("apiUrl","origin required");let n;try{n=new URL(e);}catch{b("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!C.test(e))&&b("apiUrl","HTTPS required except exact loopback"),n.origin}function F(e,t,n={allowHttpLoopback:false}){let r=q(e,{label:"issuer",allowHttpLoopback:n.allowHttpLoopback}),o=q(t,{label:"jwksUri",allowHttpLoopback:n.allowHttpLoopback});return B(e,r,"issuer"),B(t,o,"jwksUri"),r.pathname!=="/"&&r.pathname.endsWith("/")&&b("issuer","trailing slash forbidden"),{issuer:r.toString().replace(/\/$/,""),jwksUri:o.toString()}}var ye=1e4,he=1024*1024,A=class extends Error{kind;requestId;constructor(t,n){super(Oe(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},X=new WeakSet;function y(e,t){let n=new A(e,t);return X.add(n),n}async function j({fetchImpl:e,url:t,init:n={},timeoutMs:r=ye,maxResponseBytes:o=he,allowHttpLoopback:s=false,decode:i}){Y(r,"timeoutMs"),Y(o,"maxResponseBytes");let c=L(t,{allowHttpLoopback:s}),d=n.signal,u=new AbortController,m=null,g,p=new Promise(l=>{g=l;}),w=l=>{m===null&&(m=l,g({type:"abort",kind:l}),u.abort());},h=()=>w("aborted");d?.addEventListener("abort",h,{once:true});let _=setTimeout(()=>w("timeout"),r);d?.aborted&&h();try{if(m!==null)throw y(m);let l;try{l=await Promise.race([e(c.toString(),{...n,redirect:"error",signal:u.signal}).then(ue=>({type:"response",response:ue})),p]);}catch{throw y(m??"network")}if(l.type==="abort")throw y(l.kind);if(!ge(l.response))throw y("invalid_response");let f=l.response,k=Se(f.headers),de=await be(f,o,p,()=>m,k),W=_e(f,de,k),J;try{J=f.ok&&i?i(W,Object.freeze({status:f.status})):W;}catch{throw y("invalid_response",k)}return {response:f,data:J,...k===void 0?{}:{requestId:k}}}catch(l){throw l instanceof A&&X.has(l)?l:y(m??"network")}finally{clearTimeout(_),d?.removeEventListener("abort",h);}}function ge(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 be(e,t,n,r,o){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw G(e.body),y("invalid_response",o);if(Number(s)>t)throw G(e.body),y("response_too_large",o)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw y("network",o)}let c=[],d=0,u=null;try{for(;;){let p;try{p=await Promise.race([i.read(),n]);}catch{u=y(r()??"network",o);break}if(we(p)){u=y(p.kind,o);break}let{done:w,value:h}=p;if(w)break;if(h.byteLength!==0){if(d+=h.byteLength,d>t){u=y("response_too_large",o);break}c.push(h);}}}finally{u&&Ae(i);try{i.releaseLock();}catch{}}if(u)throw u;let m=new Uint8Array(d),g=0;for(let p of c)m.set(p,g),g+=p.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(m)}catch{throw y("invalid_response",o)}}function we(e){return "type"in e&&e.type==="abort"}function G(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function Ae(e){try{e.cancel().catch(()=>{});}catch{}}function _e(e,t,n){if(e.status===204||e.status===205)return null;let r=ke(e.headers.get("content-type"));if(!e.ok&&(!r||t.length===0))return null;if(!r||t.length===0)throw y("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw y("invalid_response",n)}}function ke(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function Se(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Y(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Oe(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 a=class extends Error{code;constructor(t,n="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=n;}},Te=300*1e3,Ee=5e3,Ie=64*1024,Pe=64,xe=60*1e3,Z=new Map,Q=new Map;function z(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?t:t+"=".repeat(4-t.length%4),r=typeof atob=="function"?atob(n):globalThis.Buffer.from(n,"base64").toString("binary"),o=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}function ee(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(z(e)),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");return n}catch(t){throw t instanceof a?t:new a("Malformed JWT segment.","TOKEN_MALFORMED")}}function re(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function te(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&z(e).byteLength===32}function Re(e){if(!re(e))throw new a("JWKS contains a non-object key.","JWKS_KEY_INVALID");let t=new Set(["alg","crv","kid","kty","use","x","y"]),n=["d","p","q","dp","dq","qi","k","oth"];if("key_ops"in e||n.some(r=>r in e)||Object.keys(e).some(r=>!t.has(r)))throw new a("JWKS contains private, key_ops, or unexpected key members.","JWKS_KEY_INVALID");if(e.kty!=="EC"||e.crv!=="P-256"||e.alg!=="ES256"||e.use!=="sig"||typeof e.kid!="string"||e.kid.length===0||e.kid.length>128||!/^[A-Za-z0-9_-]+$/.test(e.kid)||!te(e.x)||!te(e.y))throw new a("JWKS contains a key outside the AuthOwl ES256 public-key schema.","JWKS_KEY_INVALID");return {alg:e.alg,crv:e.crv,kid:e.kid,kty:e.kty,use:e.use,x:e.x,y:e.y}}function Le(e){if(!re(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new a("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>Pe)throw new a("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(Re),n=new Set;for(let r of t){if(n.has(r.kid))throw new a("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");n.add(r.kid);}return t}async function ne(e,t){let n=Z.get(e);if(!t&&n&&Date.now()-n.fetchedAt<Te)return n.keys;try{let r=await j({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Ee,maxResponseBytes:Ie,allowHttpLoopback:new URL(e).protocol==="http:",decode:s=>V(s)});if(!r.response.ok)throw new a(`JWKS fetch returned ${r.response.status}.`,"JWKS_HTTP_ERROR");let o=Le(r.data);return Z.set(e,{keys:o,fetchedAt:Date.now()}),o}catch(r){if(r instanceof a)throw r;if(r instanceof A)switch(r.kind){case "timeout":throw new a("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new a("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new a("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new a("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function je(e,t){let n=o=>t?o.find(s=>s.kid===t):o[0],r=n(await ne(e,false));if(!r){let o=Q.get(e)??0;Date.now()-o>=xe&&(Q.set(e,Date.now()),r=n(await ne(e,true)));}if(!r)throw new a("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return r}function Ue(e){let t=globalThis.crypto?.subtle;if(!t)throw new a("WebCrypto is unavailable in this runtime.","WEBCRYPTO_UNAVAILABLE");return t.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y},{name:"ECDSA",namedCurve:"P-256"},false,["verify"])}function Ke(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function Ne(e){let t=e.membership;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,r=typeof n.role=="string"?n.role:"",o=Array.isArray(n.permissions)?n.permissions.filter(i=>typeof i=="string"):[],s=Array.isArray(n.teams)?n.teams.filter(i=>typeof i=="string"):void 0;return r===""&&o.length===0&&!s?.length?null:{role:r,permissions:o,...s===void 0?{}:{teams:s}}}async function Ce(e,t){return E(e,U(t))}function U(e,t=false){if(!e||typeof e!="object")throw new a("Token verification options are required.","TOKEN_CONFIG_INVALID");let n;try{n=F(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new a("Token verifier issuer or JWKS URL is invalid.","TOKEN_CONFIG_INVALID")}if(typeof e.audience!="string"||e.audience.length===0||e.audience.length>256)throw new a("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new a("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...n}}async function E(e,t){if(typeof e!="string"||e.length===0)throw new a("A token string is required.","TOKEN_MALFORMED");let n=e.split(".");if(n.length!==3)throw new a("Malformed JWT.","TOKEN_MALFORMED");let[r,o,s]=n,i=ee(r);if(i.alg!=="ES256")throw new a("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let c=await je(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),d;try{d=await Ue(c);}catch(_){throw _ instanceof a?_:new a("JWKS key could not be imported.","JWKS_KEY_INVALID")}let u;try{if(!/^[A-Za-z0-9_-]{86}$/.test(s))throw new Error("invalid signature encoding");if(u=z(s),u.byteLength!==64)throw new Error("invalid signature length")}catch{throw new a("Malformed JWT signature.","TOKEN_MALFORMED")}let m=new TextEncoder().encode(`${r}.${o}`),g;try{g=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,u,m);}catch{throw new a("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!g)throw new a("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let p=ee(o),w=t.clockToleranceSeconds??60,h=Math.floor(Date.now()/1e3);if(typeof p.exp!="number")throw new a("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(p.exp+w<h)throw new a("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof p.nbf=="number"&&p.nbf-w>h)throw new a("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof p.iss!="string"||p.iss!==t.issuer)throw new a("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!Ke(p.aud,t.audience))throw new a("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof p.sub=="string"?p.sub:null,membership:Ne(p),claims:p}}var ze=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,ve=/^sk_/i;function oe(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(ve.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=ze.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1],env:t[2],projectId:t[3]}}function v(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=oe(e.publishableKey),n=H(e.apiUrl,{allowHttpLoopback:t.env==="test"}),r=`${n}/api/projects/${t.projectId}/auth`;return {...e,apiUrl:n,decoded:t,projectBaseURL:r}}function se(e,t){return !e||!t?false:e.permissions.includes(t)}function Me(e,t){return !e||!t?false:e.teams?.includes(t)??false}function ie(e,t){if(!e)return false;let{role:n,permission:r,teamId:o}=t;return !(n===void 0&&r===void 0&&o===void 0||n!==void 0&&e.role!==n||r!==void 0&&!e.permissions.includes(r)||o!==void 0&&!Me(e,o))}function $e(e,t){let n=`p_${e.replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}var De="dc1953d9d9b9e1f7002fa045f12788280e5865bacfda94b1d133e9580aa87d62",I={getOpenApiDocument:{method:"GET",path:"/openapi.json",successStatuses:[200],responseSchemas:{200:{type:"object"}}},listUsers:{method:"GET",path:"/users",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserPage"}}},createUser:{method:"POST",path:"/users",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/User"}}},startUserExport:{method:"POST",path:"/users/export",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getUser:{method:"GET",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},updateUser:{method:"PATCH",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},deleteUser:{method:"DELETE",path:"/users/{userId}",successStatuses:[204],responseSchemas:{204:null}},listUserSessions:{method:"GET",path:"/users/{userId}/sessions",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionPage"}}},revokeUserSessions:{method:"DELETE",path:"/users/{userId}/sessions",successStatuses:[204],responseSchemas:{204:null}},updateUserMetadata:{method:"PATCH",path:"/users/{userId}/metadata",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserMetadata"}}},verifySession:{method:"POST",path:"/sessions/verify",successStatuses:[200],responseSchemas:{200:{type:"object",required:["user","session"],properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}},getSession:{method:"GET",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Session"}}},updateSessionMetadata:{method:"PATCH",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionMetadata"}}},revokeSession:{method:"DELETE",path:"/sessions/{sessionId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizations:{method:"GET",path:"/organizations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationPage"}}},createOrganization:{method:"POST",path:"/organizations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Organization"}}},getOrganization:{method:"GET",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},updateOrganization:{method:"PATCH",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},deleteOrganization:{method:"DELETE",path:"/organizations/{organizationId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationMembers:{method:"GET",path:"/organizations/{organizationId}/members",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MemberPage"}}},addOrganizationMember:{method:"POST",path:"/organizations/{organizationId}/members",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationMember"}}},updateOrganizationMember:{method:"PATCH",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationMember"}}},removeOrganizationMember:{method:"DELETE",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationRoles:{method:"GET",path:"/organizations/{organizationId}/roles",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/RolePage"}}},createOrganizationRole:{method:"POST",path:"/organizations/{organizationId}/roles",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationRole"}}},updateOrganizationRole:{method:"PATCH",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationRole"}}},deleteOrganizationRole:{method:"DELETE",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[204],responseSchemas:{204:null}},listInvitations:{method:"GET",path:"/invitations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/InvitationPage"}}},createInvitation:{method:"POST",path:"/invitations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Invitation"}}},getInvitation:{method:"GET",path:"/invitations/{invitationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Invitation"}}},revokeInvitation:{method:"DELETE",path:"/invitations/{invitationId}",successStatuses:[204],responseSchemas:{204:null}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},M={Problem:{type:"object",required:["type","title","status","detail","instance","code"],properties:{type:{type:"string",format:"uri"},title:{type:"string"},status:{type:"integer"},detail:{type:"string"},instance:{type:"string",format:"uri"},code:{type:"string"}},additionalProperties:true},User:{type:"object",required:["id","email","phone","name","image","email_verified","banned","public_metadata","private_metadata","unsafe_metadata","metadata_version","created_at","updated_at"],properties:{id:{type:"string"},email:{type:"string",format:"email"},phone:{type:["string","null"]},name:{type:["string","null"]},image:{type:["string","null"],format:"uri"},email_verified:{type:"boolean"},banned:{type:"boolean"},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateUser:{type:"object",required:["email"],properties:{email:{type:"string",format:"email",maxLength:320},password:{type:"string",minLength:8,maxLength:128},name:{type:"string",minLength:1,maxLength:200},phone:{type:"string",minLength:1,maxLength:32}},additionalProperties:false},UpdateUser:{type:"object",minProperties:1,properties:{email:{type:"string",format:"email",maxLength:320},name:{type:["string","null"],minLength:1,maxLength:200},phone:{type:["string","null"],minLength:1,maxLength:32},banned:{type:"boolean"}},additionalProperties:false},MetadataObject:{type:"object",maxProperties:100,description:"JSON metadata object. Reserved prototype keys and the authowl_ prefix are rejected at every depth. Encoded object size is limited to 8192 bytes.",additionalProperties:true},UserMetadata:{type:"object",required:["public_metadata","private_metadata","unsafe_metadata","metadata_version"],properties:{public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateUserMetadata:{type:"object",required:["expected_version"],minProperties:2,properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Session:{type:"object",required:["id","user_id","expires_at","created_at","metadata","metadata_version"],properties:{id:{type:"string"},user_id:{type:"string"},expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},ip_address:{type:["string","null"]},user_agent:{type:["string","null"]},metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},SessionMetadata:{type:"object",required:["metadata","metadata_version"],properties:{metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateSessionMetadata:{type:"object",required:["expected_version","metadata"],properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Organization:{type:"object",required:["id","name","slug","created_at"],properties:{id:{type:"string"},name:{type:"string"},slug:{type:"string"},logo:{type:["string","null"],format:"uri"},metadata:{type:["object","null"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateOrganization:{type:"object",required:["name","slug"],properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:"string",format:"uri",maxLength:2048},metadata:{type:"object"}},additionalProperties:false},UpdateOrganization:{type:"object",minProperties:1,properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:["string","null"],format:"uri",maxLength:2048},metadata:{type:["object","null"]}},additionalProperties:false},OrganizationMember:{type:"object",required:["organization_id","user_id","role","created_at"],properties:{organization_id:{type:"string"},user_id:{type:"string"},role:{type:"string"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},AddMember:{type:"object",required:["user_id","role"],properties:{user_id:{type:"string"},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},OrganizationRole:{type:"object",required:["id","organization_id","name","permissions"],properties:{id:{type:"string"},organization_id:{type:"string"},name:{type:"string"},permissions:{type:"array",items:{$ref:"#/components/schemas/OrganizationPermissionId"}}},additionalProperties:false},OrganizationPermissionId:{type:"string",enum:["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","team:create","team:update","team:delete","ac:create","ac:read","ac:update","ac:delete"]},RoleInput:{type:"object",required:["name","permissions"],properties:{name:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9_-]*$"},permissions:{type:"array",maxItems:100,items:{$ref:"#/components/schemas/OrganizationPermissionId"},uniqueItems:true}},additionalProperties:false},Invitation:{type:"object",required:["id","organization_id","email","role","status","expires_at"],properties:{id:{type:"string"},organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100},status:{type:"string"},expires_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateInvitation:{type:"object",required:["organization_id","email","role"],properties:{organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},Event:{type:"object",required:["id","type","status","created_at"],properties:{id:{type:"string"},type:{type:"string"},status:{type:"string"},user_id:{type:["string","null"]},metadata:{type:"object"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},StatsOverview:{type:"object",required:["users_total","monthly_active_users","recent_sign_ins"],properties:{users_total:{type:"integer",minimum:0},monthly_active_users:{type:"integer",minimum:0},recent_sign_ins:{type:"integer",minimum:0}},additionalProperties:false},WebhookInput:{type:"object",required:["url","events"],properties:{url:{type:"string",format:"uri",maxLength:2048},description:{type:"string",maxLength:500},events:{type:"array",minItems:1,maxItems:20,items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"},uniqueItems:true}},additionalProperties:false},WebhookSubscriptionEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset"]},WebhookEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","webhook.test"]},WebhookEndpoint:{type:"object",required:["id","url","events","status","created_at","updated_at"],properties:{id:{type:"string",format:"uuid"},url:{type:"string",format:"uri"},description:{type:["string","null"]},events:{type:"array",items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"}},status:{type:"string",enum:["active","paused","auto_paused"]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookSecret:{type:"object",required:["secret","overlap_expires_at"],properties:{secret:{type:"string"},overlap_expires_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookWithSecret:{type:"object",required:["endpoint","secret"],properties:{endpoint:{$ref:"#/components/schemas/WebhookEndpoint"},secret:{type:"string"}},additionalProperties:false},WebhookDelivery:{type:"object",required:["id","event_id","attempt_id","attempt_number","webhook_id","event_type","status","response_status","response_body","error_code","created_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},event_id:{type:"string",format:"uuid"},attempt_id:{type:"string",format:"uuid"},attempt_number:{type:"integer",minimum:1},webhook_id:{type:"string",format:"uuid"},event_type:{$ref:"#/components/schemas/WebhookEventType"},status:{type:"string",enum:["queued","delivering","succeeded","failed"]},response_status:{type:["integer","null"]},response_body:{type:["string","null"]},error_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},ExportJob:{type:"object",required:["id","status","created_at"],properties:{id:{type:"string",format:"uuid"},status:{type:"string",enum:["pending","processing","completed","failed"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},Page:{type:"object",required:["data","next_cursor"],properties:{data:{type:"array"},next_cursor:{type:["string","null"]}},additionalProperties:false},UserPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/User"}}}}]},SessionPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}]},OrganizationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}]},MemberPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationMember"}}}}]},RolePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationRole"}}}}]},InvitationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Invitation"}}}}]},EventPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Event"}}}}]},WebhookPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookEndpoint"}}}}]},DeliveryPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookDelivery"}}}}]}};var We=new Set(["__proto__","constructor","prototype"]),Je=64,Ve=5e4;function ae(e,t,n){let o=I[e].responseSchemas;Object.hasOwn(o,String(t))||K();let s=o[String(t)];if(s===null){n!==null&&K();return}let i={nodes:0};return O(n,x(s),0,i)||K(),n}function O(e,t,n,r){if(r.nodes+=1,n>Je||r.nodes>Ve)return false;if(typeof t.$ref=="string"){let s=Xe(t.$ref);if(s===null||!O(e,s,n+1,r))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(s=>O(e,x(s),n+1,r))||Array.isArray(t.enum)&&!t.enum.some(s=>Object.is(s,e)))return false;let o=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!o.some(s=>qe(e,s))?false:e===null?t.type===void 0||o.includes("null"):typeof e=="string"?Be(e,t):typeof e=="number"?Fe(e,t):Array.isArray(e)?Ge(e,t,n,r):P(e)?Ye(e,t,n,r):typeof e=="boolean"}function qe(e,t){switch(t){case "null":return e===null;case "object":return P(e);case "array":return Array.isArray(e);case "string":return typeof e=="string";case "integer":return Number.isSafeInteger(e);case "number":return typeof e=="number"&&Number.isFinite(e);case "boolean":return typeof e=="boolean";default:return false}}function Be(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!He(e,t.pattern))return false;switch(t.format){case void 0:return true;case "uuid":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);case "date-time":return /^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e));case "email":return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);case "uri":try{return new URL(e).protocol.length>1}catch{return false}default:return false}}function He(e,t){switch(t){case "^[a-z0-9]+(?:-[a-z0-9]+)*$":return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e);case "^[a-z][a-z0-9_-]*$":return /^[a-z][a-z0-9_-]*$/.test(e);default:return false}}function Fe(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Ge(e,t,n,r){if(typeof t.minItems=="number"&&e.length<t.minItems||typeof t.maxItems=="number"&&e.length>t.maxItems||t.uniqueItems===true&&new Set(e.map(s=>JSON.stringify(s))).size!==e.length)return false;if(t.items===void 0)return true;let o=x(t.items);return e.every(s=>O(s,o,n+1,r))}function Ye(e,t,n,r){let o=Object.keys(e);if(o.some(i=>We.has(i))||typeof t.minProperties=="number"&&o.length<t.minProperties||typeof t.maxProperties=="number"&&o.length>t.maxProperties)return false;let s=P(t.properties)?t.properties:{};if(Array.isArray(t.required)&&t.required.some(i=>typeof i!="string"||!Object.hasOwn(e,i)))return false;for(let[i,c]of Object.entries(e)){let d=s[i];if(d!==void 0){if(!O(c,x(d),n+1,r))return false;continue}if(t.additionalProperties===false||P(t.additionalProperties)&&!O(c,t.additionalProperties,n+1,r))return false}return true}function Xe(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let n=e.slice(t.length);return Object.hasOwn(M,n)?x(M[n]):null}function x(e){return P(e)||K(),e}function P(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function K(){throw new TypeError("Admin API response does not match its generated contract.")}var Ze=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Qe=1024*1024,et=1e4,R=class extends Error{status;code;requestId;problem;retryAfter;constructor(t){super(t.problem.detail),this.name="AuthOwlAdminApiError",this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.problem=t.problem,this.retryAfter=t.retryAfter;}},T=class extends Error{kind;requestId;constructor(t,n){super(t==="aborted"?"The AuthOwl Admin API request was aborted.":t==="timeout"?"The AuthOwl Admin API request timed out.":t==="response_too_large"?"The AuthOwl Admin API response exceeded the allowed size.":t==="invalid_response"?"The AuthOwl Admin API returned an invalid response.":"The AuthOwl Admin API request could not be completed."),this.name="AuthOwlAdminNetworkError",this.kind=t,this.requestId=n;}};function tt(e){nt();let t=rt(e?.secretKey),n=ot(e?.apiUrl),r=e?.fetch??globalThis.fetch;if(typeof r!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let o=async(i,c)=>{let d=c??{},u=I[i],m=new URL(st(u.path,d).replace(/^\/+/,""),n);it(m,d);let g=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`}),p="body"in d?JSON.stringify(d.body):void 0;p!==void 0&&g.set("content-type","application/json");let w;try{w=await j({fetchImpl:r,url:m,init:{method:u.method,headers:g,body:p,signal:c?.signal},timeoutMs:et,maxResponseBytes:Qe,allowHttpLoopback:n.protocol==="http:",decode:(f,k)=>ae(i,k.status,f)});}catch(f){throw f instanceof R?f:f instanceof A?new T(f.kind,f.requestId):new T("network")}let{response:h,requestId:_,data:l}=w;if(!h.ok)throw at(h,l,_);if(!u.successStatuses.some(f=>f===h.status))throw new T("invalid_response",_);return l},s=Object.assign(Object.create(null),{request:o});for(let i of Object.keys(I))s[i]=c=>o(i,c);return Object.freeze(s)}function nt(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function rt(e){if(typeof e!="string"||!Ze.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function ot(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=L(e,{allowHttpLoopback:true});if(t.username||t.password||t.search||t.hash)throw new TypeError("apiUrl must not contain credentials, a query, or a fragment.");let n=t.pathname.replace(/\/+$/,"");if(n!==""&&n!=="/api/v1")throw new TypeError("apiUrl path must be empty or /api/v1.");return t.pathname="/api/v1/",t}function st(e,t){let n="path"in t&&$(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(r,o)=>{let s=n[o];if(typeof s!="string"&&typeof s!="number")throw new TypeError(`Missing Admin API path parameter: ${o}.`);return encodeURIComponent(String(s))})}function it(e,t){if(!(!("query"in t)||!$(t.query)))for(let[n,r]of Object.entries(t.query)){if(r==null)continue;let o=Array.isArray(r)?r:[r];for(let s of o)e.searchParams.append(n,String(s));}}function at(e,t,n){let r=n??ce(e.headers.get("x-request-id"),256),o=ce(e.headers.get("retry-after"),128),s=ct(e.status,r),i=pt(t)?t:s;return new R({status:e.status,code:i.code,requestId:r,problem:i,retryAfter:o})}function ct(e,t){return {type:"about:blank",title:"AuthOwl Admin API error",status:e,detail:"The AuthOwl Admin API rejected the request.",instance:`urn:authowl:request:${t??"unknown"}`,code:"UNKNOWN_ERROR"}}function pt(e){return $(e)?typeof e.type=="string"&&typeof e.title=="string"&&typeof e.status=="number"&&typeof e.detail=="string"&&typeof e.instance=="string"&&typeof e.code=="string":false}function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ce(e,t){let n=e?.trim();if(!(!n||n.length>t||!/^[\x21-\x7e]+$/.test(n)))return n}var dt=/^v1=([a-f0-9]{64})$/i,ut=/^whsec_[A-Za-z0-9_-]{1,256}$/,mt=/^(0|[1-9]\d{0,10})$/;async function lt(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=ft(e.secrets),n=e.toleranceSeconds??300;if(!Number.isSafeInteger(n)||n<0||n>3600)throw new TypeError("Webhook toleranceSeconds must be an integer from 0 to 3600.");let r=e.now??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(r)||r<0)throw new TypeError("Webhook now must be a non-negative Unix timestamp.");let o=ht(e.rawBody);if(o.byteLength>1048576||typeof e.timestamp!="string"||!mt.test(e.timestamp))return false;let s=Number(e.timestamp);if(!Number.isSafeInteger(s)||Math.abs(r-s)>n)return false;let i=yt(e.signatureHeader);if(i.length===0)return false;let c=new TextEncoder().encode(`${e.timestamp}.`),d=new Uint8Array(c.byteLength+o.byteLength);d.set(c),d.set(o,c.byteLength);let u=false;for(let m of t){let g=await crypto.subtle.importKey("raw",new TextEncoder().encode(m),{name:"HMAC",hash:"SHA-256"},false,["sign"]),p=new Uint8Array(await crypto.subtle.sign("HMAC",g,d));for(let w of i)u=bt(p,w)||u;}return u}function ft(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!ut.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function yt(e){if(typeof e!="string"||e.length>1024)return [];let t=e.split(",");if(t.length>4)return [];let n=[];for(let r of t){let o=dt.exec(r.trim());o&&n.push(gt(o[1]));}return n}function ht(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("Webhook rawBody must be a string, ArrayBuffer, or ArrayBuffer view.")}function gt(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}function bt(e,t){if(e.byteLength!==t.byteLength)return false;let n=0;for(let r=0;r<e.byteLength;r+=1)n|=e[r]^t[r];return n===0}var pe=["publishableKey","apiUrl","issuer","jwksUri","audience"],wt=new Set([...pe,"clockToleranceSeconds"]);function D(e){if(e!==void 0&&(!e||typeof e!="object"))throw new Error("AuthOwl token verification config must be an object.");if(e&&Object.keys(e).some(c=>!wt.has(c)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(pe.filter(c=>Object.prototype.hasOwnProperty.call(e??{},c))),n=t.has("publishableKey")||t.has("apiUrl"),r=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(n&&r)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(r){if(typeof e?.issuer!="string"||typeof e.jwksUri!="string"||typeof e.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return U({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let o,s;if(n){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");o=e.publishableKey,s=e.apiUrl;}else o=process.env.AUTHOWL_PUBLISHABLE_KEY,s=process.env.AUTHOWL_API_URL;if(!o||!s)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let i=v({publishableKey:o,apiUrl:s});return U({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},i.decoded.env==="test")}async function Bt(e,t){return E(e,D(t))}async function Ht(e,t,n){let r=D(n);try{let o=await E(e,r);return ie(o.membership,t)}catch{return false}}async function Ft(e,t,n){let r=D(n);try{let o=await E(e,r);return se(o.membership,t.permission)}catch{return false}}
|
|
2
|
+
exports.ADMIN_API_SPEC_SHA256=De;exports.AuthOwlAdminApiError=R;exports.AuthOwlAdminNetworkError=T;exports.TokenVerificationError=a;exports.createAdminClient=tt;exports.has=Ht;exports.hasPermission=Ft;exports.resolveConfig=v;exports.sessionCookieName=$e;exports.verifyProjectToken=Ce;exports.verifyToken=Bt;exports.verifyWebhook=lt;
|