@authowl/core 0.12.0 → 0.14.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/README.md +3 -2
- package/dist/chunk-MX7KKUAW.js +1 -0
- package/dist/chunk-T5SH3ZZP.js +1 -0
- package/dist/{client-1cjryEHU.d.cts → client-DOOkDLWg.d.cts} +31 -3
- package/dist/{client-CzV2XWt6.d.ts → client-jpaYv3wu.d.ts} +31 -3
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +11 -2
- package/dist/index.d.ts +11 -2
- package/dist/index.js +3 -3
- package/dist/messages.cjs +1 -1
- package/dist/messages.d.cts +1 -0
- package/dist/messages.d.ts +1 -0
- package/dist/messages.js +1 -1
- package/dist/native.cjs +2 -1
- package/dist/native.d.cts +2 -2
- package/dist/native.d.ts +2 -2
- package/dist/native.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +894 -52
- package/dist/server.d.ts +894 -52
- package/dist/server.js +1 -1
- package/dist/session-handoff-6B5KZXQV.js +2 -0
- package/package.json +5 -1
- package/dist/chunk-SM5LS47O.js +0 -1
package/dist/native.cjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
'use strict';var gn=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,mn=/^sk_/i;function oe(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(mn.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=gn.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]}}var ve=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function re(e,t){throw new Error(`${e}: ${t}`)}function Ce(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 i=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&ve.test(i)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function ze(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&re("apiUrl","origin required");let n;try{n=new URL(e);}catch{re("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!ve.test(e))&&re("apiUrl","HTTPS required except exact loopback"),n.origin}function ae(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=oe(e.publishableKey),n=ze(e.apiUrl,{allowHttpLoopback:t.env==="test"}),i=`${n}/api/projects/${t.projectId}/auth`;return {...e,apiUrl:n,decoded:t,projectBaseURL:i}}var hn=1e4,yn=1024*1024,S=class extends Error{kind;requestId;constructor(t,n){super(In(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},Ue=new WeakSet;function I(e,t){let n=new S(e,t);return Ue.add(n),n}async function J({fetchImpl:e,url:t,init:n={},timeoutMs:i=hn,maxResponseBytes:o=yn,allowHttpLoopback:a=false,decode:r}){Ee(i,"timeoutMs"),Ee(o,"maxResponseBytes");let s=Ce(t,{allowHttpLoopback:a}),u=n.signal,m=new AbortController,d=null,l,f=new Promise(A=>{l=A;}),g=A=>{d===null&&(d=A,l({type:"abort",kind:A}),m.abort());},y=()=>g("aborted");u?.addEventListener("abort",y,{once:true});let _=setTimeout(()=>g("timeout"),i);u?.aborted&&y();try{if(d!==null)throw I(d);let A;try{A=await Promise.race([e(s.toString(),{...n,redirect:"error",signal:m.signal}).then(fn=>({type:"response",response:fn})),f]);}catch{throw I(d??"network")}if(A.type==="abort")throw I(A.kind);if(!An(A.response))throw I("invalid_response");let C=A.response,V=Sn(C.headers),pn=await bn(C,o,f,()=>d,V),Pe=kn(C,pn,V),xe;try{xe=C.ok&&r?r(Pe,Object.freeze({status:C.status})):Pe;}catch{throw I("invalid_response",V)}return {response:C,data:xe,...V===void 0?{}:{requestId:V}}}catch(A){throw A instanceof S&&Ue.has(A)?A:I(d??"network")}finally{clearTimeout(_),u?.removeEventListener("abort",y);}}function An(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 bn(e,t,n,i,o){let a=e.headers.get("content-length");if(a!==null){if(!/^\d+$/.test(a))throw De(e.body),I("invalid_response",o);if(Number(a)>t)throw De(e.body),I("response_too_large",o)}if(!e.body)return "";let r;try{r=e.body.getReader();}catch{throw I("network",o)}let s=[],u=0,m=null;try{for(;;){let f;try{f=await Promise.race([r.read(),n]);}catch{m=I(i()??"network",o);break}if(On(f)){m=I(f.kind,o);break}let{done:g,value:y}=f;if(g)break;if(y.byteLength!==0){if(u+=y.byteLength,u>t){m=I("response_too_large",o);break}s.push(y);}}}finally{m&&wn(r);try{r.releaseLock();}catch{}}if(m)throw m;let d=new Uint8Array(u),l=0;for(let f of s)d.set(f,l),l+=f.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(d)}catch{throw I("invalid_response",o)}}function On(e){return "type"in e&&e.type==="abort"}function De(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function wn(e){try{e.cancel().catch(()=>{});}catch{}}function kn(e,t,n){if(e.status===204||e.status===205)return null;let i=Rn(e.headers.get("content-type"));if(!e.ok&&(!i||t.length===0))return null;if(!i||t.length===0)throw I("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw I("invalid_response",n)}}function Rn(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function Sn(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Ee(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function In(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 Tn="x-authowl-turnstile-token",Pn=1e4,xn=32,vn=2e4;function M(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 Me(e,t=e.projectBaseURL){return {async request(n,i={}){let o=Dn(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(Tn,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)}},u=Object.freeze({method:a,path:n});await i.fetchOptions?.onRequest?.(u);let m=zn(a,i.fetchOptions),d;try{d=await Cn(e,o,{...s,signal:i.fetchOptions?.signal},m);}catch(A){let C=_e(A);return await i.fetchOptions?.onError?.(se(u,C,Nn(A))),{data:null,error:C}}let{response:l,requestId:f}=d,g=Ln(n,d.data),y=g;if(l.ok)try{y=ce(g),i.decode&&(y=i.decode(y));}catch{let A=_e(new S("invalid_response",f));return await i.fetchOptions?.onError?.(se(u,A,"invalid_response")),{data:null,error:A}}let _=Object.freeze({...u,status:l.status,...f===void 0?{}:{requestId:f}});if(await i.fetchOptions?.onResponse?.(_),!l.ok){let A=En(l,g,f);return await i.fetchOptions?.onError?.(se(u,A,"api")),{data:null,error:A}}return await i.fetchOptions?.onSuccess?.(_),{data:y,error:null}}}}async function Cn(e,t,n,i){let o=Date.now()+Pn;for(let a=0;a<i;a+=1){let r=o-Date.now();if(r<=0)throw new S("timeout");try{let s=await J({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 S)||s.kind!=="network")throw s}await _n(50*2**a,n.signal,o);}throw new S("network")}function zn(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 Dn(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 En(e,t,n){let i=K(t)?t:{},o=Un(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 Un(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??Ne(t.get("retry-after"))??Ne(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function Ne(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 _e(e){let t=e instanceof S?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 S&&e.requestId?{requestId:e.requestId}:{}}}function se(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function Nn(e){return e instanceof S?e.kind:"network"}function _n(e,t,n){return new Promise((i,o)=>{if(t?.aborted){o(new S("aborted"));return}let a=n-Date.now();if(a<=0){o(new S("timeout"));return}let r=Math.min(e,a),s=()=>{clearTimeout(u),o(new S("aborted"));},u=setTimeout(()=>{t?.removeEventListener("abort",s),Date.now()>=n?o(new S("timeout")):i();},r);t?.addEventListener("abort",s,{once:true}),t?.aborted&&s();})}function ce(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>xn||i.nodes>vn)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=>ce(o,"",n+1,i)):K(e)?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,Mn(o)?a:ce(a,o,n+1,i)])):e}function Mn(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function Ln(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>K(o)?ue(o):o);if(!K(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-")?ue(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")&&K(i.session)&&(i={...i,session:ue(i.session)}),i}function ue(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function K(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}var Fn=new Set(["__proto__","constructor","prototype"]);function p(e){(!e||typeof e!="object"||Array.isArray(e))&&c();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&c(),e}function w(e){return typeof e!="string"&&c(),e}function k(e){return typeof e!="boolean"&&c(),e}function O(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&c(),e}function W(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&c(),[...e]}function b(e,t){let n=e[t];return n==null||typeof n=="string"?n:c()}function Le(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:c()}function x(e){let t=p(e),n=t.email;return n!==null&&typeof n!="string"&&c(),{id:w(t.id),email:n,emailVerified:k(t.emailVerified),createdAt:O(t.createdAt),updatedAt:O(t.updatedAt),...P("phoneNumber",b(t,"phoneNumber")),...P("username",b(t,"username")),...P("displayUsername",b(t,"displayUsername")),...P("firstName",b(t,"firstName")),...P("lastName",b(t,"lastName")),...P("name",b(t,"name")),...P("image",b(t,"image")),...P("twoFactorEnabled",Le(t,"twoFactorEnabled"))}}function $(e){let t=p(e),n=t.membership;return {id:w(t.id),userId:w(t.userId),expiresAt:O(t.expiresAt),...P("activeOrganizationId",b(t,"activeOrganizationId")),...P("activeTeamId",b(t,"activeTeamId")),...P("membership",n==null?n:qn(n)),...P("pendingMfaEnrollment",Le(t,"pendingMfaEnrollment"))}}function c(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function z(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&c(),le(e,t,n)}function le(e,t=20,n=1e4){return de(e,0,{nodes:0},t,n)}function qn(e){let t=p(e);return {role:w(t.role),permissions:W(t.permissions),...t.teams===void 0?{}:{teams:W(t.teams)}}}function de(e,t,n,i,o){if(n.nodes+=1,(t>i||n.nodes>o)&&c(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||c(),e;if(Array.isArray(e))return e.map(s=>de(s,t+1,n,i,o));(!e||typeof e!="object")&&c();let a=Object.getPrototypeOf(e);a!==Object.prototype&&a!==null&&c();let r={};for(let[s,u]of Object.entries(e))Fn.has(s)&&c(),r[s]=de(u,t+1,n,i,o);return r}function P(e,t){return t===void 0?{}:{[e]:t}}function qe(e,t){let n=new Set,i=null,o=null,a=null,r,s=g=>{d(g);};r={data:null,isPending:true,isRefetching:false,error:null,refetch:s};function u(g){r=g;for(let y of n)y();}async function m(g){return e.request("/get-session",{query:g?.query,decode:Fe})}async function d(g){a?.abort();let y=new AbortController;a=y,u({...r,isPending:r.data===null&&r.error===null,isRefetching:r.data!==null});let _=await e.request("/get-session",{query:g?.query,fetchOptions:{signal:y.signal},decode:Fe});a===y&&(a=null,u({data:_.data,error:_.error,isPending:false,isRefetching:false,refetch:s}));}function l(){if(typeof window>"u"||o)return;let g=()=>{d();},y=()=>{document.visibilityState==="visible"&&d();};window.addEventListener("focus",g),document.addEventListener("visibilitychange",y),typeof BroadcastChannel<"u"&&(i=new BroadcastChannel(`authowl:${t}`),i.addEventListener("message",g)),o=()=>{window.removeEventListener("focus",g),document.removeEventListener("visibilitychange",y),i?.close(),i=null,o=null;};}function f(g){return n.add(g),n.size===1&&(l(),d()),()=>{n.delete(g),n.size===0&&(a?.abort(),a=null,o?.());}}return {store:{subscribe:f,getSnapshot:()=>r},getSession:m,notifyMutation(){i?.postMessage({type:"session-changed"}),n.size>0&&d({query:{disableCookieCache:true}});}}}function Fe(e){if(e===null)return null;let t=p(e);return (t.session===void 0||t.user===void 0)&&c(),{session:$(t.session),user:x(t.user)}}function He(){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 Ve(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:je})}async function Ke(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:je})}function je(e){let t=p(e),n=z(t.public_metadata),i=z(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 Je(e,t){let{post:n,mutation:i}=M(e,t);return {getMetadata:o=>Ve(e,o),updateUnsafeMetadata:(o,a)=>Ke(e,o,a),updateProfile:(o,a)=>i(n("/update-user",o,a,j)),changeEmail:(o,a)=>i(n("/change-email",o,a,j)),changePassword:(o,a)=>i(n("/change-password",o,a,Hn)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:Vn}),revokeSession:({sessionId:o},a)=>i(n("/revoke-session",{sessionId:o},a,j)),revokeOtherSessions:o=>i(n("/revoke-other-sessions",{},o,j)),listSocialAccounts:async o=>{let a=await e.request("/list-accounts",{fetchOptions:o,decode:Kn});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,jn),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,j)),delete:(o={},a)=>i(n("/delete-user",o,a,Bn))}}function j(e){let t=p(e);return {status:k(t.status)}}function Hn(e){let t=p(e);return {user:x(t.user)}}function Vn(e){return Array.isArray(e)||c(),e.map(t=>{let n=p(t);return {id:w(n.id),userId:w(n.userId),createdAt:O(n.createdAt),updatedAt:O(n.updatedAt),expiresAt:O(n.expiresAt),...Be("ipAddress",b(n,"ipAddress")),...Be("userAgent",b(n,"userAgent"))}})}function Kn(e){return Array.isArray(e)||c(),e.map(t=>{let n=p(t);return {id:w(n.id),userId:w(n.userId),providerId:w(n.providerId),accountId:w(n.accountId),scopes:W(n.scopes),createdAt:O(n.createdAt),updatedAt:O(n.updatedAt)}})}function jn(e){let t=p(e);return {url:w(t.url),redirect:k(t.redirect)}}function Bn(e){let t=p(e);return {success:k(t.success),message:w(t.message)}}function Be(e,t){return t===void 0?{}:{[e]:t}}function pe(e,t){return !e||!t?false:e.permissions.includes(t)}function Jn(e,t){return !e||!t?false:e.teams?.includes(t)??false}function fe(e,t){if(!e)return false;let{role:n,permission:i,teamId:o}=t;return !(n===void 0&&i===void 0&&o===void 0||n!==void 0&&e.role!==n||i!==void 0&&!e.permissions.includes(i)||o!==void 0&&!Jn(e,o))}function Wn(e){return {has:t=>fe(e,t),hasPermission:t=>pe(e,t.permission)}}var $n=new Set(["pending","accepted","rejected","canceled"]),We=1e4;function L(e,t,n){let i=p(e),o={id:h(i.id),name:h(i.name),slug:h(i.slug),createdAt:O(i.createdAt),...G("logo",b(i,"logo")),...G("metadata",i.metadata===void 0?void 0:le(i.metadata))};return U(o.id,t),U(o.slug,n),o}function $e(e){return N(e,L)}function ge(e,t,n){return e===null?null:(t===null&&c(),L(e,t,n))}function Ge(e,t,n){if(e===null)return null;let i=p(e),o=L(i,t,n);return {...o,members:N(i.members,a=>ut(a,o.id)),invitations:N(i.invitations,a=>D(a,void 0,o.id))}}function Xe(e,t){let n=N(e,i=>st(i));return X(n.map(i=>i.organizationId),t),n}function Ye(e,t,n){return e===null?null:(t===null&&c(),st(e,t,n))}function Qe(e,t){let n=p(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&c(),{members:Gn(n.members,t),total:n.total}}function D(e,t,n){let i=p(e),o=h(i.status);$n.has(o)||c();let a={id:h(i.id),organizationId:h(i.organizationId),email:h(i.email),role:h(i.role),status:o,inviterId:h(i.inviterId),expiresAt:O(i.expiresAt),createdAt:O(i.createdAt)};return U(a.id,t),U(a.organizationId,n),a}function Ze(e,t){let n=N(e,i=>D(i));return X(n.map(i=>i.organizationId),t),n}function et(e){return N(e,t=>{let n=p(t);return {...D(n),organizationName:h(n.organizationName)}})}function tt(e,t){let n=p(e);return {...D(n,t),organizationName:h(n.organizationName),organizationSlug:h(n.organizationSlug),inviterEmail:h(n.inviterEmail)}}function nt(e,t){let n=p(e),i=D(n.invitation,t);return {invitation:i,member:F(n.member,void 0,i.organizationId)}}function it(e,t){let n=p(e);return n.member!==null&&c(),{invitation:n.invitation===null?null:D(n.invitation,t),member:null}}function ot(e,t){return e===null?null:D(e,t)}function rt(e,t,n){let i=p(e);return {member:F(i.member,n,t)}}function F(e,t,n){let i=p(e),o={id:h(i.id),organizationId:h(i.organizationId),userId:h(i.userId),role:h(i.role),createdAt:O(i.createdAt),...i.user===void 0?{}:{user:ct(i.user)}};return U(o.id,t),U(o.organizationId,n),o}function at(e,t){let n=N(e,i=>{let o=p(i);return {organizationId:h(o.organizationId),data:{role:h(o.role),...G("permission",o.permission===void 0?void 0:Xn(o.permission))}}});return X(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function st(e,t,n){let i=p(e),o=i.updatedAt,a={id:h(i.id),name:h(i.name),organizationId:h(i.organizationId),createdAt:O(i.createdAt),...o===void 0?{}:{updatedAt:O(o)}};return U(a.id,t),U(a.organizationId,n),a}function ut(e,t){let n=p(e);return {...F(n,void 0,t),user:ct(n.user)}}function Gn(e,t){let n=N(e,i=>ut(i));return X(n.map(i=>i.organizationId),t),n}function Xn(e){let t=p(e),n={};for(let[i,o]of Object.entries(t))(i==="__proto__"||i==="constructor"||i==="prototype"||i.length===0||i.length>We||!Array.isArray(o))&&c(),n[i]=o.map(a=>h(a));return n}function h(e){let t=w(e);return (t.length===0||t.length>We)&&c(),t}function U(e,t){t!==void 0&&e!==t&&c();}function X(e,t){let n=t??e[0];n!==void 0&&e.some(i=>i!==n)&&c();}function ct(e){let t=p(e);return {id:h(t.id),name:h(t.name),email:h(t.email),...G("image",b(t,"image"))}}function N(e,t){return Array.isArray(e)||c(),e.map(n=>t(n))}function G(e,t){return t===void 0?{}:{[e]:t}}function dt(e,t,n=()=>null){let{post:i,mutation:o}=M(e,t),a=(r,s,u,m)=>e.request(r,{query:s,fetchOptions:u,decode:m});return {create:(r,s)=>o(i("/organization/create",r,s,L)),list:r=>a("/organization/list",void 0,r,$e),get:(r={},s)=>a("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},s,u=>Ge(u,r.organizationId,r.organizationSlug)),setActive:(r,s)=>o(i("/organization/set-active",r,s,u=>ge(u,r.organizationId,r.organizationSlug))),listTeams:(r={},s)=>a("/organization/list-teams",{organizationId:r.organizationId},s,u=>Xe(u,r.organizationId)),setActiveTeam:(r,s)=>o(i("/organization/set-active-team",r,s,u=>Ye(u,r.teamId))),update:(r,s)=>o(i("/organization/update",r,s,u=>ge(u,r.organizationId))),delete:(r,s)=>o(i("/organization/delete",r,s,u=>L(u,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,u=>Qe(u,r.organizationId)),inviteMember:(r,s)=>o(i("/organization/invite-member",r,s,u=>D(u,void 0,r.organizationId))),listInvitations:(r={},s)=>a("/organization/list-invitations",{organizationId:r.organizationId},s,u=>Ze(u,r.organizationId)),listUserInvitations:r=>a("/organization/list-user-invitations",void 0,r,et),getInvitation:(r,s)=>a("/organization/get-invitation",{id:r.id},s,u=>tt(u,r.id)),acceptInvitation:(r,s)=>o(i("/organization/accept-invitation",r,s,u=>nt(u,r.invitationId))),rejectInvitation:(r,s)=>o(i("/organization/reject-invitation",r,s,u=>it(u,r.invitationId))),cancelInvitation:(r,s)=>o(i("/organization/cancel-invitation",r,s,u=>ot(u,r.invitationId))),removeMember:(r,s)=>o(i("/organization/remove-member",r,s,u=>rt(u,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,s)=>o(i("/organization/update-member-role",r,s,u=>F(u,r.memberId,r.organizationId))),leave:(r,s)=>o(i("/organization/leave",r,s,u=>F(u,void 0,r.organizationId))),listRoles:(r={},s)=>a("/organization/list-roles",{organizationId:r.organizationId},s,u=>at(u,r.organizationId)),has:r=>fe(n(),r),hasPermission:r=>pe(n(),r.permission)}}var lt=4096,Yn=4096,Qn=100,Zn=256,ei=16,ti=64;function he(e){let t=p(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&c(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:xt(t.twoFactorMethods,ei,ti)}}):(t.twoFactorRedirect!==void 0&&c(),{redirect:k(t.redirect),...ri(t,"url"),user:x(t.user)})}function pt(e){let t=p(e);return {user:x(t.user)}}function ft(e){let t=p(e);return {sessionCreated:k(t.sessionCreated),user:x(t.user)}}function gt(e,t){let n=p(e),i=k(n.redirect);n.user===null&&c();let o=n.user!==void 0&&n.user!==null,a=n.url!==void 0&&n.url!==null;return i?((o||!a)&&c(),{redirect:true,url:me(n.url,t)}):(o===a&&c(),o?{redirect:false,user:x(n.user)}:{redirect:false,url:me(n.url,t)})}function mt(e,t){let n=p(e);return (n.redirect!==true||n.user!==void 0)&&c(),{redirect:true,url:me(n.url,t)}}function ht(e){return {status:k(p(e).status)}}function yt(e){return {success:k(p(e).success)}}function At(e){return p(e).status!=="pending"&&c(),{status:"pending"}}function bt(e){let t=p(e);return (t.status!==true||t.sessionCreated!==true)&&c(),{status:true,sessionCreated:true,user:ni(t.user)}}function ye(e){return {status:k(p(e).status)}}function Ot(e){return {status:k(p(e).status)}}function wt(e){let t=p(e);return {status:k(t.status),user:x(t.user)}}function kt(e){return {success:k(p(e).success)}}function Rt(e){let t=p(e);return {totpURI:oi(t.totpURI),backupCodes:Pt(t.backupCodes)}}function St(e){return {status:k(p(e).status)}}function Y(e){return p(e).status!==true&&c(),{status:true}}function It(e){return {status:k(p(e).status)}}function Tt(e){let t=p(e);return t.status!==void 0&&t.status!==true&&c(),{backupCodes:Pt(t.backupCodes)}}function ni(e){let t=p(e);return {id:q(t.id,512),...ai(t,"name",1024),phoneNumber:q(t.phoneNumber,64),phoneNumberVerified:k(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:O(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:O(t.updatedAt)}}}function me(e,t){let n=q(e,lt);/[\u0000-\u0020\u007f]/u.test(n)&&c();let i;try{i=new URL(n);}catch{return c()}return (i.username||i.password)&&c(),i.protocol==="https:"||t&&i.protocol==="http:"&&ii(i.hostname)?i.href:c()}function ii(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function oi(e){let t=q(e,Yn),n;try{n=new URL(t);}catch{return c()}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))&&c(),t}function Pt(e){return xt(e,Qn,Zn)}function xt(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&c();let i=e.map(o=>q(o,n));return i.some(o=>o.trim().length===0)&&c(),new Set(i).size!==i.length&&c(),i}function q(e,t){let n=w(e);return (n.length===0||n.length>t)&&c(),n}function ri(e,t){let n=e[t];return n==null?{}:{[t]:q(n,lt)}}function ai(e,t,n){let i=b(e,t);return i===void 0?{}:(i!==null&&i.length>n&&c(),{[t]:i})}var vt=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Q=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 Z(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||zt(n,i)||Ct(i)||vt.has(i))return {valid:false}}let t=si(e);return Ae(t)?{valid:true,value:t}:{valid:false}}function Ae(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||zt(o,a)||Ct(a)||vt.has(a))return false;n??=a,i=a;}return t>0&&n!==void 0&&i!==void 0&&!Q.has(n)&&!Q.has(i)}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 si(e){let t=0,n=e.length;for(;t<n;){let i=e.codePointAt(t);if(i===void 0||!Q.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||!Q.has(r))break;n=a;}return e.slice(t,n)}function Ct(e){return e>=0&&e<=31||e>=127&&e<=159}function zt(e,t){return e.length===1&&t>=55296&&t<=57343}var Ut=12,Nt=5e3,ui=8,ci=1e3,di=16,Dt=512,_t=100,Mt=8192,li=32768,be=1024,Et=256,we=64,pi=6e5,fi=/^[A-Za-z0-9_-]+$/u,gi=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,mi=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,hi=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,yi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,Lt=new Set(["discouraged","preferred","required"]),Ai=new Set(["singleDevice","multiDevice"]),Ft=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),qt=new Set(["hybrid","security-key","client-device"]),bi=new Set(["none","indirect","direct","enterprise"]),Oi=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),wi=new Set(["platform","cross-platform"]),ki=new Set(["discouraged","preferred","required"]),Ri=new Set([-8,-7,-257]);function Ht(e){let t=z(e,Ut,Nt);return {challenge:Yt(t.challenge),...R("timeout",Gt(t.timeout)),...R("rpId",Qt(t.rpId)),...R("allowCredentials",$t(t.allowCredentials)),...R("userVerification",B(t.userVerification,Lt)),...R("hints",te(t.hints,qt)),...R("extensions",Xt(t.extensions))}}function Vt(e){let t=z(e,Ut,Nt);return {challenge:Yt(t.challenge),rp:Si(t.rp),user:Ii(t.user),pubKeyCredParams:Ti(t.pubKeyCredParams),...R("timeout",Gt(t.timeout)),...R("excludeCredentials",$t(t.excludeCredentials)),...R("authenticatorSelection",Pi(t.authenticatorSelection)),...R("attestation",B(t.attestation,bi)),...R("attestationFormats",te(t.attestationFormats,Oi)),...R("hints",te(t.hints,qt)),...R("extensions",Xt(t.extensions))}}function Kt(e){let t=p(e),n=$(t.session),i=x(t.user);return n.userId!==i.id&&c(),{session:n,user:i}}function ke(e){let t=p(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&c();let i=Re(t.deviceType,Ai),o=k(t.backedUp);return o&&i!=="multiDevice"&&c(),{id:H(t.id,Et),...Ci(t),publicKey:xi(t.publicKey,li),userId:H(t.userId,Et),credentialID:ie(t.credentialID,Mt),counter:n,deviceType:i,backedUp:o,...zi(t),createdAt:O(t.createdAt),...Di(t)}}function jt(e,t,n){let i=ke(e);return (i.credentialID!==t||(n===void 0?i.name!==void 0&&i.name!==null:i.name!==n))&&c(),i}function Bt(e){(!Array.isArray(e)||e.length>_t)&&c();let t=e.map(ke);return ne(t.map(n=>n.id)),ne(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&c(),t}function Jt(e,t,n){let i=p(e),o=ke(i.passkey);return (o.id!==t||o.name!==n)&&c(),{passkey:o}}function Wt(e){return p(e).status!==true&&c(),{status:true}}function Si(e){let t=p(e);return {name:Oe(t.name,be),...R("id",Qt(t.id))}}function Ii(e){let t=p(e);return {id:ie(t.id,128,1,64),name:Oe(t.name,be),displayName:Oe(t.displayName,be)}}function Ti(e){(!Array.isArray(e)||e.length===0||e.length>we)&&c();let t=e.map(n=>{let i=p(n);return (i.type!=="public-key"||!Number.isSafeInteger(i.alg)||!Ri.has(i.alg))&&c(),{type:"public-key",alg:i.alg}});return Ei(t.map(n=>n.alg)),t}function $t(e){if(e===void 0)return;(!Array.isArray(e)||e.length>_t)&&c();let t=e.map(n=>{let i=p(n);return i.type!=="public-key"&&c(),{type:"public-key",id:ie(i.id,Mt),...R("transports",te(i.transports,Ft))}});return ne(t.map(n=>n.id)),t}function Pi(e){if(e===void 0)return;let t=p(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&c();let n=B(t.residentKey,ki);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&c(),{...R("authenticatorAttachment",B(t.authenticatorAttachment,wi)),...R("residentKey",n),...R("requireResidentKey",t.requireResidentKey),...R("userVerification",B(t.userVerification,Lt))}}function Gt(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>pi)&&c(),e}function Xt(e){return e===void 0?void 0:z(e,ui,ci)}function te(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>we)&&c();let n=e.map(i=>Re(i,t));return ne(n),n}function B(e,t){if(e!==void 0)return Re(e,t)}function Yt(e){return ie(e,Math.ceil(Dt*4/3),di,Dt)}function ie(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=H(e,t),a=o.length%4,r=vi(o.at(-1)??""),s=Math.floor(o.length*3/4);return (!fi.test(o)||a===1||a===2&&(r&15)!==0||a===3&&(r&3)!==0||s<n||s>i)&&c(),o}function H(e,t){let n=w(e);return (n.length===0||n.length>t)&&c(),n}function Oe(e,t){let n=H(e,t);return mi.test(n)&&c(),n}function Qt(e){if(e===void 0)return;let t=H(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!hi.test(n)))&&c(),t}function xi(e,t){let n=H(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",r=Zt(a);return (n.length%4!==0||!gi.test(n)||i&&(r&15)!==0||o&&(r&3)!==0)&&c(),n}function vi(e){return Zt(e,true)}function Zt(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function Ci(e){let t=b(e,"name");return t===void 0?{}:(t!==null&&!Ae(t)&&c(),{name:t})}function zi(e){let t=b(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>we||n.some(i=>!Ft.has(i))||new Set(n).size!==n.length)&&c(),{transports:t}}function Di(e){let t=b(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(yi.test(t)||c(),{aaguid:t})}function Re(e,t){let n=w(e);return t.has(n)||c(),n}function R(e,t){return t===void 0?{}:{[e]:t}}function ne(e){new Set(e).size!==e.length&&c();}function Ei(e){new Set(e).size!==e.length&&c();}function Ui(e,t=()=>{},n=Mi){let i=Me(e),o=qe(i,e.decoded.projectId),a=n(i,o.notifyMutation),r=()=>{o.notifyMutation(),t();},{post:s,mutation:u}=M(i,r),m=e.decoded.env==="test";return {sessionStore:o.store,getSession:o.getSession,account:Je(i,r),organization:dt(i,r,()=>o.store.getSnapshot().data?.session.membership??null),signIn:{email:(d,l)=>u(s("/sign-in/email",d,l,he),f=>!("twoFactorRedirect"in f)),username:(d,l)=>u(s("/sign-in/username",d,l,he),f=>!("twoFactorRedirect"in f)),social:async(d,l)=>{let f=await u(s("/sign-in/social",d,l,g=>gt(g,m)),g=>"user"in g);return f.error!==null||f.data===null||"url"in f.data&&f.data.redirect&&!d.disableRedirect&&typeof window<"u"&&window.location.assign(f.data.url),f},sso:async(d,l)=>{let f=await s("/sign-in/sso",d,l,g=>mt(g,m));return f.error!==null||f.data===null||typeof window<"u"&&window.location.assign(f.data.url),f},magicLink:(d,l)=>s("/sign-in/magic-link",d,l,ht),emailOtp:(d,l)=>u(s("/sign-in/email-otp",d,l,pt)),passkey:(d,l)=>a.signIn(d,l)},signUp:{email:(d,l)=>u(s("/sign-up/email",d,l,ft),f=>f.sessionCreated)},emailOtp:{sendVerificationOtp:(d,l)=>s("/email-otp/send-verification-otp",d,l,yt),verifyEmail:(d,l)=>u(s("/email-otp/verify-email",d,l,wt))},phoneOtp:{start:(d,l)=>s("/phone-otp/start",{...d,idempotencyKey:d.idempotencyKey??He()},l,At),verify:(d,l)=>u(s("/phone-otp/verify",d,l,bt))},requestPasswordReset:(d,l)=>s("/request-password-reset",d,l,ye),resetPassword:(d,l)=>s("/reset-password",d,l,ye),sendVerificationEmail:(d,l)=>s("/send-verification-email",d,l,Ot),passkey:{addPasskey:(d,l)=>a.add(d,l),listUserPasskeys:()=>i.request("/passkey/list-user-passkeys",{decode:Bt}),updatePasskey:async(d,l)=>{let f=Z(d.name);if(!f.valid||f.value===void 0)return ee();let g=f.value;return s("/passkey/update-passkey",{...d,name:g},l,y=>Jt(y,d.id,g))},deletePasskey:(d,l)=>s("/passkey/delete-passkey",d,l,Wt)},twoFactor:{enable:(d,l)=>s("/two-factor/enable",d,l,Rt),disable:(d,l)=>u(s("/two-factor/disable",d,l,St),f=>f.status),verifyTotp:(d,l)=>u(s("/two-factor/verify-totp",d,l,Y)),verifyBackupCode:(d,l)=>u(s("/two-factor/verify-backup-code",d,l,Y)),sendOtp:(d={},l)=>s("/two-factor/send-otp",d,l,It),verifyOtp:(d,l)=>u(s("/two-factor/verify-otp",d,l,Y)),generateBackupCodes:(d,l)=>s("/two-factor/generate-backup-codes",d,l,Tt)},signOut:d=>u(i.request("/sign-out",{method:"POST",body:{},fetchOptions:d,decode:kt}),l=>l.success)}}function Se(e,t=()=>{},n){let i=Ui(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:en(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp,passkey:i.signIn.passkey},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey,addPasskey:i.passkey.addPasskey}}:{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:en(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function en(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return Ni();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?_i():i}}function Ni(){return Promise.resolve({data:null,error:{status:400,statusText:"BAD_REQUEST",code:"NATIVE_SOCIAL_ID_TOKEN_REQUIRED",message:"Native social sign-in requires a provider ID token."}})}function _i(){return Promise.resolve({data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_NATIVE_SOCIAL_RESPONSE",message:"The server returned a redirect for native ID-token sign-in."}})}function Mi(){return {signIn:()=>tn(),add:()=>tn()}}function tn(){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 Li(e,t,n){let i=new Map;return {async signIn(o={},a){let r=await e.request("/passkey/generate-authenticate-options");if(!r.data)return rn(r.error);let s;try{s=Ht(r.data);}catch{return nn()}let u;try{u=await n.authenticate({optionsJSON:s,useBrowserAutofill:o.autoFill});}catch(g){return an(n,g,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!Fi(u))return on();let{clientExtensionResults:m,...d}=u,l=i.get(u.id);if(l)return l;let f=(async()=>{let g=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:d},fetchOptions:a,decode:Kt});return g.data&&t(),g})();i.set(u.id,f);try{return await f}finally{i.get(u.id)===f&&i.delete(u.id);}},async add(o={},a){let r=Z(o.name);if(!r.valid)return ee();let s=await e.request("/passkey/generate-register-options",{query:{name:r.value,authenticatorAttachment:o.authenticatorAttachment}});if(!s.data)return rn(s.error);let u;try{u=Vt(s.data);}catch{return nn()}let m;try{m=await n.register({optionsJSON:u});}catch(g){return an(n,g,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!qi(m))return on();let{clientExtensionResults:d,...l}=m,f=await e.request("/passkey/verify-registration",{method:"POST",body:{response:l,name:r.value},fetchOptions:a,decode:g=>jt(g,m.id,r.value)});return f.data&&t(),f}}}function nn(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function on(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function sn(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 Fi(e){if(!sn(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 qi(e){if(!sn(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function rn(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function an(e,t,n,i){let o=Vi(t,"page does not have focus"),a=e.errorCode?.(t),r=a!==void 0?a==="ERROR_CEREMONY_ABORTED":Hi(t)==="AbortError";return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:o?"PASSKEY_PAGE_NOT_FOCUSED":r?n:a??"PASSKEY_BROWSER_ERROR",message:o?"Keep this page focused while completing the passkey prompt.":r?i:n==="AUTH_CANCELLED"?"Passkey authentication could not be completed by this browser.":"Passkey registration could not be completed by this browser."}}}function Hi(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function Vi(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}var Ie=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 un(e,t,n={}){let i=new Headers(n.init?.headers);return i.set("x-publishable-key",e.publishableKey),J({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 cn(e,t){if(!e.response.ok)throw new Ie(t,e.response,e.requestId);return e.data}async function Ki(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return cn(await un(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>ji(i,e)}),"public-config")}function ji(e,t){let n=z(e),i=n.environmentId,o=n.environmentType,a=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Bi(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==a)throw v();let r=T(n.branding),s=T(n.legal);if(!Te(n.enabledMethods,64)||!Te(n.socialProviders,64)||!ln(r,["appName","logoUrl","primaryColor"])||r.showAppName!==void 0&&typeof r.showAppName!="boolean"||r.alignment!==void 0&&r.alignment!=="left"&&r.alignment!=="center"&&r.alignment!=="right"||r.theme!==void 0&&r.theme!=="light"&&r.theme!=="dark"&&r.theme!=="system"||!ln(s,["termsUrl","privacyUrl"])||!Number.isSafeInteger(s.version)||s.version<0||typeof s.required!="boolean")throw v();if(n.socialProviderClientIds!==void 0){let u=T(n.socialProviderClientIds);if(Object.keys(u).length>64||Object.values(u).some(m=>typeof m!="string"||m.length>2048))throw v()}if(!E(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!dn(n.turnstileSiteKey)||!dn(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw v();if(n.jwtIssuer!==null){let u=T(n.jwtIssuer);if(u.issuer!==a||u.jwksUrl!==`${a}/jwks`||u.aud!==t.decoded.projectId)throw v()}if(n.signUp!==void 0){let u=T(n.signUp).mode;if(typeof u!="string"||!["open","restricted","allowlist","waitlist"].includes(u))throw v()}if(n.authentication!==void 0&&Ji(n.authentication),n.emailVerification!==void 0){let u=T(n.emailVerification);if(!E(u,["required"])||u.method!=="link"&&u.method!=="code")throw v()}if(n.userModel!==void 0&&!E(T(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw v();if(n.mfa!==void 0){let u=T(n.mfa);if(!E(u,["totp","required","backupCodes"])||(u.required===true||u.backupCodes===true)&&u.totp!==true)throw v()}return n}function Bi(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 v(){return new TypeError("public-config returned an invalid response")}function T(e){if(!e||typeof e!="object"||Array.isArray(e))throw v();return e}function dn(e){return e===null||typeof e=="string"&&e.length<=4096}function Ji(e){let t=T(e),n=T(t.email),i=T(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!E(n,["signUp"])||!Te(n.signIn,3)||n.signIn.some(a=>a!=="password"&&a!=="magic_link"&&a!=="email_otp")||!E(T(t.phone),["signUp","signIn"])||!E(i,["signUp","add"])||o&&(!Number.isSafeInteger(i.minLength)||!Number.isSafeInteger(i.maxLength)||i.minLength<1||i.maxLength>4096||i.minLength>i.maxLength)||!E(T(t.passkey),["signIn","add"])||!E(T(t.username),["collectOnSignUp","signIn"]))throw v()}function E(e,t){return t.every(n=>typeof e[n]=="boolean")}function ln(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function Te(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length<=128)&&new Set(e).size===e.length}function Wi(e){let t=e?.enabledMethods??["password"],n=t.includes("password"),i=t.includes("passkey"),o=e?.authentication,a=e?.mfa;return {emailSignUp:o?.email.signUp??t.some(r=>r==="password"||r==="magic_link"||r==="email_otp"),passwordSignUp:o?.password.signUp??n,phoneSignUp:o?.phone.signUp??t.includes("phone_otp"),passwordSignIn:o?.email.signIn.includes("password")??n,passwordMinLength:o?.password.minLength??8,passwordMaxLength:o?.password.maxLength??128,magicLinkSignIn:o?.email.signIn.includes("magic_link")??t.includes("magic_link"),emailOtpSignIn:o?.email.signIn.includes("email_otp")??t.includes("email_otp"),phoneSignIn:o?.phone.signIn??t.includes("phone_otp"),usernameSignIn:o?.username.signIn??false,collectUsername:o?.username.collectOnSignUp??false,passkeySignIn:o?.passkey.signIn??i,passkeyAdd:o?.passkey.add??i,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:a?.totp??e?.twoFactor??false,mfaRequired:a?.required??e?.mfaRequired??false,backupCodes:a?.backupCodes??e?.twoFactor??false,legacyNameField:e?.authentication===void 0}}function $i(e,t){let n=`p_${e.replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}function Go(e,t){return Se(ae(e),t)}exports.createMembershipHas=Wn;exports.createNativeAuthClient=Se;exports.createNativeClient=Go;exports.createPasskeyClient=Li;exports.decodePublishableKey=oe;exports.getPublicConfig=Ki;exports.resolveConfig=ae;exports.resolveProjectCapabilities=Wi;exports.sessionCookieName=$i;
|
|
1
|
+
'use strict';var vn=Object.defineProperty;var Ue=(e,t)=>()=>(e&&(t=e(e=0)),t);var Cn=(e,t)=>{for(var n in t)vn(e,n,{get:t[n],enumerable:true});};function j(){return typeof window<"u"&&typeof document<"u"&&typeof crypto<"u"&&typeof crypto.subtle?.digest=="function"}var me=Ue(()=>{});var re={};Cn(re,{beginCrossSiteSignIn:()=>ro,challengeFor:()=>ln,completeCrossSiteSignIn:()=>so,takeHandoffCode:()=>fn});function dn(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ln(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return dn(new Uint8Array(t))}function no(){return dn(crypto.getRandomValues(new Uint8Array(Zi)))}function pn(e,t){let n=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${cn}=${e}; Path=/; Max-Age=${t}; SameSite=Lax${n}`;}function io(){for(let e of document.cookie.split(";")){let t=e.indexOf("=");if(!(t<0)&&e.slice(0,t).trim()===cn)return e.slice(t+1).trim()||null}return null}function oo(){pn("",0);}function un(e){return new URL(e,window.location.href).toString()}async function ro(e,t){let n=t.callbackURL?un(t.callbackURL):null;if(n&&new URL(n).origin!==window.location.origin)return null;let i=no(),o=new URL(`${e.projectBaseURL}/session/start`);if(o.searchParams.set("pk",e.publishableKey),o.searchParams.set("kind",t.kind),t.kind==="social")o.searchParams.set("provider",t.provider),t.scopes?.length&&o.searchParams.set("scopes",t.scopes.join(",")),t.loginHint&&o.searchParams.set("loginHint",t.loginHint),t.requestSignUp!==void 0&&o.searchParams.set("requestSignUp",t.requestSignUp?"1":"0");else for(let r of to){let u=t[r];u&&o.searchParams.set(r,u);}let s=`${window.location.origin}${window.location.pathname}${window.location.search}`;o.searchParams.set("cb",n??s);for(let[r,u]of [["err",t.errorCallbackURL],["new",t.newUserCallbackURL]])u&&o.searchParams.set(r,un(u));return o.searchParams.set("challenge",await ln(i)),pn(i,eo),o.toString()}function fn(){if(typeof window>"u")return null;let e=window.location.hash;if(!e.includes(xe))return null;let t=new URLSearchParams(e.replace(/^#/,"")),n=t.get(xe);if(!n)return null;t.delete(xe);let i=t.toString();return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${i?`#${i}`:""}`),n}async function so(e){if(!j())return false;let t=fn();if(!t)return false;let n=io();if(oo(),!n)return false;let{error:i}=await e.request("/session/exchange",{method:"POST",body:{code:t,verifier:n}});return i===null}var cn,xe,Zi,eo,to,se=Ue(()=>{me();cn="authowl_handoff_verifier",xe="authowl_code",Zi=32,eo=900,to=["email","providerId","domain","organizationSlug"];});var En=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,Dn=/^sk_/i;function ae(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(Dn.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=En.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]}}var Ne=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function ue(e,t){throw new Error(`${e}: ${t}`)}function _e(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 i=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&Ne.test(i)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function Le(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&ue("apiUrl","origin required");let n;try{n=new URL(e);}catch{ue("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!Ne.test(e))&&ue("apiUrl","HTTPS required except exact loopback"),n.origin}function ce(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=ae(e.publishableKey),n=Le(e.apiUrl,{allowHttpLoopback:t.env==="test"}),i=`${n}/api/projects/${t.projectId}/auth`;return {...e,apiUrl:n,decoded:t,projectBaseURL:i}}var zn=1e4,Un=1024*1024,I=class extends Error{kind;requestId;constructor(t,n){super(Vn(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},qe=new WeakSet;function P(e,t){let n=new I(e,t);return qe.add(n),n}async function $({fetchImpl:e,url:t,init:n={},timeoutMs:i=zn,maxResponseBytes:o=Un,allowHttpLoopback:s=false,decode:r}){Fe(i,"timeoutMs"),Fe(o,"maxResponseBytes");let u=_e(t,{allowHttpLoopback:s}),c=n.signal,f=new AbortController,m=null,k,a=new Promise(h=>{k=h;}),d=h=>{m===null&&(m=h,k({type:"abort",kind:h}),f.abort());},g=()=>d("aborted");c?.addEventListener("abort",g,{once:true});let R=setTimeout(()=>d("timeout"),i);c?.aborted&&g();try{if(m!==null)throw P(m);let h;try{h=await Promise.race([e(u.toString(),{...n,redirect:"error",signal:f.signal}).then(xn=>({type:"response",response:xn})),a]);}catch{throw P(m??"network")}if(h.type==="abort")throw P(h.kind);if(!Nn(h.response))throw P("invalid_response");let E=h.response,V=Hn(E.headers),Tn=await _n(E,o,a,()=>m,V),De=Fn(E,Tn,V),ze;try{ze=E.ok&&r?r(De,Object.freeze({status:E.status})):De;}catch{throw P("invalid_response",V)}return {response:E,data:ze,...V===void 0?{}:{requestId:V}}}catch(h){throw h instanceof I&&qe.has(h)?h:P(m??"network")}finally{clearTimeout(R),c?.removeEventListener("abort",g);}}function Nn(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 _n(e,t,n,i,o){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw Me(e.body),P("invalid_response",o);if(Number(s)>t)throw Me(e.body),P("response_too_large",o)}if(!e.body)return "";let r;try{r=e.body.getReader();}catch{throw P("network",o)}let u=[],c=0,f=null;try{for(;;){let a;try{a=await Promise.race([r.read(),n]);}catch{f=P(i()??"network",o);break}if(Ln(a)){f=P(a.kind,o);break}let{done:d,value:g}=a;if(d)break;if(g.byteLength!==0){if(c+=g.byteLength,c>t){f=P("response_too_large",o);break}u.push(g);}}}finally{f&&Mn(r);try{r.releaseLock();}catch{}}if(f)throw f;let m=new Uint8Array(c),k=0;for(let a of u)m.set(a,k),k+=a.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(m)}catch{throw P("invalid_response",o)}}function Ln(e){return "type"in e&&e.type==="abort"}function Me(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function Mn(e){try{e.cancel().catch(()=>{});}catch{}}function Fn(e,t,n){if(e.status===204||e.status===205)return null;let i=qn(e.headers.get("content-type"));if(!e.ok&&(!i||t.length===0))return null;if(!i||t.length===0)throw P("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw P("invalid_response",n)}}function qn(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function Hn(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Fe(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Vn(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 Kn="x-authowl-turnstile-token",jn=1e4,Bn=32,Jn=2e4;function L(e,t){return {post:(n,i,o,s)=>e.request(n,{method:"POST",body:i,fetchOptions:o,decode:s}),mutation:async(n,i)=>{let o=await n;return o.error===null&&(i===void 0||o.data!==null&&i(o.data))&&t(),o}}}function Ke(e,t=e.projectBaseURL){return {async request(n,i={}){let o=Gn(t,n,i.query),s=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(Kn,i.fetchOptions.authChallengeToken),i.body!==void 0&&r.set("content-type","application/json");let u={method:s,headers:r,credentials:i.credentials??"include",...i.body===void 0?{}:{body:JSON.stringify(i.body)}},c=Object.freeze({method:s,path:n});await i.fetchOptions?.onRequest?.(c);let f=Wn(s,i.fetchOptions),m;try{m=await $n(e,o,{...u,signal:i.fetchOptions?.signal},f);}catch(h){let E=Ve(h);return await i.fetchOptions?.onError?.(de(c,E,Qn(h))),{data:null,error:E}}let{response:k,requestId:a}=m,d=ti(n,m.data),g=d;if(k.ok)try{g=pe(d),i.decode&&(g=i.decode(g));}catch{let h=Ve(new I("invalid_response",a));return await i.fetchOptions?.onError?.(de(c,h,"invalid_response")),{data:null,error:h}}let R=Object.freeze({...c,status:k.status,...a===void 0?{}:{requestId:a}});if(await i.fetchOptions?.onResponse?.(R),!k.ok){let h=Xn(k,d,a);return await i.fetchOptions?.onError?.(de(c,h,"api")),{data:null,error:h}}return await i.fetchOptions?.onSuccess?.(R),{data:g,error:null}}}}async function $n(e,t,n,i){let o=Date.now()+jn;for(let s=0;s<i;s+=1){let r=o-Date.now();if(r<=0)throw new I("timeout");try{let u=await $({fetchImpl:e.fetch??fetch,url:t,init:n,timeoutMs:Math.max(1,Math.ceil(r)),allowHttpLoopback:e.decoded.env==="test"});if(u.response.status<500||s===i-1)return u}catch(u){if(s===i-1||!(u instanceof I)||u.kind!=="network")throw u}await Zn(50*2**s,n.signal,o);}throw new I("network")}function Wn(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 Gn(e,t,n){let i=new URL(`${e}${t.startsWith("/")?t:`/${t}`}`);for(let[o,s]of Object.entries(n??{}))s!==void 0&&i.searchParams.set(o,String(s));return i.toString()}function Xn(e,t,n){let i=K(t)?t:{},o=Yn(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 Yn(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??He(t.get("retry-after"))??He(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function He(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 Ve(e){let t=e instanceof I?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 I&&e.requestId?{requestId:e.requestId}:{}}}function de(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function Qn(e){return e instanceof I?e.kind:"network"}function Zn(e,t,n){return new Promise((i,o)=>{if(t?.aborted){o(new I("aborted"));return}let s=n-Date.now();if(s<=0){o(new I("timeout"));return}let r=Math.min(e,s),u=()=>{clearTimeout(c),o(new I("aborted"));},c=setTimeout(()=>{t?.removeEventListener("abort",u),Date.now()>=n?o(new I("timeout")):i();},r);t?.addEventListener("abort",u,{once:true}),t?.aborted&&u();})}function pe(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>Bn||i.nodes>Jn)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=>pe(o,"",n+1,i)):K(e)?Object.fromEntries(Object.entries(e).map(([o,s])=>[o,ei(o)?s:pe(s,o,n+1,i)])):e}function ei(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function ti(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>K(o)?le(o):o);if(!K(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-")?le(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")&&K(i.session)&&(i={...i,session:le(i.session)}),i}function le(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function K(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}var ni=new Set(["__proto__","constructor","prototype"]);function p(e){(!e||typeof e!="object"||Array.isArray(e))&&l();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&l(),e}function A(e){return typeof e!="string"&&l(),e}function b(e){return typeof e!="boolean"&&l(),e}function O(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&l(),e}function W(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&l(),[...e]}function w(e,t){let n=e[t];return n==null||typeof n=="string"?n:l()}function je(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:l()}function v(e){let t=p(e),n=t.email;return n!==null&&typeof n!="string"&&l(),{id:A(t.id),email:n,emailVerified:b(t.emailVerified),createdAt:O(t.createdAt),updatedAt:O(t.updatedAt),...x("phoneNumber",w(t,"phoneNumber")),...x("username",w(t,"username")),...x("displayUsername",w(t,"displayUsername")),...x("firstName",w(t,"firstName")),...x("lastName",w(t,"lastName")),...x("name",w(t,"name")),...x("image",w(t,"image")),...x("twoFactorEnabled",je(t,"twoFactorEnabled"))}}function G(e){let t=p(e),n=t.membership;return {id:A(t.id),userId:A(t.userId),expiresAt:O(t.expiresAt),...x("activeOrganizationId",w(t,"activeOrganizationId")),...x("activeTeamId",w(t,"activeTeamId")),...x("membership",n==null?n:ii(n)),...x("pendingMfaEnrollment",je(t,"pendingMfaEnrollment"))}}function l(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function D(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&l(),ge(e,t,n)}function ge(e,t=20,n=1e4){return fe(e,0,{nodes:0},t,n)}function ii(e){let t=p(e);return {role:A(t.role),permissions:W(t.permissions),...t.teams===void 0?{}:{teams:W(t.teams)}}}function fe(e,t,n,i,o){if(n.nodes+=1,(t>i||n.nodes>o)&&l(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||l(),e;if(Array.isArray(e))return e.map(u=>fe(u,t+1,n,i,o));(!e||typeof e!="object")&&l();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&l();let r={};for(let[u,c]of Object.entries(e))ni.has(u)&&l(),r[u]=fe(c,t+1,n,i,o);return r}function x(e,t){return t===void 0?{}:{[e]:t}}function Je(e,t){let n=new Set,i=null,o=null,s=null,r,u=d=>{m(d);};r={data:null,isPending:true,isRefetching:false,error:null,refetch:u};function c(d){r=d;for(let g of n)g();}async function f(d){return e.request("/get-session",{query:d?.query,decode:Be})}async function m(d){s?.abort();let g=new AbortController;s=g,c({...r,isPending:r.data===null&&r.error===null,isRefetching:r.data!==null});let R=await e.request("/get-session",{query:d?.query,fetchOptions:{signal:g.signal},decode:Be});s===g&&(s=null,c({data:R.data,error:R.error,isPending:false,isRefetching:false,refetch:u}));}function k(){if(typeof window>"u"||o)return;let d=()=>{m();},g=()=>{document.visibilityState==="visible"&&m();};window.addEventListener("focus",d),document.addEventListener("visibilitychange",g),typeof BroadcastChannel<"u"&&(i=new BroadcastChannel(`authowl:${t}`),i.addEventListener("message",d)),o=()=>{window.removeEventListener("focus",d),document.removeEventListener("visibilitychange",g),i?.close(),i=null,o=null;};}function a(d){return n.add(d),n.size===1&&(k(),m()),()=>{n.delete(d),n.size===0&&(s?.abort(),s=null,o?.());}}return {store:{subscribe:a,getSnapshot:()=>r},getSession:f,notifyMutation(){i?.postMessage({type:"session-changed"}),n.size>0&&m({query:{disableCookieCache:true}});}}}function Be(e){if(e===null)return null;let t=p(e);return (t.session===void 0||t.user===void 0)&&l(),{session:G(t.session),user:v(t.user)}}me();function $e(){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 We(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:Xe})}async function Ge(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:Xe})}function Xe(e){let t=p(e),n=D(t.public_metadata),i=D(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 Qe(e,t){let{post:n,mutation:i}=L(e,t);return {getMetadata:o=>We(e,o),updateUnsafeMetadata:(o,s)=>Ge(e,o,s),updateProfile:(o,s)=>i(n("/update-user",o,s,B)),changeEmail:(o,s)=>i(n("/change-email",o,s,B)),changePassword:(o,s)=>i(n("/change-password",o,s,oi)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:ri}),revokeSession:({sessionId:o},s)=>i(n("/revoke-session",{sessionId:o},s,B)),revokeOtherSessions:o=>i(n("/revoke-other-sessions",{},o,B)),listSocialAccounts:async o=>{let s=await e.request("/list-accounts",{fetchOptions:o,decode:si});if(!s.data)return {data:null,error:s.error};let r=s.data.length>1;return {...s,data:s.data.filter(u=>u.providerId!=="credential").map(u=>({...u,canUnlink:r}))}},linkSocial:(o,s)=>n("/link-social",o,s,ai),unlinkSocial:(o,s)=>i(n("/unlink-account",o,s,B)),delete:(o={},s)=>i(n("/delete-user",o,s,ui))}}function B(e){let t=p(e);return {status:b(t.status)}}function oi(e){let t=p(e);return {user:v(t.user)}}function ri(e){return Array.isArray(e)||l(),e.map(t=>{let n=p(t);return {id:A(n.id),userId:A(n.userId),createdAt:O(n.createdAt),updatedAt:O(n.updatedAt),expiresAt:O(n.expiresAt),...Ye("ipAddress",w(n,"ipAddress")),...Ye("userAgent",w(n,"userAgent"))}})}function si(e){return Array.isArray(e)||l(),e.map(t=>{let n=p(t);return {id:A(n.id),userId:A(n.userId),providerId:A(n.providerId),accountId:A(n.accountId),scopes:W(n.scopes),createdAt:O(n.createdAt),updatedAt:O(n.updatedAt)}})}function ai(e){let t=p(e);return {url:A(t.url),redirect:b(t.redirect)}}function ui(e){let t=p(e);return {success:b(t.success),message:A(t.message)}}function Ye(e,t){return t===void 0?{}:{[e]:t}}function he(e,t){return !e||!t?false:e.permissions.includes(t)}function ci(e,t){return !e||!t?false:e.teams?.includes(t)??false}function ye(e,t){if(!e)return false;let{role:n,permission:i,teamId:o}=t;return !(n===void 0&&i===void 0&&o===void 0||n!==void 0&&e.role!==n||i!==void 0&&!e.permissions.includes(i)||o!==void 0&&!ci(e,o))}function di(e){return {has:t=>ye(e,t),hasPermission:t=>he(e,t.permission)}}var li=new Set(["pending","accepted","rejected","canceled"]),Ze=1e4;function M(e,t,n){let i=p(e),o={id:y(i.id),name:y(i.name),slug:y(i.slug),createdAt:O(i.createdAt),...X("logo",w(i,"logo")),...X("metadata",i.metadata===void 0?void 0:ge(i.metadata))};return N(o.id,t),N(o.slug,n),o}function et(e){return _(e,M)}function Ae(e,t,n){return e===null?null:(t===null&&l(),M(e,t,n))}function tt(e,t,n){if(e===null)return null;let i=p(e),o=M(i,t,n);return {...o,members:_(i.members,s=>gt(s,o.id)),invitations:_(i.invitations,s=>z(s,void 0,o.id))}}function nt(e,t){let n=_(e,i=>ft(i));return Y(n.map(i=>i.organizationId),t),n}function it(e,t,n){return e===null?null:(t===null&&l(),ft(e,t,n))}function ot(e,t){let n=p(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&l(),{members:pi(n.members,t),total:n.total}}function z(e,t,n){let i=p(e),o=y(i.status);li.has(o)||l();let s={id:y(i.id),organizationId:y(i.organizationId),email:y(i.email),role:y(i.role),status:o,inviterId:y(i.inviterId),expiresAt:O(i.expiresAt),createdAt:O(i.createdAt)};return N(s.id,t),N(s.organizationId,n),s}function rt(e,t){let n=_(e,i=>z(i));return Y(n.map(i=>i.organizationId),t),n}function st(e){return _(e,t=>{let n=p(t);return {...z(n),organizationName:y(n.organizationName)}})}function at(e,t){let n=p(e);return {...z(n,t),organizationName:y(n.organizationName),organizationSlug:y(n.organizationSlug),inviterEmail:y(n.inviterEmail)}}function ut(e,t){let n=p(e),i=z(n.invitation,t);return {invitation:i,member:F(n.member,void 0,i.organizationId)}}function ct(e,t){let n=p(e);return n.member!==null&&l(),{invitation:n.invitation===null?null:z(n.invitation,t),member:null}}function dt(e,t){return e===null?null:z(e,t)}function lt(e,t,n){let i=p(e);return {member:F(i.member,n,t)}}function F(e,t,n){let i=p(e),o={id:y(i.id),organizationId:y(i.organizationId),userId:y(i.userId),role:y(i.role),createdAt:O(i.createdAt),...i.user===void 0?{}:{user:mt(i.user)}};return N(o.id,t),N(o.organizationId,n),o}function pt(e,t){let n=_(e,i=>{let o=p(i);return {organizationId:y(o.organizationId),data:{role:y(o.role),...X("permission",o.permission===void 0?void 0:fi(o.permission))}}});return Y(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function ft(e,t,n){let i=p(e),o=i.updatedAt,s={id:y(i.id),name:y(i.name),organizationId:y(i.organizationId),createdAt:O(i.createdAt),...o===void 0?{}:{updatedAt:O(o)}};return N(s.id,t),N(s.organizationId,n),s}function gt(e,t){let n=p(e);return {...F(n,void 0,t),user:mt(n.user)}}function pi(e,t){let n=_(e,i=>gt(i));return Y(n.map(i=>i.organizationId),t),n}function fi(e){let t=p(e),n={};for(let[i,o]of Object.entries(t))(i==="__proto__"||i==="constructor"||i==="prototype"||i.length===0||i.length>Ze||!Array.isArray(o))&&l(),n[i]=o.map(s=>y(s));return n}function y(e){let t=A(e);return (t.length===0||t.length>Ze)&&l(),t}function N(e,t){t!==void 0&&e!==t&&l();}function Y(e,t){let n=t??e[0];n!==void 0&&e.some(i=>i!==n)&&l();}function mt(e){let t=p(e);return {id:y(t.id),name:y(t.name),email:y(t.email),...X("image",w(t,"image"))}}function _(e,t){return Array.isArray(e)||l(),e.map(n=>t(n))}function X(e,t){return t===void 0?{}:{[e]:t}}function ht(e,t,n=()=>null){let{post:i,mutation:o}=L(e,t),s=(r,u,c,f)=>e.request(r,{query:u,fetchOptions:c,decode:f});return {create:(r,u)=>o(i("/organization/create",r,u,M)),list:r=>s("/organization/list",void 0,r,et),get:(r={},u)=>s("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},u,c=>tt(c,r.organizationId,r.organizationSlug)),setActive:(r,u)=>o(i("/organization/set-active",r,u,c=>Ae(c,r.organizationId,r.organizationSlug))),listTeams:(r={},u)=>s("/organization/list-teams",{organizationId:r.organizationId},u,c=>nt(c,r.organizationId)),setActiveTeam:(r,u)=>o(i("/organization/set-active-team",r,u,c=>it(c,r.teamId))),update:(r,u)=>o(i("/organization/update",r,u,c=>Ae(c,r.organizationId))),delete:(r,u)=>o(i("/organization/delete",r,u,c=>M(c,r.organizationId))),listMembers:(r={},u)=>s("/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},u,c=>ot(c,r.organizationId)),inviteMember:(r,u)=>o(i("/organization/invite-member",r,u,c=>z(c,void 0,r.organizationId))),listInvitations:(r={},u)=>s("/organization/list-invitations",{organizationId:r.organizationId},u,c=>rt(c,r.organizationId)),listUserInvitations:r=>s("/organization/list-user-invitations",void 0,r,st),getInvitation:(r,u)=>s("/organization/get-invitation",{id:r.id},u,c=>at(c,r.id)),acceptInvitation:(r,u)=>o(i("/organization/accept-invitation",r,u,c=>ut(c,r.invitationId))),rejectInvitation:(r,u)=>o(i("/organization/reject-invitation",r,u,c=>ct(c,r.invitationId))),cancelInvitation:(r,u)=>o(i("/organization/cancel-invitation",r,u,c=>dt(c,r.invitationId))),removeMember:(r,u)=>o(i("/organization/remove-member",r,u,c=>lt(c,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,u)=>o(i("/organization/update-member-role",r,u,c=>F(c,r.memberId,r.organizationId))),leave:(r,u)=>o(i("/organization/leave",r,u,c=>F(c,void 0,r.organizationId))),listRoles:(r={},u)=>s("/organization/list-roles",{organizationId:r.organizationId},u,c=>pt(c,r.organizationId)),has:r=>ye(n(),r),hasPermission:r=>he(n(),r.permission)}}var yt=4096,gi=4096,mi=100,hi=256,yi=16,Ai=64,bi=12;function we(e){let t=p(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&l(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:Nt(t.twoFactorMethods,yi,Ai)}}):(t.twoFactorRedirect!==void 0&&l(),{redirect:b(t.redirect),...Si(t,"url"),user:v(t.user)})}function At(e){let t=p(e);return {user:v(t.user)}}function bt(e){let t=p(e);return {sessionCreated:b(t.sessionCreated),user:v(t.user)}}function wt(e,t){let n=p(e),i=b(n.redirect);n.user===null&&l();let o=n.user!==void 0&&n.user!==null,s=n.url!==void 0&&n.url!==null;return i?((o||!s)&&l(),{redirect:true,url:be(n.url,t)}):(o===s&&l(),o?{redirect:false,user:v(n.user)}:{redirect:false,url:be(n.url,t)})}function Ot(e,t){let n=p(e);return (n.redirect!==true||n.user!==void 0)&&l(),{redirect:true,url:be(n.url,t)}}function kt(e){return {status:b(p(e).status)}}function Rt(e){return {success:b(p(e).success)}}function St(e){return p(e).status!=="pending"&&l(),{status:"pending"}}function It(e){let t=p(e);if(t.kind==="authowl_turnstile")return {kind:"authowl_turnstile"};t.kind!=="akedly_shield_v1_2"&&l();let n=p(t.turnstile),i=n.siteKey===null?null:A(n.siteKey);return {kind:"akedly_shield_v1_2",connectionId:A(t.connectionId),challenge:A(t.challenge),difficulty:wi(t.difficulty),challengeToken:A(t.challengeToken),challengeRequired:b(t.challengeRequired),turnstile:{required:b(n.required),siteKey:i}}}function wi(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>bi)&&l(),Number(e)}function Pt(e){let t=p(e);return (t.status!==true||t.sessionCreated!==true)&&l(),{status:true,sessionCreated:true,user:Oi(t.user)}}function Oe(e){return {status:b(p(e).status)}}function Tt(e){return {status:b(p(e).status)}}function xt(e){let t=p(e);return {status:b(t.status),user:v(t.user)}}function vt(e){return {success:b(p(e).success)}}function Ct(e){let t=p(e);return {totpURI:Ri(t.totpURI),backupCodes:Ut(t.backupCodes)}}function Et(e){return {status:b(p(e).status)}}function Q(e){return p(e).status!==true&&l(),{status:true}}function Dt(e){return {status:b(p(e).status)}}function zt(e){let t=p(e);return t.status!==void 0&&t.status!==true&&l(),{backupCodes:Ut(t.backupCodes)}}function Oi(e){let t=p(e);return {id:q(t.id,512),...Ii(t,"name",1024),phoneNumber:q(t.phoneNumber,64),phoneNumberVerified:b(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:O(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:O(t.updatedAt)}}}function be(e,t){let n=q(e,yt);/[\u0000-\u0020\u007f]/u.test(n)&&l();let i;try{i=new URL(n);}catch{return l()}return (i.username||i.password)&&l(),i.protocol==="https:"||t&&i.protocol==="http:"&&ki(i.hostname)?i.href:l()}function ki(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Ri(e){let t=q(e,gi),n;try{n=new URL(t);}catch{return l()}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))&&l(),t}function Ut(e){return Nt(e,mi,hi)}function Nt(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&l();let i=e.map(o=>q(o,n));return i.some(o=>o.trim().length===0)&&l(),new Set(i).size!==i.length&&l(),i}function q(e,t){let n=A(e);return (n.length===0||n.length>t)&&l(),n}function Si(e,t){let n=e[t];return n==null?{}:{[t]:q(n,yt)}}function Ii(e,t,n){let i=w(e,t);return i===void 0?{}:(i!==null&&i.length>n&&l(),{[t]:i})}var _t=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Z=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 ee(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||Mt(n,i)||Lt(i)||_t.has(i))return {valid:false}}let t=Pi(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 s=o.codePointAt(0);if(s===void 0||Mt(o,s)||Lt(s)||_t.has(s))return false;n??=s,i=s;}return t>0&&n!==void 0&&i!==void 0&&!Z.has(n)&&!Z.has(i)}function te(){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 Pi(e){let t=0,n=e.length;for(;t<n;){let i=e.codePointAt(t);if(i===void 0||!Z.has(i))break;t+=i>65535?2:1;}for(;n>t;){let i=e.codePointAt(n-1);if(i===void 0)break;let s=i>=56320&&i<=57343?n-2:n-1,r=e.codePointAt(s);if(r===void 0||!Z.has(r))break;n=s;}return e.slice(t,n)}function Lt(e){return e>=0&&e<=31||e>=127&&e<=159}function Mt(e,t){return e.length===1&&t>=55296&&t<=57343}var Ht=12,Vt=5e3,Ti=8,xi=1e3,vi=16,Ft=512,Kt=100,jt=8192,Ci=32768,Re=1024,qt=256,Ie=64,Ei=6e5,Di=/^[A-Za-z0-9_-]+$/u,zi=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,Ui=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,Ni=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,_i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,Bt=new Set(["discouraged","preferred","required"]),Li=new Set(["singleDevice","multiDevice"]),Jt=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),$t=new Set(["hybrid","security-key","client-device"]),Mi=new Set(["none","indirect","direct","enterprise"]),Fi=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),qi=new Set(["platform","cross-platform"]),Hi=new Set(["discouraged","preferred","required"]),Vi=new Set([-8,-7,-257]);function Wt(e){let t=D(e,Ht,Vt);return {challenge:rn(t.challenge),...S("timeout",nn(t.timeout)),...S("rpId",sn(t.rpId)),...S("allowCredentials",tn(t.allowCredentials)),...S("userVerification",J(t.userVerification,Bt)),...S("hints",ne(t.hints,$t)),...S("extensions",on(t.extensions))}}function Gt(e){let t=D(e,Ht,Vt);return {challenge:rn(t.challenge),rp:Ki(t.rp),user:ji(t.user),pubKeyCredParams:Bi(t.pubKeyCredParams),...S("timeout",nn(t.timeout)),...S("excludeCredentials",tn(t.excludeCredentials)),...S("authenticatorSelection",Ji(t.authenticatorSelection)),...S("attestation",J(t.attestation,Mi)),...S("attestationFormats",ne(t.attestationFormats,Fi)),...S("hints",ne(t.hints,$t)),...S("extensions",on(t.extensions))}}function Xt(e){let t=p(e),n=G(t.session),i=v(t.user);return n.userId!==i.id&&l(),{session:n,user:i}}function Pe(e){let t=p(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&l();let i=Te(t.deviceType,Li),o=b(t.backedUp);return o&&i!=="multiDevice"&&l(),{id:H(t.id,qt),...Gi(t),publicKey:$i(t.publicKey,Ci),userId:H(t.userId,qt),credentialID:oe(t.credentialID,jt),counter:n,deviceType:i,backedUp:o,...Xi(t),createdAt:O(t.createdAt),...Yi(t)}}function Yt(e,t,n){let i=Pe(e);return (i.credentialID!==t||(n===void 0?i.name!==void 0&&i.name!==null:i.name!==n))&&l(),i}function Qt(e){(!Array.isArray(e)||e.length>Kt)&&l();let t=e.map(Pe);return ie(t.map(n=>n.id)),ie(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&l(),t}function Zt(e,t,n){let i=p(e),o=Pe(i.passkey);return (o.id!==t||o.name!==n)&&l(),{passkey:o}}function en(e){return p(e).status!==true&&l(),{status:true}}function Ki(e){let t=p(e);return {name:Se(t.name,Re),...S("id",sn(t.id))}}function ji(e){let t=p(e);return {id:oe(t.id,128,1,64),name:Se(t.name,Re),displayName:Se(t.displayName,Re)}}function Bi(e){(!Array.isArray(e)||e.length===0||e.length>Ie)&&l();let t=e.map(n=>{let i=p(n);return (i.type!=="public-key"||!Number.isSafeInteger(i.alg)||!Vi.has(i.alg))&&l(),{type:"public-key",alg:i.alg}});return Qi(t.map(n=>n.alg)),t}function tn(e){if(e===void 0)return;(!Array.isArray(e)||e.length>Kt)&&l();let t=e.map(n=>{let i=p(n);return i.type!=="public-key"&&l(),{type:"public-key",id:oe(i.id,jt),...S("transports",ne(i.transports,Jt))}});return ie(t.map(n=>n.id)),t}function Ji(e){if(e===void 0)return;let t=p(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&l();let n=J(t.residentKey,Hi);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&l(),{...S("authenticatorAttachment",J(t.authenticatorAttachment,qi)),...S("residentKey",n),...S("requireResidentKey",t.requireResidentKey),...S("userVerification",J(t.userVerification,Bt))}}function nn(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>Ei)&&l(),e}function on(e){return e===void 0?void 0:D(e,Ti,xi)}function ne(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>Ie)&&l();let n=e.map(i=>Te(i,t));return ie(n),n}function J(e,t){if(e!==void 0)return Te(e,t)}function rn(e){return oe(e,Math.ceil(Ft*4/3),vi,Ft)}function oe(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=H(e,t),s=o.length%4,r=Wi(o.at(-1)??""),u=Math.floor(o.length*3/4);return (!Di.test(o)||s===1||s===2&&(r&15)!==0||s===3&&(r&3)!==0||u<n||u>i)&&l(),o}function H(e,t){let n=A(e);return (n.length===0||n.length>t)&&l(),n}function Se(e,t){let n=H(e,t);return Ui.test(n)&&l(),n}function sn(e){if(e===void 0)return;let t=H(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!Ni.test(n)))&&l(),t}function $i(e,t){let n=H(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),s=n.at(i?-3:o?-2:-1)??"",r=an(s);return (n.length%4!==0||!zi.test(n)||i&&(r&15)!==0||o&&(r&3)!==0)&&l(),n}function Wi(e){return an(e,true)}function an(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function Gi(e){let t=w(e,"name");return t===void 0?{}:(t!==null&&!ke(t)&&l(),{name:t})}function Xi(e){let t=w(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>Ie||n.some(i=>!Jt.has(i))||new Set(n).size!==n.length)&&l(),{transports:t}}function Yi(e){let t=w(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(_i.test(t)||l(),{aaguid:t})}function Te(e,t){let n=A(e);return t.has(n)||l(),n}function S(e,t){return t===void 0?{}:{[e]:t}}function ie(e){new Set(e).size!==e.length&&l();}function Qi(e){new Set(e).size!==e.length&&l();}function ao(e,t){if(!t)return e;let n=t.catch(()=>{});return n.then(()=>{n=null;}),{async request(i,o){return n&&await n,e.request(i,o)}}}var gn=new Map;function uo(e,t){let n=gn.get(t);return n||(n=Promise.resolve().then(()=>(se(),re)).then(i=>i.completeCrossSiteSignIn(e)),gn.set(t,n)),n}function mn(e){return !j()||e.idToken||e.disableRedirect?"legacy":"first-party"}function co(e,t=()=>{},n=fo){let i=Ke(e),o=j()?uo(i,e.decoded.projectId):void 0,s=ao(i,o),r=Je(s,e.decoded.projectId),u=n(s,r.notifyMutation),c=()=>{r.notifyMutation(),t();},{post:f,mutation:m}=L(s,c),k=e.decoded.env==="test";return {sessionStore:r.store,getSession:r.getSession,account:Qe(s,c),organization:ht(s,c,()=>r.store.getSnapshot().data?.session.membership??null),signIn:{email:(a,d)=>m(f("/sign-in/email",a,d,we),g=>!("twoFactorRedirect"in g)),username:(a,d)=>m(f("/sign-in/username",a,d,we),g=>!("twoFactorRedirect"in g)),social:async(a,d)=>{if(mn(a)==="first-party"){let{beginCrossSiteSignIn:R}=await Promise.resolve().then(()=>(se(),re)),h=await R(e,{kind:"social",provider:a.provider,callbackURL:a.callbackURL,errorCallbackURL:a.errorCallbackURL,newUserCallbackURL:a.newUserCallbackURL,scopes:a.scopes,loginHint:a.loginHint,requestSignUp:a.requestSignUp});if(h)return window.location.assign(h),{data:{redirect:true,url:h},error:null}}let g=await m(f("/sign-in/social",a,d,R=>wt(R,k)),R=>"user"in R);return g.error!==null||g.data===null||"url"in g.data&&g.data.redirect&&!a.disableRedirect&&typeof window<"u"&&window.location.assign(g.data.url),g},sso:async(a,d)=>{if(mn(a)==="first-party"){let{beginCrossSiteSignIn:R}=await Promise.resolve().then(()=>(se(),re)),h=await R(e,{kind:"sso",email:a.email,providerId:a.providerId,domain:a.domain,organizationSlug:a.organizationSlug,callbackURL:a.callbackURL,errorCallbackURL:a.errorCallbackURL,newUserCallbackURL:a.newUserCallbackURL});if(h)return window.location.assign(h),{data:{url:h,redirect:true},error:null}}let g=await f("/sign-in/sso",a,d,R=>Ot(R,k));return g.error!==null||g.data===null||typeof window<"u"&&window.location.assign(g.data.url),g},magicLink:(a,d)=>f("/sign-in/magic-link",a,d,kt),emailOtp:(a,d)=>m(f("/sign-in/email-otp",a,d,At)),passkey:(a,d)=>u.signIn(a,d)},signUp:{email:(a,d)=>m(f("/sign-up/email",a,d,bt),g=>g.sessionCreated)},emailOtp:{sendVerificationOtp:(a,d)=>f("/email-otp/send-verification-otp",a,d,Rt),verifyEmail:(a,d)=>m(f("/email-otp/verify-email",a,d,xt))},phoneOtp:{prepare:a=>f("/phone-otp/challenge",{},a,It),start:(a,d)=>f("/phone-otp/start",{...a,idempotencyKey:a.idempotencyKey??$e()},d,St),verify:(a,d)=>m(f("/phone-otp/verify",a,d,Pt))},requestPasswordReset:(a,d)=>f("/request-password-reset",a,d,Oe),resetPassword:(a,d)=>f("/reset-password",a,d,Oe),sendVerificationEmail:(a,d)=>f("/send-verification-email",a,d,Tt),passkey:{addPasskey:(a,d)=>u.add(a,d),listUserPasskeys:()=>s.request("/passkey/list-user-passkeys",{decode:Qt}),updatePasskey:async(a,d)=>{let g=ee(a.name);if(!g.valid||g.value===void 0)return te();let R=g.value;return f("/passkey/update-passkey",{...a,name:R},d,h=>Zt(h,a.id,R))},deletePasskey:(a,d)=>f("/passkey/delete-passkey",a,d,en)},twoFactor:{enable:(a,d)=>f("/two-factor/enable",a,d,Ct),disable:(a,d)=>m(f("/two-factor/disable",a,d,Et),g=>g.status),verifyTotp:(a,d)=>m(f("/two-factor/verify-totp",a,d,Q)),verifyBackupCode:(a,d)=>m(f("/two-factor/verify-backup-code",a,d,Q)),sendOtp:(a={},d)=>f("/two-factor/send-otp",a,d,Dt),verifyOtp:(a,d)=>m(f("/two-factor/verify-otp",a,d,Q)),generateBackupCodes:(a,d)=>f("/two-factor/generate-backup-codes",a,d,zt)},signOut:a=>m(s.request("/sign-out",{method:"POST",body:{},fetchOptions:a,decode:vt}),d=>d.success)}}function ve(e,t=()=>{},n){let i=co(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:hn(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp,passkey:i.signIn.passkey},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey,addPasskey:i.passkey.addPasskey}}:{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:hn(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function hn(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return lo();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?po():i}}function lo(){return Promise.resolve({data:null,error:{status:400,statusText:"BAD_REQUEST",code:"NATIVE_SOCIAL_ID_TOKEN_REQUIRED",message:"Native social sign-in requires a provider ID token."}})}function po(){return Promise.resolve({data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_NATIVE_SOCIAL_RESPONSE",message:"The server returned a redirect for native ID-token sign-in."}})}function fo(){return {signIn:()=>yn(),add:()=>yn()}}function yn(){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 go(e,t,n){let i=new Map;return {async signIn(o={},s){let r=await e.request("/passkey/generate-authenticate-options");if(!r.data)return wn(r.error);let u;try{u=Wt(r.data);}catch{return An()}let c;try{c=await n.authenticate({optionsJSON:u,useBrowserAutofill:o.autoFill});}catch(d){return On(n,d,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!mo(c))return bn();let{clientExtensionResults:f,...m}=c,k=i.get(c.id);if(k)return k;let a=(async()=>{let d=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:m},fetchOptions:s,decode:Xt});return d.data&&t(),d})();i.set(c.id,a);try{return await a}finally{i.get(c.id)===a&&i.delete(c.id);}},async add(o={},s){let r=ee(o.name);if(!r.valid)return te();let u=await e.request("/passkey/generate-register-options",{query:{name:r.value,authenticatorAttachment:o.authenticatorAttachment}});if(!u.data)return wn(u.error);let c;try{c=Gt(u.data);}catch{return An()}let f;try{f=await n.register({optionsJSON:c});}catch(d){return On(n,d,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!ho(f))return bn();let{clientExtensionResults:m,...k}=f,a=await e.request("/passkey/verify-registration",{method:"POST",body:{response:k,name:r.value},fetchOptions:s,decode:d=>Yt(d,f.id,r.value)});return a.data&&t(),a}}}function An(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function bn(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function kn(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 mo(e){if(!kn(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 ho(e){if(!kn(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function wn(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function On(e,t,n,i){let o=Ao(t,"page does not have focus"),s=e.errorCode?.(t),r=s!==void 0?s==="ERROR_CEREMONY_ABORTED":yo(t)==="AbortError";return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:o?"PASSKEY_PAGE_NOT_FOCUSED":r?n:s??"PASSKEY_BROWSER_ERROR",message:o?"Keep this page focused while completing the passkey prompt.":r?i:n==="AUTH_CANCELLED"?"Passkey authentication could not be completed by this browser.":"Passkey registration could not be completed by this browser."}}}function yo(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function Ao(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}var Ce=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 Rn(e,t,n={}){let i=new Headers(n.init?.headers);return i.set("x-publishable-key",e.publishableKey),$({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 Sn(e,t){if(!e.response.ok)throw new Ce(t,e.response,e.requestId);return e.data}async function bo(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return Sn(await Rn(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>wo(i,e)}),"public-config")}function wo(e,t){let n=D(e),i=n.environmentId,o=n.environmentType,s=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Oo(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==s)throw C();let r=T(n.branding),u=T(n.legal);if(!Ee(n.enabledMethods,64)||!Ee(n.socialProviders,64)||!Pn(r,["appName","logoUrl","primaryColor"])||r.showAppName!==void 0&&typeof r.showAppName!="boolean"||r.alignment!==void 0&&r.alignment!=="left"&&r.alignment!=="center"&&r.alignment!=="right"||r.theme!==void 0&&r.theme!=="light"&&r.theme!=="dark"&&r.theme!=="system"||!Pn(u,["termsUrl","privacyUrl"])||!Number.isSafeInteger(u.version)||u.version<0||typeof u.required!="boolean")throw C();if(n.socialProviderClientIds!==void 0){let c=T(n.socialProviderClientIds);if(Object.keys(c).length>64||Object.values(c).some(f=>typeof f!="string"||f.length>2048))throw C()}if(!U(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!In(n.turnstileSiteKey)||!In(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw C();if(n.jwtIssuer!==null){let c=T(n.jwtIssuer);if(c.issuer!==s||c.jwksUrl!==`${s}/jwks`||c.aud!==t.decoded.projectId)throw C()}if(n.signUp!==void 0){let c=T(n.signUp).mode;if(typeof c!="string"||!["open","restricted","allowlist","waitlist"].includes(c))throw C()}if(n.authentication!==void 0&&ko(n.authentication),n.emailVerification!==void 0){let c=T(n.emailVerification);if(!U(c,["required"])||c.method!=="link"&&c.method!=="code")throw C()}if(n.userModel!==void 0&&!U(T(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw C();if(n.mfa!==void 0){let c=T(n.mfa);if(!U(c,["totp","required","backupCodes"])||(c.required===true||c.backupCodes===true)&&c.totp!==true)throw C()}return n}function Oo(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 C(){return new TypeError("public-config returned an invalid response")}function T(e){if(!e||typeof e!="object"||Array.isArray(e))throw C();return e}function In(e){return e===null||typeof e=="string"&&e.length<=4096}function ko(e){let t=T(e),n=T(t.email),i=T(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!U(n,["signUp"])||!Ee(n.signIn,3)||n.signIn.some(s=>s!=="password"&&s!=="magic_link"&&s!=="email_otp")||!U(T(t.phone),["signUp","signIn"])||!U(i,["signUp","add"])||o&&(!Number.isSafeInteger(i.minLength)||!Number.isSafeInteger(i.maxLength)||i.minLength<1||i.maxLength>4096||i.minLength>i.maxLength)||!U(T(t.passkey),["signIn","add"])||!U(T(t.username),["collectOnSignUp","signIn"]))throw C()}function U(e,t){return t.every(n=>typeof e[n]=="boolean")}function Pn(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function Ee(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length<=128)&&new Set(e).size===e.length}function Ro(e){let t=e?.enabledMethods??["password"],n=t.includes("password"),i=t.includes("passkey"),o=e?.authentication,s=e?.mfa;return {emailSignUp:o?.email.signUp??t.some(r=>r==="password"||r==="magic_link"||r==="email_otp"),passwordSignUp:o?.password.signUp??n,phoneSignUp:o?.phone.signUp??t.includes("phone_otp"),passwordSignIn:o?.email.signIn.includes("password")??n,passwordMinLength:o?.password.minLength??8,passwordMaxLength:o?.password.maxLength??128,magicLinkSignIn:o?.email.signIn.includes("magic_link")??t.includes("magic_link"),emailOtpSignIn:o?.email.signIn.includes("email_otp")??t.includes("email_otp"),phoneSignIn:o?.phone.signIn??t.includes("phone_otp"),usernameSignIn:o?.username.signIn??false,collectUsername:o?.username.collectOnSignUp??false,passkeySignIn:o?.passkey.signIn??i,passkeyAdd:o?.passkey.add??i,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}}function So(e,t){let n=`p_${e.replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}function xr(e,t){return ve(ce(e),t)}
|
|
2
|
+
exports.createMembershipHas=di;exports.createNativeAuthClient=ve;exports.createNativeClient=xr;exports.createPasskeyClient=go;exports.decodePublishableKey=ae;exports.getPublicConfig=bo;exports.resolveConfig=ce;exports.resolveProjectCapabilities=Ro;exports.sessionCookieName=So;
|
package/dist/native.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { R as ResolvedAuthConfig, A as AuthConfig } from './organization-membership-B3m6PbmO.cjs';
|
|
2
2
|
export { D as DecodedPublishableKey, H as HasParams, O as OrganizationMembership, c as createMembershipHas, d as decodePublishableKey, r as resolveConfig, s as sessionCookieName } from './organization-membership-B3m6PbmO.cjs';
|
|
3
|
-
import {
|
|
4
|
-
export {
|
|
3
|
+
import { k as AuthOwlClient, aL as SocialIdTokenOptions, bd as createAuthHttpClient, be as AuthHttpClient, al as PasskeySignInOptions, f as ActionFetchOptions, h as AuthActionResult, ak as PasskeyAuthData, g as AddPasskeyOptions, m as AuthPasskey } from './client-DOOkDLWg.cjs';
|
|
4
|
+
export { i as AuthClientError, p as AuthSession, q as AuthUser, a4 as Organization, a5 as OrganizationClient, a6 as OrganizationDetails, as as ProjectCapabilities, at as PublicConfig, aE as SessionState, aF as SessionStore, aG as SetActiveOrganizationOptions, aK as SocialAuthData, bb as getPublicConfig, bc as resolveProjectCapabilities } from './client-DOOkDLWg.cjs';
|
|
5
5
|
import { startAuthentication, startRegistration } from '@simplewebauthn/browser';
|
|
6
6
|
|
|
7
7
|
type AuthActionClient = Omit<AuthOwlClient, 'getToken' | 'getConsentStatus' | 'acceptConsent' | 'waitlist'>;
|
package/dist/native.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { R as ResolvedAuthConfig, A as AuthConfig } from './organization-membership-B3m6PbmO.js';
|
|
2
2
|
export { D as DecodedPublishableKey, H as HasParams, O as OrganizationMembership, c as createMembershipHas, d as decodePublishableKey, r as resolveConfig, s as sessionCookieName } from './organization-membership-B3m6PbmO.js';
|
|
3
|
-
import {
|
|
4
|
-
export {
|
|
3
|
+
import { k as AuthOwlClient, aL as SocialIdTokenOptions, bd as createAuthHttpClient, be as AuthHttpClient, al as PasskeySignInOptions, f as ActionFetchOptions, h as AuthActionResult, ak as PasskeyAuthData, g as AddPasskeyOptions, m as AuthPasskey } from './client-jpaYv3wu.js';
|
|
4
|
+
export { i as AuthClientError, p as AuthSession, q as AuthUser, a4 as Organization, a5 as OrganizationClient, a6 as OrganizationDetails, as as ProjectCapabilities, at as PublicConfig, aE as SessionState, aF as SessionStore, aG as SetActiveOrganizationOptions, aK as SocialAuthData, bb as getPublicConfig, bc as resolveProjectCapabilities } from './client-jpaYv3wu.js';
|
|
5
5
|
import { startAuthentication, startRegistration } from '@simplewebauthn/browser';
|
|
6
6
|
|
|
7
7
|
type AuthActionClient = Omit<AuthOwlClient, 'getToken' | 'getConsentStatus' | 'acceptConsent' | 'waitlist'>;
|
package/dist/native.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {f}from'./chunk-
|
|
1
|
+
import {f}from'./chunk-MX7KKUAW.js';export{f as createNativeAuthClient,g as createPasskeyClient,k as getPublicConfig,a as resolveProjectCapabilities}from'./chunk-MX7KKUAW.js';import {e}from'./chunk-KPXCQZUX.js';export{v as createMembershipHas,a as decodePublishableKey,e as resolveConfig,b as sessionCookieName}from'./chunk-KPXCQZUX.js';import'./chunk-T5SH3ZZP.js';function u(i,o){return f(e(i),o)}export{u as createNativeClient};
|
package/dist/server.cjs
CHANGED
|
@@ -1,2 +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=
|
|
1
|
+
'use strict';var ue=new Set(["__proto__","constructor","prototype"]);function T(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function q(e,t=20,r=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&T(),le(e,t,r)}function le(e,t=20,r=1e4){return K(e,0,{nodes:0},t,r)}function K(e,t,r,n,s){if(r.nodes+=1,(t>n||r.nodes>s)&&T(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||T(),e;if(Array.isArray(e))return e.map(p=>K(p,t+1,r,n,s));(!e||typeof e!="object")&&T();let o=Object.getPrototypeOf(e);o!==Object.prototype&&o!==null&&T();let i={};for(let[p,d]of Object.entries(e))ue.has(p)&&T(),i[p]=K(d,t+1,r,n,s);return i}var z=/^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 V(e,{label:t,allowHttpLoopback:r}){(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 n;try{n=new URL(e);}catch{b(t,"absolute URL required");}return (n.username||n.password)&&b(t,"credentials forbidden"),n.protocol!=="https:"&&n.protocol!=="http:"&&b(t,"HTTPS required"),n.protocol==="http:"&&(!r||!z.test(e))&&b(t,"HTTPS required except exact loopback"),n}function j(e,t){let r;try{r=new URL(String(e));}catch{throw new TypeError("Transport URL must be absolute.")}if(r.username||r.password||r.hash)throw new TypeError("Transport URL must not contain credentials or a fragment.");let n=r.toString();if(r.protocol!=="https:"&&!(r.protocol==="http:"&&t.allowHttpLoopback&&z.test(n)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return r}function B(e,t,r){let n=fe(e);(n.includes("//")||n.split("/").some(s=>s==="."||s==="..")||n!==""&&n!==t.pathname)&&b(r,"path traversal or duplicate separator");}function H(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&b("apiUrl","origin required");let r;try{r=new URL(e);}catch{b("apiUrl","origin required");}return r.protocol==="http:"&&(!t.allowHttpLoopback||!z.test(e))&&b("apiUrl","HTTPS required except exact loopback"),r.origin}function F(e,t,r={allowHttpLoopback:false}){let n=V(e,{label:"issuer",allowHttpLoopback:r.allowHttpLoopback}),s=V(t,{label:"jwksUri",allowHttpLoopback:r.allowHttpLoopback});return B(e,n,"issuer"),B(t,s,"jwksUri"),n.pathname!=="/"&&n.pathname.endsWith("/")&&b("issuer","trailing slash forbidden"),{issuer:n.toString().replace(/\/$/,""),jwksUri:s.toString()}}var ye=1e4,he=1024*1024,_=class extends Error{kind;requestId;constructor(t,r){super(Oe(t)),this.name="TransportError",this.kind=t,this.requestId=r;}},Z=new WeakSet;function y(e,t){let r=new _(e,t);return Z.add(r),r}async function L({fetchImpl:e,url:t,init:r={},timeoutMs:n=ye,maxResponseBytes:s=he,allowHttpLoopback:o=false,decode:i}){Y(n,"timeoutMs"),Y(s,"maxResponseBytes");let p=j(t,{allowHttpLoopback:o}),d=r.signal,m=new AbortController,u=null,h,c=new Promise(l=>{h=l;}),w=l=>{u===null&&(u=l,h({type:"abort",kind:l}),m.abort());},g=()=>w("aborted");d?.addEventListener("abort",g,{once:true});let S=setTimeout(()=>w("timeout"),n);d?.aborted&&g();try{if(u!==null)throw y(u);let l;try{l=await Promise.race([e(p.toString(),{...r,redirect:"error",signal:m.signal}).then(me=>({type:"response",response:me})),c]);}catch{throw y(u??"network")}if(l.type==="abort")throw y(l.kind);if(!ge(l.response))throw y("invalid_response");let f=l.response,k=ke(f.headers),de=await be(f,s,c,()=>u,k),W=Ae(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 _&&Z.has(l)?l:y(u??"network")}finally{clearTimeout(S),d?.removeEventListener("abort",g);}}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,r,n,s){let o=e.headers.get("content-length");if(o!==null){if(!/^\d+$/.test(o))throw G(e.body),y("invalid_response",s);if(Number(o)>t)throw G(e.body),y("response_too_large",s)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw y("network",s)}let p=[],d=0,m=null;try{for(;;){let c;try{c=await Promise.race([i.read(),r]);}catch{m=y(n()??"network",s);break}if(we(c)){m=y(c.kind,s);break}let{done:w,value:g}=c;if(w)break;if(g.byteLength!==0){if(d+=g.byteLength,d>t){m=y("response_too_large",s);break}p.push(g);}}}finally{m&&_e(i);try{i.releaseLock();}catch{}}if(m)throw m;let u=new Uint8Array(d),h=0;for(let c of p)u.set(c,h),h+=c.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{throw y("invalid_response",s)}}function we(e){return "type"in e&&e.type==="abort"}function G(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function _e(e){try{e.cancel().catch(()=>{});}catch{}}function Ae(e,t,r){if(e.status===204||e.status===205)return null;let n=Se(e.headers.get("content-type"));if(!e.ok&&(!n||t.length===0))return null;if(!n||t.length===0)throw y("invalid_response",r);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw y("invalid_response",r)}}function Se(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function ke(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,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Te=300*1e3,Ee=5e3,Ie=64*1024,Pe=64,xe=60*1e3,X=new Map,Q=new Map;function $(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4===0?t:t+"=".repeat(4-t.length%4),n=typeof atob=="function"?atob(r):globalThis.Buffer.from(r,"base64").toString("binary"),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}function ee(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode($(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof a?t:new a("Malformed JWT segment.","TOKEN_MALFORMED")}}function ne(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function te(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&$(e).byteLength===32}function Re(e){if(!ne(e))throw new a("JWKS contains a non-object key.","JWKS_KEY_INVALID");let t=new Set(["alg","crv","kid","kty","use","x","y"]),r=["d","p","q","dp","dq","qi","k","oth"];if("key_ops"in e||r.some(n=>n in e)||Object.keys(e).some(n=>!t.has(n)))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 je(e){if(!ne(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),r=new Set;for(let n of t){if(r.has(n.kid))throw new a("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function re(e,t){let r=X.get(e);if(!t&&r&&Date.now()-r.fetchedAt<Te)return r.keys;try{let n=await L({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Ee,maxResponseBytes:Ie,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>q(o)});if(!n.response.ok)throw new a(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=je(n.data);return X.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof a)throw n;if(n instanceof _)switch(n.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 Le(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await re(e,false));if(!n){let s=Q.get(e)??0;Date.now()-s>=xe&&(Q.set(e,Date.now()),n=r(await re(e,true)));}if(!n)throw new a("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}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 ve(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 r=t,n=typeof r.role=="string"?r.role:"",s=Array.isArray(r.permissions)?r.permissions.filter(i=>typeof i=="string"):[],o=Array.isArray(r.teams)?r.teams.filter(i=>typeof i=="string"):void 0;return n===""&&s.length===0&&!o?.length?null:{role:n,permissions:s,...o===void 0?{}:{teams:o}}}async function Ke(e,t){return I(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 r;try{r=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,...r}}async function I(e,t){if(typeof e!="string"||e.length===0)throw new a("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new a("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,i=ee(n);if(i.alg!=="ES256")throw new a("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await Le(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),d;try{d=await Ue(p);}catch(S){throw S instanceof a?S:new a("JWKS key could not be imported.","JWKS_KEY_INVALID")}let m;try{if(!/^[A-Za-z0-9_-]{86}$/.test(o))throw new Error("invalid signature encoding");if(m=$(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new a("Malformed JWT signature.","TOKEN_MALFORMED")}let u=new TextEncoder().encode(`${n}.${s}`),h;try{h=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,m,u);}catch{throw new a("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!h)throw new a("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let c=ee(s),w=t.clockToleranceSeconds??60,g=Math.floor(Date.now()/1e3);if(typeof c.exp!="number")throw new a("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(c.exp+w<g)throw new a("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof c.nbf=="number"&&c.nbf-w>g)throw new a("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof c.iss!="string"||c.iss!==t.issuer)throw new a("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!ve(c.aud,t.audience))throw new a("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof c.sub=="string"?c.sub:null,membership:Ne(c),claims:c}}var ze=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,$e=/^sk_/i;function se(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if($e.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 M(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=se(e.publishableKey),r=H(e.apiUrl,{allowHttpLoopback:t.env==="test"}),n=`${r}/api/projects/${t.projectId}/auth`;return {...e,apiUrl:r,decoded:t,projectBaseURL:n}}function oe(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:r,permission:n,teamId:s}=t;return !(r===void 0&&n===void 0&&s===void 0||r!==void 0&&e.role!==r||n!==void 0&&!e.permissions.includes(n)||s!==void 0&&!Me(e,s))}function Ce(e,t){let r=`p_${e.replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${r}.session_token`}var De="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",P={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"}}},getUserExport:{method:"GET",path:"/users/export/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadUserExport:{method:"GET",path:"/users/export/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},startPasswordHashUserExport:{method:"POST",path:"/users/export/hashes",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},dryRunUserImport:{method:"POST",path:"/imports/dry-run",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportDryRun"}}},createUserImport:{method:"POST",path:"/imports",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportBatch"}}},getUserImport:{method:"GET",path:"/imports/{importId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ImportBatch"}}},downloadUserImportReport:{method:"GET",path:"/imports/{importId}/report",successStatuses:[200],responseSchemas:{200:null}},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}},listMessages:{method:"GET",path:"/messages",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MessagePage"}}},sendMessage:{method:"POST",path:"/messages",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/Message"}}},getMessage:{method:"GET",path:"/messages/{messageId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Message"}}},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"}}}},C={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},ImportDryRun:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","errors","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"dry_run"},status:{type:"string",const:"validated"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},errors:{type:"array",maxItems:100,items:{type:"object",required:["line","code","path","message"],properties:{line:{type:"integer",minimum:2},code:{type:"string",enum:["INVALID_JSON","UNEXPECTED_RECORD","INVALID_USER","DUPLICATE_EXTERNAL_ID"]},path:{type:["string","null"]},message:{type:"string"}},additionalProperties:false}},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},ImportBatch:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","report_expires_at","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"commit"},status:{type:"string",const:"completed"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid","created","updated","unchanged","failed"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4},created:{type:"integer",minimum:0,maximum:1e4},updated:{type:"integer",minimum:0,maximum:1e4},unchanged:{type:"integer",minimum:0,maximum:1e4},failed:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},report_expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},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},SendMessage:{type:"object",required:["to","template","variables"],properties:{to:{type:"string",minLength:7,maxLength:32},channel:{type:"string",enum:["sms","whatsapp","auto"],description:"Defaults to auto."},purpose:{type:"string",enum:["transactional"],description:"Defaults to transactional."},template:{type:"string",pattern:"^[a-z][a-z0-9_]{0,63}$"},locale:{type:"string",enum:["en","ar"],description:"Defaults to en."},variables:{type:"object",maxProperties:50,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_]{0,63}$"},additionalProperties:{type:"string",maxLength:1024}},customerReference:{type:"string",minLength:1,maxLength:255}},additionalProperties:false},MessageState:{type:"string",enum:["preparing","queued","accepted","skipped","delivered","failed","unknown","canceled"]},Message:{type:"object",required:["id","state","purpose","requested_channel","actual_channel","customer_reference","masked_recipient","sms","billing","failure","created_at","updated_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},state:{$ref:"#/components/schemas/MessageState"},purpose:{type:"string",enum:["transactional","auth_otp"]},requested_channel:{type:"string",enum:["sms","whatsapp","auto"]},actual_channel:{type:["string","null"],enum:["sms","whatsapp",null]},customer_reference:{type:["string","null"]},masked_recipient:{type:"string"},sms:{oneOf:[{type:"null"},{type:"object",required:["encoding","segments"],properties:{encoding:{type:["string","null"],enum:["gsm7","ucs2",null]},segments:{type:["integer","null"],minimum:1}},additionalProperties:false}]},billing:{type:"object",required:["credential_mode","unit","units","charged_piasters","reserved_piasters"],properties:{credential_mode:{type:"string",enum:["managed","byok"]},unit:{type:["string","null"]},units:{type:["integer","null"]},charged_piasters:{type:"integer",minimum:0},reserved_piasters:{type:"integer",minimum:0}},additionalProperties:false},failure:{oneOf:[{type:"null"},{type:"object",required:["code","retryable"],properties:{code:{type:"string"},retryable:{type:"boolean"}},additionalProperties:false}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},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","message.accepted","message.skipped","message.delivered","message.failed"]},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","message.accepted","message.skipped","message.delivered","message.failed","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","format","status","includes_password_hashes","total_rows","artifact_bytes","failure_code","created_at","completed_at","expires_at","download_url"],properties:{id:{type:"string",format:"uuid"},format:{type:"string",enum:["ndjson","csv"]},status:{type:"string",enum:["pending","processing","completed","failed"]},includes_password_hashes:{type:"boolean"},total_rows:{type:"integer",minimum:0},artifact_bytes:{type:"integer",minimum:0},failure_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},completed_at:{type:["string","null"],format:"date-time"},expires_at:{type:["string","null"],format:"date-time"},download_url:{type:["string","null"]}},additionalProperties:false},ExportRequest:{type:"object",properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"}},additionalProperties:false},HashExportRequest:{type:"object",required:["approval_token"],properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"},approval_token:{type:"string",minLength:1,maxLength:256}},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"}}}}]},MessagePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Message"}}}}]}};var We=new Set(["__proto__","constructor","prototype"]),Je=64,qe=5e4;function ae(e,t,r){let s=P[e].responseSchemas;Object.hasOwn(s,String(t))||v();let o=s[String(t)];if(o===null){r!==null&&v();return}let i={nodes:0};return A(r,O(o),0,i)||v(),r}function A(e,t,r,n){if(n.nodes+=1,r>Je||n.nodes>qe)return false;if(typeof t.$ref=="string"){let o=Ze(t.$ref);if(o===null||!A(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>A(e,O(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>A(e,O(o),r+1,n)).length!==1||Array.isArray(t.enum)&&!t.enum.some(o=>Object.is(o,e))||t.const!==void 0&&!Object.is(t.const,e))return false;let s=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!s.some(o=>Ve(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?Be(e,t):typeof e=="number"?Fe(e,t):Array.isArray(e)?Ge(e,t,r,n):x(e)?Ye(e,t,r,n):typeof e=="boolean"}function Ve(e,t){switch(t){case "null":return e===null;case "object":return x(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);case "^[A-Za-z0-9][A-Za-z0-9._:/-]*$":return /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/.test(e);case "^[a-z][a-z0-9_]{0,63}$":return /^[a-z][a-z0-9_]{0,63}$/.test(e);case "^[A-Za-z][A-Za-z0-9_]{0,63}$":return /^[A-Za-z][A-Za-z0-9_]{0,63}$/.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,r,n){if(typeof t.minItems=="number"&&e.length<t.minItems||typeof t.maxItems=="number"&&e.length>t.maxItems||t.uniqueItems===true&&new Set(e.map(o=>JSON.stringify(o))).size!==e.length)return false;if(t.items===void 0)return true;let s=O(t.items);return e.every(o=>A(o,s,r+1,n))}function Ye(e,t,r,n){let s=Object.keys(e);if(s.some(i=>We.has(i))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=x(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(i=>!A(i,O(t.propertyNames),r+1,n))||Array.isArray(t.required)&&t.required.some(i=>typeof i!="string"||!Object.hasOwn(e,i)))return false;for(let[i,p]of Object.entries(e)){let d=o[i];if(d!==void 0){if(!A(p,O(d),r+1,n))return false;continue}if(t.additionalProperties===false||x(t.additionalProperties)&&!A(p,t.additionalProperties,r+1,n))return false}return true}function Ze(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(C,r)?O(C[r]):null}function O(e){return x(e)||v(),e}function x(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function v(){throw new TypeError("Admin API response does not match its generated contract.")}var Xe=/^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;}},E=class extends Error{kind;requestId;constructor(t,r){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=r;}};function tt(e){rt();let t=nt(e?.secretKey),r=st(e?.apiUrl),n=e?.fetch??globalThis.fetch;if(typeof n!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let s=async(i,p)=>{let d=p??{},m=P[i],u=new URL(ot(m.path,d).replace(/^\/+/,""),r);it(u,d);let h=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});at(h,d);let c="body"in d?JSON.stringify(d.body):void 0;c!==void 0&&h.set("content-type","application/json");let w;try{w=await L({fetchImpl:n,url:u,init:{method:m.method,headers:h,body:c,signal:p?.signal},timeoutMs:et,maxResponseBytes:Qe,allowHttpLoopback:r.protocol==="http:",decode:(f,k)=>ae(i,k.status,f)});}catch(f){throw f instanceof R?f:f instanceof _?new E(f.kind,f.requestId):new E("network")}let{response:g,requestId:S,data:l}=w;if(!g.ok)throw pt(g,l,S);if(!m.successStatuses.some(f=>f===g.status))throw new E("invalid_response",S);return l},o=Object.assign(Object.create(null),{request:s});for(let i of Object.keys(P))o[i]=p=>s(i,p);return Object.freeze(o)}function rt(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function nt(e){if(typeof e!="string"||!Xe.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function st(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=j(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 r=t.pathname.replace(/\/+$/,"");if(r!==""&&r!=="/api/v1")throw new TypeError("apiUrl path must be empty or /api/v1.");return t.pathname="/api/v1/",t}function ot(e,t){let r="path"in t&&N(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(n,s)=>{let o=r[s];if(typeof o!="string"&&typeof o!="number")throw new TypeError(`Missing Admin API path parameter: ${s}.`);return encodeURIComponent(String(o))})}function it(e,t){if(!(!("query"in t)||!N(t.query)))for(let[r,n]of Object.entries(t.query)){if(n==null)continue;let s=Array.isArray(n)?n:[n];for(let o of s)e.searchParams.append(r,String(o));}}function at(e,t){if(!(!("header"in t)||!N(t.header)))for(let[r,n]of Object.entries(t.header)){if(n==null)continue;if(r.toLowerCase()!=="idempotency-key")throw new TypeError(`Unsupported Admin API header parameter: ${r}.`);if(typeof n!="string"||n.length<1||n.length>255)throw new TypeError("Idempotency-Key must contain between 1 and 255 characters.");if(!/^[\x21-\x7e ]+$/.test(n))throw new TypeError("Idempotency-Key contains unsupported characters.");e.set("Idempotency-Key",n);}}function pt(e,t,r){let n=r??pe(e.headers.get("x-request-id"),256),s=pe(e.headers.get("retry-after"),128),o=ct(e.status,n),i=dt(t)?t:o;return new R({status:e.status,code:i.code,requestId:n,problem:i,retryAfter:s})}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 dt(e){return N(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 N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var mt=/^v1=([a-f0-9]{64})$/i,ut=/^whsec_[A-Za-z0-9_-]{1,256}$/,lt=/^(0|[1-9]\d{0,10})$/;async function ft(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=yt(e.secrets),r=e.toleranceSeconds??300;if(!Number.isSafeInteger(r)||r<0||r>3600)throw new TypeError("Webhook toleranceSeconds must be an integer from 0 to 3600.");let n=e.now??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(n)||n<0)throw new TypeError("Webhook now must be a non-negative Unix timestamp.");let s=gt(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!lt.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let i=ht(e.signatureHeader);if(i.length===0)return false;let p=new TextEncoder().encode(`${e.timestamp}.`),d=new Uint8Array(p.byteLength+s.byteLength);d.set(p),d.set(s,p.byteLength);let m=false;for(let u of t){let h=await crypto.subtle.importKey("raw",new TextEncoder().encode(u),{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=new Uint8Array(await crypto.subtle.sign("HMAC",h,d));for(let w of i)m=wt(c,w)||m;}return m}function yt(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 ht(e){if(typeof e!="string"||e.length>1024)return [];let t=e.split(",");if(t.length>4)return [];let r=[];for(let n of t){let s=mt.exec(n.trim());s&&r.push(bt(s[1]));}return r}function gt(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 bt(e){let t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(r*2,r*2+2),16);return t}function wt(e,t){if(e.byteLength!==t.byteLength)return false;let r=0;for(let n=0;n<e.byteLength;n+=1)r|=e[n]^t[n];return r===0}var ce=["publishableKey","apiUrl","issuer","jwksUri","audience"],_t=new Set([...ce,"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(p=>!_t.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(ce.filter(p=>Object.prototype.hasOwnProperty.call(e??{},p))),r=t.has("publishableKey")||t.has("apiUrl"),n=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n){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 s,o;if(r){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e.publishableKey,o=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o=process.env.AUTHOWL_API_URL;if(!s||!o)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=M({publishableKey:s,apiUrl:o});return U({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},i.decoded.env==="test")}async function Ht(e,t){return I(e,D(t))}async function Ft(e,t,r){let n=D(r);try{let s=await I(e,n);return ie(s.membership,t)}catch{return false}}async function Gt(e,t,r){let n=D(r);try{let s=await I(e,n);return oe(s.membership,t.permission)}catch{return false}}
|
|
2
|
+
exports.ADMIN_API_SPEC_SHA256=De;exports.AuthOwlAdminApiError=R;exports.AuthOwlAdminNetworkError=E;exports.TokenVerificationError=a;exports.createAdminClient=tt;exports.has=Ft;exports.hasPermission=Gt;exports.resolveConfig=M;exports.sessionCookieName=Ce;exports.verifyProjectToken=Ke;exports.verifyToken=Ht;exports.verifyWebhook=ft;
|