@authowl/core 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var ve=new Set(["__proto__","constructor","prototype"]);function P(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function re(e,t=20,r=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&P(),je(e,t,r)}function je(e,t=20,r=1e4){return F(e,0,{nodes:0},t,r)}function F(e,t,r,n,s){if(r.nodes+=1,(t>n||r.nodes>s)&&P(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||P(),e;if(Array.isArray(e))return e.map(a=>F(a,t+1,r,n,s));(!e||typeof e!="object")&&P();let o=Object.getPrototypeOf(e);o!==Object.prototype&&o!==null&&P();let i={};for(let[a,p]of Object.entries(e))ve.has(a)&&P(),i[a]=F(p,t+1,r,n,s);return i}var G=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function S(e,t){throw new Error(`${e}: ${t}`)}function Ne(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function ne(e,{label:t,allowHttpLoopback:r}){(typeof e!="string"||e.length===0)&&S(t,"required"),e!==e.trim()&&S(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&S(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&S(t,"path must be unencoded");let n;try{n=new URL(e);}catch{S(t,"absolute URL required");}return (n.username||n.password)&&S(t,"credentials forbidden"),n.protocol!=="https:"&&n.protocol!=="http:"&&S(t,"HTTPS required"),n.protocol==="http:"&&(!r||!G.test(e))&&S(t,"HTTPS required except exact loopback"),n}function W(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&&G.test(n)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return r}function se(e,t,r){let n=Ne(e);(n.includes("//")||n.split("/").some(s=>s==="."||s==="..")||n!==""&&n!==t.pathname)&&S(r,"path traversal or duplicate separator");}function oe(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&S("apiUrl","origin required");let r;try{r=new URL(e);}catch{S("apiUrl","origin required");}return r.protocol==="http:"&&(!t.allowHttpLoopback||!G.test(e))&&S("apiUrl","HTTPS required except exact loopback"),r.origin}function ie(e,t,r={allowHttpLoopback:false}){let n=ne(e,{label:"issuer",allowHttpLoopback:r.allowHttpLoopback}),s=ne(t,{label:"jwksUri",allowHttpLoopback:r.allowHttpLoopback});return se(e,n,"issuer"),se(t,s,"jwksUri"),n.pathname!=="/"&&n.pathname.endsWith("/")&&S("issuer","trailing slash forbidden"),{issuer:n.toString().replace(/\/$/,""),jwksUri:s.toString()}}var Ue=1e4,Ke=1024*1024,E=class extends Error{kind;requestId;constructor(t,r){super(Ve(t)),this.name="TransportError",this.kind=t,this.requestId=r;}},ce=new WeakSet;function w(e,t){let r=new E(e,t);return ce.add(r),r}async function q({fetchImpl:e,url:t,init:r={},timeoutMs:n=Ue,maxResponseBytes:s=Ke,allowHttpLoopback:o=false,decode:i}){pe(n,"timeoutMs"),pe(s,"maxResponseBytes");let a=W(t,{allowHttpLoopback:o}),p=r.signal,d=new AbortController,l=null,h,m=new Promise(f=>{h=f;}),b=f=>{l===null&&(l=f,h({type:"abort",kind:f}),d.abort());},g=()=>b("aborted");p?.addEventListener("abort",g,{once:true});let T=setTimeout(()=>b("timeout"),n);p?.aborted&&g();try{if(l!==null)throw w(l);let f;try{f=await Promise.race([e(a.toString(),{...r,redirect:"error",signal:d.signal}).then(D=>({type:"response",response:D})),m]);}catch{throw w(l??"network")}if(f.type==="abort")throw w(f.kind);if(!Ce(f.response))throw w("invalid_response");let A=f.response,y=qe(A.headers),x=await ze(A,s,m,()=>l,y),$=Me(A,x,y),N;try{N=A.ok&&i?i($,Object.freeze({status:A.status})):$;}catch{throw w("invalid_response",y)}return {response:A,data:N,...y===void 0?{}:{requestId:y}}}catch(f){throw f instanceof E&&ce.has(f)?f:w(l??"network")}finally{clearTimeout(T),p?.removeEventListener("abort",g);}}function Ce(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 ze(e,t,r,n,s){let o=e.headers.get("content-length");if(o!==null){if(!/^\d+$/.test(o))throw ae(e.body),w("invalid_response",s);if(Number(o)>t)throw ae(e.body),w("response_too_large",s)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw w("network",s)}let a=[],p=0,d=null;try{for(;;){let m;try{m=await Promise.race([i.read(),r]);}catch{d=w(n()??"network",s);break}if($e(m)){d=w(m.kind,s);break}let{done:b,value:g}=m;if(b)break;if(g.byteLength!==0){if(p+=g.byteLength,p>t){d=w("response_too_large",s);break}a.push(g);}}}finally{d&&De(i);try{i.releaseLock();}catch{}}if(d)throw d;let l=new Uint8Array(p),h=0;for(let m of a)l.set(m,h),h+=m.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw w("invalid_response",s)}}function $e(e){return "type"in e&&e.type==="abort"}function ae(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function De(e){try{e.cancel().catch(()=>{});}catch{}}function Me(e,t,r){if(e.status===204||e.status===205)return null;let n=We(e.headers.get("content-type"));if(!e.ok&&(!n||t.length===0))return null;if(!n||t.length===0)throw w("invalid_response",r);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw w("invalid_response",r)}}function We(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function qe(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function pe(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Ve(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 c=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},He=300*1e3,Be=5e3,Fe=64*1024,Ge=64,Ye=60*1e3,de=new Map,ue=new Map;function Y(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 me(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new c("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(Y(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new c("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof c?t:new c("Malformed JWT segment.","TOKEN_MALFORMED")}}function he(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function le(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&Y(e).byteLength===32}function Ze(e){if(!he(e))throw new c("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 c("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)||!le(e.x)||!le(e.y))throw new c("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 Xe(e){if(!he(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new c("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>Ge)throw new c("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(Ze),r=new Set;for(let n of t){if(r.has(n.kid))throw new c("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function fe(e,t){let r=de.get(e);if(!t&&r&&Date.now()-r.fetchedAt<He)return r.keys;try{let n=await q({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Be,maxResponseBytes:Fe,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>re(o)});if(!n.response.ok)throw new c(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=Xe(n.data);return de.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof c)throw n;if(n instanceof E)switch(n.kind){case "timeout":throw new c("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new c("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new c("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new c("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function Qe(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await fe(e,false));if(!n){let s=ue.get(e)??0;Date.now()-s>=Ye&&(ue.set(e,Date.now()),n=r(await fe(e,true)));}if(!n)throw new c("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function et(e){let t=globalThis.crypto?.subtle;if(!t)throw new c("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 tt(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function rt(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(a=>typeof a=="string"):[],o=Array.isArray(r.roles)?r.roles.filter(a=>typeof a=="string"):void 0,i=Array.isArray(r.teams)?r.teams.filter(a=>typeof a=="string"):void 0;return n===""&&s.length===0&&!o?.length&&!i?.length?null:{role:n,...o===void 0?{}:{roles:o},permissions:s,...i===void 0?{}:{teams:i}}}async function nt(e,t){return U(e,V(t))}function V(e,t=false){if(!e||typeof e!="object")throw new c("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=ie(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new c("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 c("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 c("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function U(e,t){if(typeof e!="string"||e.length===0)throw new c("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new c("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,i=me(n);if(i.alg!=="ES256")throw new c("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let a=await Qe(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),p;try{p=await et(a);}catch(T){throw T instanceof c?T:new c("JWKS key could not be imported.","JWKS_KEY_INVALID")}let d;try{if(!/^[A-Za-z0-9_-]{86}$/.test(o))throw new Error("invalid signature encoding");if(d=Y(o),d.byteLength!==64)throw new Error("invalid signature length")}catch{throw new c("Malformed JWT signature.","TOKEN_MALFORMED")}let l=new TextEncoder().encode(`${n}.${s}`),h;try{h=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},p,d,l);}catch{throw new c("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!h)throw new c("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let m=me(s),b=t.clockToleranceSeconds??60,g=Math.floor(Date.now()/1e3);if(typeof m.exp!="number")throw new c("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(m.exp+b<g)throw new c("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof m.nbf=="number"&&m.nbf-b>g)throw new c("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof m.iss!="string"||m.iss!==t.issuer)throw new c("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!tt(m.aud,t.audience))throw new c("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof m.sub=="string"?m.sub:null,membership:rt(m),claims:m}}var st=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,ot=/^sk_/i;function ye(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(ot.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=st.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1].toLowerCase(),env:t[2].toLowerCase(),projectId:t[3].toLowerCase()}}function R(e,t){try{return e?.getItem(t)??null}catch{return null}}function L(e,t,r){try{r===null?e?.removeItem(t):e?.setItem(t,r);}catch{}}function v(){try{return globalThis.localStorage}catch{return}}function O(){try{return globalThis.sessionStorage}catch{return}}var it="authowl.session-challenge",at=e=>`${it}.${e}`,pt="set-auth-challenge",ge="x-authowl-challenge";var ct=2048,J=e=>e!==null&&e.length<=ct,be=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function dt(e){let t=[];for(let r of e.split(";")){let n=r.trimStart(),s=n.indexOf("=");s<=0||t.push([n.slice(0,s).trimEnd(),n.slice(s+1)]);}return t}function we(e){let t=at(e),r=new Map;function n(){return r.size===0?null:[...r].map(([a,p])=>`${a}=${p}`).join("; ")}function s(){let a=n();L(O(),t,J(a)?a:null);}function o(a){for(let[p,d]of dt(a))be.test(p)&&(d===""?r.delete(p):be.test(d)&&r.set(p,d));}let i=R(O(),t);return J(i)&&o(i),{presentOn(a){let p=n();a.delete(ge),J(p)&&a.set(ge,p);},observe(a){let p=a.get(pt);J(p)&&(o(p),s());},clear(){r.clear(),s();}}}var _e="set-auth-token",Z="x-authowl-session-transport",X="bearer";var ut="authowl.session-token",mt="authowl.cookie-transport",Te="ok",Ae="bearer",lt=e=>`${ut}.${e}`,ft=e=>`${mt}.${e}`;function ht(e){return e===Te?"cookies":e===Ae?"bearer":"unknown"}function yt(e){return e==="cookies"?Te:e==="bearer"?Ae:null}function gt(e){let t=lt(e),r=ft(e),n=we(e),s=null,o=false,i=null,a=ht(R(v(),r)),p=()=>a==="unknown",d=0,l=null,h=false;function m(){let u=R(O(),t);if(u!==null)return o=true,u;let _=R(v(),t);return _!==null?(o=false,_):null}s=m(),s!==null&&p()&&(h=true);function b(){if(!(!h||!l)){h=false;try{l();}catch{}}}function g(){let u=a==="bearer"?s:null,[_,M]=o?[O(),v()]:[v(),O()];L(M,t,null),L(_,t,u);}function T(u){u!==null&&i!==null&&(o=i,i=null),s=u,g(),u!==null&&p()&&(h=true,b());}function f(u){a=u,L(v(),r,yt(u));}function A(){f("unknown"),h=false;}function y(){return s===null&&(s=m()),s}function x(){let u=m();return u!==null&&(s=u),s}function $(u){x()===u&&g();}function N(){d+=1,i=null,o=false,T(null),n.clear(),A();}let D=()=>a!=="cookies";return {hasToken:()=>y()!==null,declareOn(u){if(u.has("authorization"))return false;let _=y();return !_&&!D()?false:(_&&u.set("authorization",`Bearer ${_}`),u.set(Z,X),n.presentOn(u),true)},wantsToken:D,needsProbe:p,observe(u){let _=u.get(_e);_&&T(_),n.observe(u);},dropChallenge:n.clear,measureWith(u){l=u,b();},beginRead(){let u=y(),_=d;return {carriedToken:u!==null,endIfDead(){u!==null&&x()===u&&d===_&&N();},recordCookieVerdict(M){if(d===_&&p()){if(f(M?"cookies":"bearer"),M){T(null);return}$(u);}}}},beginSession({remember:u}){d+=1,i=!u,n.clear(),A();},endSession:N}}var Se=new Map;function Ee(e){let t=Se.get(e);if(t)return t;let r=gt(e);return Se.set(e,r),r}function bt(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function ke(e,t){let r=Ee(e),n=(i,a)=>(t??globalThis.fetch)(i,a);return {fetch:async(i,a)=>{if(a?.credentials==="omit"||!r.wantsToken())return n(i,a);let p=bt(i,a),d=r.declareOn(p),l=await n(i,{...a,headers:p});return d&&r.observe(l.headers),l},probe:n,tokens:r}}function Oe(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=ye(e.publishableKey),r=oe(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:r,decoded:t,projectBaseURL:`${r}/api/projects/${t.projectId}/auth`}}function Q(e){let t=Oe(e),{fetch:r,...n}=ke(t.decoded.projectId,e.fetch);return {...e,...t,fetch:r,session:n}}function Ie(e,t){return !e||!t?false:e.permissions.includes(t)}function wt(e,t){return !e||!t?false:e.teams?.includes(t)??false}function _t(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function xe(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&&!_t(e,r)||n!==void 0&&!e.permissions.includes(n)||s!==void 0&&!wt(e,s))}function St(e,t){let r=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${r}.session_token`}var Tt="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",K={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"}}}},ee={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 At=new Set(["__proto__","constructor","prototype"]),Et=64,kt=5e4;function Pe(e,t,r){let s=K[e].responseSchemas;Object.hasOwn(s,String(t))||H();let o=s[String(t)];if(o===null){r!==null&&H();return}let i={nodes:0};return k(r,I(o),0,i)||H(),r}function k(e,t,r,n){if(n.nodes+=1,r>Et||n.nodes>kt)return false;if(typeof t.$ref=="string"){let o=vt(t.$ref);if(o===null||!k(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>k(e,I(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>k(e,I(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=>Ot(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?It(e,t):typeof e=="number"?Pt(e,t):Array.isArray(e)?Rt(e,t,r,n):C(e)?Lt(e,t,r,n):typeof e=="boolean"}function Ot(e,t){switch(t){case "null":return e===null;case "object":return C(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 It(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!xt(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 xt(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 Pt(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Rt(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=I(t.items);return e.every(o=>k(o,s,r+1,n))}function Lt(e,t,r,n){let s=Object.keys(e);if(s.some(i=>At.has(i))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=C(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(i=>!k(i,I(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,a]of Object.entries(e)){let p=o[i];if(p!==void 0){if(!k(a,I(p),r+1,n))return false;continue}if(t.additionalProperties===false||C(t.additionalProperties)&&!k(a,t.additionalProperties,r+1,n))return false}return true}function vt(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(ee,r)?I(ee[r]):null}function I(e){return C(e)||H(),e}function C(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function H(){throw new TypeError("Admin API response does not match its generated contract.")}var jt=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Nt=1024*1024,Ut=1e4,z=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;}},j=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 Kt(e){Ct();let t=zt(e?.secretKey),r=$t(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=n,o=async(a,p)=>{let d=p??{},l=K[a],h=new URL(Dt(l.path,d).replace(/^\/+/,""),r);Mt(h,d);let m=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Wt(m,d);let b="body"in d?JSON.stringify(d.body):void 0;b!==void 0&&m.set("content-type","application/json");let g;try{g=await q({fetchImpl:s,url:h,init:{method:l.method,headers:m,body:b,signal:p?.signal},timeoutMs:Ut,maxResponseBytes:Nt,allowHttpLoopback:r.protocol==="http:",decode:(y,x)=>Pe(a,x.status,y)});}catch(y){throw y instanceof z?y:y instanceof E?new j(y.kind,y.requestId):new j("network")}let{response:T,requestId:f,data:A}=g;if(!T.ok)throw qt(T,A,f);if(!l.successStatuses.some(y=>y===T.status))throw new j("invalid_response",f);return A},i=Object.assign(Object.create(null),{request:o});for(let a of Object.keys(K))i[a]=p=>o(a,p);return Object.freeze(i)}function Ct(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function zt(e){if(typeof e!="string"||!jt.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function $t(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=W(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 Dt(e,t){let r="path"in t&&B(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 Mt(e,t){if(!(!("query"in t)||!B(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 Wt(e,t){if(!(!("header"in t)||!B(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 qt(e,t,r){let n=r??Re(e.headers.get("x-request-id"),256),s=Re(e.headers.get("retry-after"),128),o=Vt(e.status,n),i=Jt(t)?t:o;return new z({status:e.status,code:i.code,requestId:n,problem:i,retryAfter:s})}function Vt(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 Jt(e){return B(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 B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var Ht=/^v1=([a-f0-9]{64})$/i,Bt=/^whsec_[A-Za-z0-9_-]{1,256}$/,Ft=/^(0|[1-9]\d{0,10})$/;async function Gt(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=Xt(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!Ft.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let i=Zt(e.signatureHeader);if(i.length===0)return false;let a=new TextEncoder().encode(`${e.timestamp}.`),p=new Uint8Array(a.byteLength+s.byteLength);p.set(a),p.set(s,a.byteLength);let d=false;for(let l of t){let h=await crypto.subtle.importKey("raw",new TextEncoder().encode(l),{name:"HMAC",hash:"SHA-256"},false,["sign"]),m=new Uint8Array(await crypto.subtle.sign("HMAC",h,p));for(let b of i)d=er(m,b)||d;}return d}function Yt(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!Bt.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function Zt(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=Ht.exec(n.trim());s&&r.push(Qt(s[1]));}return r}function Xt(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 Qt(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 er(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 Le=["publishableKey","apiUrl","issuer","jwksUri","audience"],tr=new Set([...Le,"clockToleranceSeconds"]);function te(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(a=>!tr.has(a)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(Le.filter(a=>Object.prototype.hasOwnProperty.call(e??{},a))),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 V({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=Q({publishableKey:s,apiUrl:o});return V({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},i.decoded.env==="test")}async function $r(e,t){return U(e,te(t))}async function Dr(e,t,r){let n=te(r);try{let s=await U(e,n);return xe(s.membership,t)}catch{return false}}async function Mr(e,t,r){let n=te(r);try{let s=await U(e,n);return Ie(s.membership,t.permission)}catch{return false}}
2
- exports.ADMIN_API_SPEC_SHA256=Tt;exports.AuthOwlAdminApiError=z;exports.AuthOwlAdminNetworkError=j;exports.SESSION_TRANSPORT_BEARER=X;exports.SESSION_TRANSPORT_HEADER=Z;exports.TokenVerificationError=c;exports.createAdminClient=Kt;exports.has=Dr;exports.hasPermission=Mr;exports.resolveAuthTarget=Oe;exports.resolveConfig=Q;exports.sessionCookieName=St;exports.verifyProjectToken=nt;exports.verifyToken=$r;exports.verifyWebhook=Gt;
1
+ 'use strict';var Ue=new Set(["__proto__","constructor","prototype"]);function P(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function ne(e,t=20,r=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&P(),Ne(e,t,r)}function Ne(e,t=20,r=1e4){return F(e,0,{nodes:0},t,r)}function F(e,t,r,n,o){if(r.nodes+=1,(t>n||r.nodes>o)&&P(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||P(),e;if(Array.isArray(e))return e.map(a=>F(a,t+1,r,n,o));(!e||typeof e!="object")&&P();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&P();let i={};for(let[a,c]of Object.entries(e))Ue.has(a)&&P(),i[a]=F(c,t+1,r,n,o);return i}var G=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function S(e,t){throw new Error(`${e}: ${t}`)}function Ke(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function oe(e,{label:t,allowHttpLoopback:r}){(typeof e!="string"||e.length===0)&&S(t,"required"),e!==e.trim()&&S(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&S(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&S(t,"path must be unencoded");let n;try{n=new URL(e);}catch{S(t,"absolute URL required");}return (n.username||n.password)&&S(t,"credentials forbidden"),n.protocol!=="https:"&&n.protocol!=="http:"&&S(t,"HTTPS required"),n.protocol==="http:"&&(!r||!G.test(e))&&S(t,"HTTPS required except exact loopback"),n}function W(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&&G.test(n)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return r}function se(e,t,r){let n=Ke(e);(n.includes("//")||n.split("/").some(o=>o==="."||o==="..")||n!==""&&n!==t.pathname)&&S(r,"path traversal or duplicate separator");}function ie(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&S("apiUrl","origin required");let r;try{r=new URL(e);}catch{S("apiUrl","origin required");}return r.protocol==="http:"&&(!t.allowHttpLoopback||!G.test(e))&&S("apiUrl","HTTPS required except exact loopback"),r.origin}function ae(e,t,r={allowHttpLoopback:false}){let n=oe(e,{label:"issuer",allowHttpLoopback:r.allowHttpLoopback}),o=oe(t,{label:"jwksUri",allowHttpLoopback:r.allowHttpLoopback});return se(e,n,"issuer"),se(t,o,"jwksUri"),n.pathname!=="/"&&n.pathname.endsWith("/")&&S("issuer","trailing slash forbidden"),{issuer:n.toString().replace(/\/$/,""),jwksUri:o.toString()}}var Ce=1e4,ze=1024*1024,E=class extends Error{kind;requestId;constructor(t,r){super(He(t)),this.name="TransportError",this.kind=t,this.requestId=r;}},de=new WeakSet;function w(e,t){let r=new E(e,t);return de.add(r),r}async function q({fetchImpl:e,url:t,init:r={},timeoutMs:n=Ce,maxResponseBytes:o=ze,allowHttpLoopback:s=false,decode:i}){pe(n,"timeoutMs"),pe(o,"maxResponseBytes");let a=W(t,{allowHttpLoopback:s}),c=r.signal,d=new AbortController,l=null,h,m=new Promise(f=>{h=f;}),b=f=>{l===null&&(l=f,h({type:"abort",kind:f}),d.abort());},g=()=>b("aborted");c?.addEventListener("abort",g,{once:true});let T=setTimeout(()=>b("timeout"),n);c?.aborted&&g();try{if(l!==null)throw w(l);let f;try{f=await Promise.race([e(a.toString(),{...r,redirect:"error",signal:d.signal}).then(M=>({type:"response",response:M})),m]);}catch{throw w(l??"network")}if(f.type==="abort")throw w(f.kind);if(!$e(f.response))throw w("invalid_response");let A=f.response,y=Je(A.headers),x=await Me(A,o,m,()=>l,y),$=qe(A,x,y),U;try{U=A.ok&&i?i($,Object.freeze({status:A.status})):$;}catch{throw w("invalid_response",y)}return {response:A,data:U,...y===void 0?{}:{requestId:y}}}catch(f){throw f instanceof E&&de.has(f)?f:w(l??"network")}finally{clearTimeout(T),c?.removeEventListener("abort",g);}}function $e(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 Me(e,t,r,n,o){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw ce(e.body),w("invalid_response",o);if(Number(s)>t)throw ce(e.body),w("response_too_large",o)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw w("network",o)}let a=[],c=0,d=null;try{for(;;){let m;try{m=await Promise.race([i.read(),r]);}catch{d=w(n()??"network",o);break}if(De(m)){d=w(m.kind,o);break}let{done:b,value:g}=m;if(b)break;if(g.byteLength!==0){if(c+=g.byteLength,c>t){d=w("response_too_large",o);break}a.push(g);}}}finally{d&&We(i);try{i.releaseLock();}catch{}}if(d)throw d;let l=new Uint8Array(c),h=0;for(let m of a)l.set(m,h),h+=m.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw w("invalid_response",o)}}function De(e){return "type"in e&&e.type==="abort"}function ce(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function We(e){try{e.cancel().catch(()=>{});}catch{}}function qe(e,t,r){if(e.status===204||e.status===205)return null;let n=Ve(e.headers.get("content-type"));if(!e.ok&&(!n||t.length===0))return null;if(!n||t.length===0)throw w("invalid_response",r);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw w("invalid_response",r)}}function Ve(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function Je(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function pe(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function He(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 p=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Fe=300*1e3,Ge=5e3,Ye=64*1024,Ze=64,Xe=60*1e3,ue=new Map,me=new Map;function Y(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"),o=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)o[s]=n.charCodeAt(s);return o}function le(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new p("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(Y(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new p("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof p?t:new p("Malformed JWT segment.","TOKEN_MALFORMED")}}function ye(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function fe(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&Y(e).byteLength===32}function Qe(e){if(!ye(e))throw new p("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 p("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)||!fe(e.x)||!fe(e.y))throw new p("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 et(e){if(!ye(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new p("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>Ze)throw new p("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(Qe),r=new Set;for(let n of t){if(r.has(n.kid))throw new p("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function he(e,t){let r=ue.get(e);if(!t&&r&&Date.now()-r.fetchedAt<Fe)return r.keys;try{let n=await q({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Ge,maxResponseBytes:Ye,allowHttpLoopback:new URL(e).protocol==="http:",decode:s=>ne(s)});if(!n.response.ok)throw new p(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let o=et(n.data);return ue.set(e,{keys:o,fetchedAt:Date.now()}),o}catch(n){if(n instanceof p)throw n;if(n instanceof E)switch(n.kind){case "timeout":throw new p("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new p("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new p("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new p("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function tt(e,t){let r=o=>t?o.find(s=>s.kid===t):o[0],n=r(await he(e,false));if(!n){let o=me.get(e)??0;Date.now()-o>=Xe&&(me.set(e,Date.now()),n=r(await he(e,true)));}if(!n)throw new p("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function rt(e){let t=globalThis.crypto?.subtle;if(!t)throw new p("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 nt(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function ot(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:"",o=Array.isArray(r.permissions)?r.permissions.filter(a=>typeof a=="string"):[],s=Array.isArray(r.roles)?r.roles.filter(a=>typeof a=="string"):void 0,i=Array.isArray(r.teams)?r.teams.filter(a=>typeof a=="string"):void 0;return n===""&&o.length===0&&!s?.length&&!i?.length?null:{role:n,...s===void 0?{}:{roles:s},permissions:o,...i===void 0?{}:{teams:i}}}async function st(e,t){return N(e,V(t))}function V(e,t=false){if(!e||typeof e!="object")throw new p("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=ae(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new p("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 p("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 p("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function N(e,t){if(typeof e!="string"||e.length===0)throw new p("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new p("Malformed JWT.","TOKEN_MALFORMED");let[n,o,s]=r,i=le(n);if(i.alg!=="ES256")throw new p("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let a=await tt(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),c;try{c=await rt(a);}catch(T){throw T instanceof p?T:new p("JWKS key could not be imported.","JWKS_KEY_INVALID")}let d;try{if(!/^[A-Za-z0-9_-]{86}$/.test(s))throw new Error("invalid signature encoding");if(d=Y(s),d.byteLength!==64)throw new Error("invalid signature length")}catch{throw new p("Malformed JWT signature.","TOKEN_MALFORMED")}let l=new TextEncoder().encode(`${n}.${o}`),h;try{h=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},c,d,l);}catch{throw new p("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!h)throw new p("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let m=le(o),b=t.clockToleranceSeconds??60,g=Math.floor(Date.now()/1e3);if(typeof m.exp!="number")throw new p("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(m.exp+b<g)throw new p("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof m.nbf=="number"&&m.nbf-b>g)throw new p("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof m.iss!="string"||m.iss!==t.issuer)throw new p("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!nt(m.aud,t.audience))throw new p("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof m.sub=="string"?m.sub:null,membership:ot(m),claims:m}}var it=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,at=/^sk_/i;function ge(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(at.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=it.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1].toLowerCase(),env:t[2].toLowerCase(),projectId:t[3].toLowerCase()}}function R(e,t){try{return e?.getItem(t)??null}catch{return null}}function L(e,t,r){try{r===null?e?.removeItem(t):e?.setItem(t,r);}catch{}}function v(){try{return globalThis.localStorage}catch{return}}function O(){try{return globalThis.sessionStorage}catch{return}}var ct="authowl.session-challenge",pt=e=>`${ct}.${e}`,dt="set-auth-challenge",be="x-authowl-challenge";var ut=2048,J=e=>e!==null&&e.length<=ut,we=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function mt(e){let t=[];for(let r of e.split(";")){let n=r.trimStart(),o=n.indexOf("=");o<=0||t.push([n.slice(0,o).trimEnd(),n.slice(o+1)]);}return t}function _e(e){let t=pt(e),r=new Map;function n(){return r.size===0?null:[...r].map(([a,c])=>`${a}=${c}`).join("; ")}function o(){let a=n();L(O(),t,J(a)?a:null);}function s(a){for(let[c,d]of mt(a))we.test(c)&&(d===""?r.delete(c):we.test(d)&&r.set(c,d));}let i=R(O(),t);return J(i)&&s(i),{presentOn(a){let c=n();a.delete(be),J(c)&&a.set(be,c);},observe(a){let c=a.get(dt);J(c)&&(s(c),o());},clear(){r.clear(),o();}}}var Se="set-auth-token",Z="x-authowl-session-transport",X="bearer";var lt="authowl.session-token",ft="authowl.cookie-transport",Ae="ok",Ee="bearer",ht=e=>`${lt}.${e}`,yt=e=>`${ft}.${e}`;function gt(e){return e===Ae?"cookies":e===Ee?"bearer":"unknown"}function bt(e){return e==="cookies"?Ae:e==="bearer"?Ee:null}function wt(e){let t=ht(e),r=yt(e),n=_e(e),o=null,s=false,i=null,a=gt(R(v(),r)),c=()=>a==="unknown",d=0,l=null,h=false;function m(){let u=R(O(),t);if(u!==null)return s=true,u;let _=R(v(),t);return _!==null?(s=false,_):null}o=m(),o!==null&&c()&&(h=true);function b(){if(!(!h||!l)){h=false;try{l();}catch{}}}function g(){let u=a==="bearer"?o:null,[_,D]=s?[O(),v()]:[v(),O()];L(D,t,null),L(_,t,u);}function T(u){u!==null&&i!==null&&(s=i,i=null),o=u,g(),u!==null&&c()&&(h=true,b());}function f(u){a=u,L(v(),r,bt(u));}function A(){f("unknown"),h=false;}function y(){return o===null&&(o=m()),o}function x(){let u=m();return u!==null&&(o=u),o}function $(u){x()===u&&g();}function U(){d+=1,i=null,s=false,T(null),n.clear(),A();}let M=()=>a!=="cookies";return {hasToken:()=>y()!==null,declareOn(u){if(u.has("authorization"))return false;let _=y();return !_&&!M()?false:(_&&u.set("authorization",`Bearer ${_}`),u.set(Z,X),n.presentOn(u),true)},wantsToken:M,needsProbe:c,observe(u){let _=u.get(Se);_&&T(_),n.observe(u);},dropChallenge:n.clear,measureWith(u){l=u,b();},beginRead(){let u=y(),_=d;return {carriedToken:u!==null,endIfDead(){u!==null&&x()===u&&d===_&&U();},recordCookieVerdict(D){if(d===_&&c()){if(f(D?"cookies":"bearer"),D){T(null);return}$(u);}}}},beginSession({remember:u}){d+=1,i=!u,n.clear(),A();},endSession:U}}var Te=new Map;function ke(e){let t=Te.get(e);if(t)return t;let r=wt(e);return Te.set(e,r),r}function _t(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function Oe(e,t){let r=ke(e),n=(i,a)=>(t??globalThis.fetch)(i,a);return {fetch:async(i,a)=>{if(a?.credentials==="omit"||!r.wantsToken())return n(i,a);let c=_t(i,a),d=r.declareOn(c),l=await n(i,{...a,headers:c});return d&&r.observe(l.headers),l},probe:n,tokens:r}}function Ie(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=ge(e.publishableKey),r=ie(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:r,decoded:t,projectBaseURL:`${r}/api/projects/${t.projectId}/auth`}}function Q(e){let t=Ie(e),{fetch:r,...n}=Oe(t.decoded.projectId,e.fetch);return {...e,...t,fetch:r,session:n}}function xe(e,t){return !e||!t?false:e.permissions.includes(t)}function St(e,t){return !e||!t?false:e.teams?.includes(t)??false}function Tt(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function Pe(e,t){if(!e)return false;let{role:r,permission:n,teamId:o}=t;return !(r===void 0&&n===void 0&&o===void 0||r!==void 0&&!Tt(e,r)||n!==void 0&&!e.permissions.includes(n)||o!==void 0&&!St(e,o))}function At(e,t){let r=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${r}.session_token`}var Et="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",K={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"}}}},ee={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 kt=new Set(["__proto__","constructor","prototype"]),Ot=64,It=5e4;function Re(e,t,r){let o=K[e].responseSchemas;Object.hasOwn(o,String(t))||H();let s=o[String(t)];if(s===null){r!==null&&H();return}let i={nodes:0};return k(r,I(s),0,i)||H(),r}function k(e,t,r,n){if(n.nodes+=1,r>Ot||n.nodes>It)return false;if(typeof t.$ref=="string"){let s=Ut(t.$ref);if(s===null||!k(e,s,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(s=>k(e,I(s),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(s=>k(e,I(s),r+1,n)).length!==1||Array.isArray(t.enum)&&!t.enum.some(s=>Object.is(s,e))||t.const!==void 0&&!Object.is(t.const,e))return false;let o=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!o.some(s=>xt(e,s))?false:e===null?t.type===void 0||o.includes("null"):typeof e=="string"?Pt(e,t):typeof e=="number"?Lt(e,t):Array.isArray(e)?vt(e,t,r,n):C(e)?jt(e,t,r,n):typeof e=="boolean"}function xt(e,t){switch(t){case "null":return e===null;case "object":return C(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 Pt(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!Rt(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 Rt(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 Lt(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function vt(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(s=>JSON.stringify(s))).size!==e.length)return false;if(t.items===void 0)return true;let o=I(t.items);return e.every(s=>k(s,o,r+1,n))}function jt(e,t,r,n){let o=Object.keys(e);if(o.some(i=>kt.has(i))||typeof t.minProperties=="number"&&o.length<t.minProperties||typeof t.maxProperties=="number"&&o.length>t.maxProperties)return false;let s=C(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&o.some(i=>!k(i,I(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,a]of Object.entries(e)){let c=s[i];if(c!==void 0){if(!k(a,I(c),r+1,n))return false;continue}if(t.additionalProperties===false||C(t.additionalProperties)&&!k(a,t.additionalProperties,r+1,n))return false}return true}function Ut(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(ee,r)?I(ee[r]):null}function I(e){return C(e)||H(),e}function C(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function H(){throw new TypeError("Admin API response does not match its generated contract.")}var Nt=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Kt=1024*1024,Ct=1e4,z=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;}},j=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 zt(e){$t();let t=Mt(e?.secretKey),r=Dt(e?.apiUrl),n=e?.fetch??globalThis.fetch;if(typeof n!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let o=n,s=async(a,c)=>{let d=c??{},l=K[a],h=new URL(Wt(l.path,d).replace(/^\/+/,""),r);qt(h,d);let m=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Vt(m,d);let b="body"in d?JSON.stringify(d.body):void 0;b!==void 0&&m.set("content-type","application/json");let g;try{g=await q({fetchImpl:o,url:h,init:{method:l.method,headers:m,body:b,signal:c?.signal},timeoutMs:Ct,maxResponseBytes:Kt,allowHttpLoopback:r.protocol==="http:",decode:(y,x)=>Re(a,x.status,y)});}catch(y){throw y instanceof z?y:y instanceof E?new j(y.kind,y.requestId):new j("network")}let{response:T,requestId:f,data:A}=g;if(!T.ok)throw Jt(T,A,f);if(!l.successStatuses.some(y=>y===T.status))throw new j("invalid_response",f);return A},i=Object.assign(Object.create(null),{request:s});for(let a of Object.keys(K))i[a]=c=>s(a,c);return Object.freeze(i)}function $t(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function Mt(e){if(typeof e!="string"||!Nt.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function Dt(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=W(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 Wt(e,t){let r="path"in t&&B(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(n,o)=>{let s=r[o];if(typeof s!="string"&&typeof s!="number")throw new TypeError(`Missing Admin API path parameter: ${o}.`);return encodeURIComponent(String(s))})}function qt(e,t){if(!(!("query"in t)||!B(t.query)))for(let[r,n]of Object.entries(t.query)){if(n==null)continue;let o=Array.isArray(n)?n:[n];for(let s of o)e.searchParams.append(r,String(s));}}function Vt(e,t){if(!(!("header"in t)||!B(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 Jt(e,t,r){let n=r??Le(e.headers.get("x-request-id"),256),o=Le(e.headers.get("retry-after"),128),s=Ht(e.status,n),i=Bt(t)?t:s;return new z({status:e.status,code:i.code,requestId:n,problem:i,retryAfter:o})}function Ht(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 Bt(e){return B(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 B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Le(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var Ft=/^v1=([a-f0-9]{64})$/i,Gt=/^whsec_[A-Za-z0-9_-]{1,256}$/,Yt=/^(0|[1-9]\d{0,10})$/;async function Zt(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=Xt(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 o=er(e.rawBody);if(o.byteLength>1048576||typeof e.timestamp!="string"||!Yt.test(e.timestamp))return false;let s=Number(e.timestamp);if(!Number.isSafeInteger(s)||Math.abs(n-s)>r)return false;let i=Qt(e.signatureHeader);if(i.length===0)return false;let a=new TextEncoder().encode(`${e.timestamp}.`),c=new Uint8Array(a.byteLength+o.byteLength);c.set(a),c.set(o,a.byteLength);let d=false;for(let l of t){let h=await crypto.subtle.importKey("raw",new TextEncoder().encode(l),{name:"HMAC",hash:"SHA-256"},false,["sign"]),m=new Uint8Array(await crypto.subtle.sign("HMAC",h,c));for(let b of i)d=rr(m,b)||d;}return d}function Xt(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!Gt.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function Qt(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 o=Ft.exec(n.trim());o&&r.push(tr(o[1]));}return r}function er(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 tr(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 rr(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 nr="/.well-known/oauth-protected-resource";function te(e,t){let r;try{r=new URL(e);}catch{throw new TypeError(`${t} must be an absolute URL.`)}let n=r.hostname==="localhost"||r.hostname==="127.0.0.1"||r.hostname==="[::1]";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n))throw new TypeError(`${t} must use HTTPS, except on a loopback host.`);if(r.hash)throw new TypeError(`${t} must not contain a fragment.`);if(r.username||r.password)throw new TypeError(`${t} must not contain embedded credentials.`);return r}function ve(e){let t=te(e,"resource"),r=t.pathname==="/"?"":t.pathname.replace(/\/+$/,"");return `${t.origin}${nr}${r}${t.search}`}function or(e){if(te(e.resource,"resource"),e.authorizationServers.length===0)throw new Error("An MCP server must name at least one authorization server, or no client can authenticate to it.");for(let t of e.authorizationServers)te(t,"authorization server");return Object.freeze({resource:e.resource,authorization_servers:Object.freeze([...e.authorizationServers]),bearer_methods_supported:Object.freeze(["header"]),...e.scopesSupported?.length?{scopes_supported:Object.freeze([...e.scopesSupported])}:{},...e.resourceName?{resource_name:e.resourceName}:{}})}function sr(e){let t=[`resource_metadata="${ve(e.resource)}"`];return e.error&&t.push(`error="${e.error}"`),e.error&&e.errorDescription&&t.push(`error_description="${e.errorDescription.replace(/["\\\r\n]/g,"")}"`),`Bearer ${t.join(", ")}`}var je=["publishableKey","apiUrl","issuer","jwksUri","audience"],ir=new Set([...je,"clockToleranceSeconds"]);function re(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(a=>!ir.has(a)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(je.filter(a=>Object.prototype.hasOwnProperty.call(e??{},a))),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 V({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let o,s;if(r){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=Q({publishableKey:o,apiUrl:s});return V({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},i.decoded.env==="test")}async function Jr(e,t){return N(e,re(t))}async function Hr(e,t,r){let n=re(r);try{let o=await N(e,n);return Pe(o.membership,t)}catch{return false}}async function Br(e,t,r){let n=re(r);try{let o=await N(e,n);return xe(o.membership,t.permission)}catch{return false}}
2
+ exports.ADMIN_API_SPEC_SHA256=Et;exports.AuthOwlAdminApiError=z;exports.AuthOwlAdminNetworkError=j;exports.SESSION_TRANSPORT_BEARER=X;exports.SESSION_TRANSPORT_HEADER=Z;exports.TokenVerificationError=p;exports.createAdminClient=zt;exports.has=Hr;exports.hasPermission=Br;exports.mcpProtectedResourceMetadata=or;exports.mcpProtectedResourceMetadataUrl=ve;exports.mcpUnauthorizedChallenge=sr;exports.resolveAuthTarget=Ie;exports.resolveConfig=Q;exports.sessionCookieName=At;exports.verifyProjectToken=st;exports.verifyToken=Jr;exports.verifyWebhook=Zt;
package/dist/server.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-B05mzhtA.cjs';
2
- export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, r as resolveAuthTarget, h as resolveConfig, s as sessionCookieName } from './organization-membership-B05mzhtA.cjs';
1
+ import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-DSqmZLkN.cjs';
2
+ export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, h as resolveAuthTarget, r as resolveConfig } from './organization-membership-DSqmZLkN.cjs';
3
+ export { s as sessionCookieName } from './cookie-BqcfagTw.cjs';
3
4
  export { a as SESSION_TRANSPORT_BEARER, b as SESSION_TRANSPORT_HEADER } from './session-transport-contract-HDPYRum8.cjs';
4
5
 
5
6
  /**
@@ -3544,6 +3545,71 @@ type VerifyWebhookInput = {
3544
3545
  */
3545
3546
  declare function verifyWebhook(input: VerifyWebhookInput): Promise<boolean>;
3546
3547
 
3548
+ /**
3549
+ * What an MCP server owes a client, so it can be authenticated by AuthOwl.
3550
+ *
3551
+ * An MCP server is a RESOURCE server, not an authorization server. AuthOwl
3552
+ * issues the tokens; these three things are the resource server's own side of
3553
+ * the protocol, and without them an agent cannot begin - it has no way to find
3554
+ * out who issues tokens for you.
3555
+ *
3556
+ * All pure. Nothing here talks to AuthOwl or reads a token; verification is
3557
+ * `verifyProjectToken`, which already checks the audience.
3558
+ */
3559
+ type McpProtectedResourceMetadata = Readonly<{
3560
+ resource: string;
3561
+ authorization_servers: readonly string[];
3562
+ scopes_supported?: readonly string[];
3563
+ resource_name?: string;
3564
+ bearer_methods_supported?: readonly string[];
3565
+ }>;
3566
+ /**
3567
+ * Where a client will look for your metadata.
3568
+ *
3569
+ * RFC 9728 §3 inserts the well-known suffix between the host and the resource's
3570
+ * path - the same construction RFC 8414 uses for an authorization server, and
3571
+ * NOT the OpenID-style append. A resource at `https://mcp.example.com/mcp`
3572
+ * publishes at `https://mcp.example.com/.well-known/oauth-protected-resource/mcp`.
3573
+ *
3574
+ * Getting this wrong is silent: the document exists, the client looks elsewhere,
3575
+ * and the agent reports only that it could not authenticate.
3576
+ */
3577
+ declare function mcpProtectedResourceMetadataUrl(resource: string): string;
3578
+ /**
3579
+ * The metadata document to serve at that URL.
3580
+ *
3581
+ * `resource` is the only field RFC 9728 requires. `authorization_servers` is
3582
+ * optional there and MANDATORY under MCP - a client uses it to find who issues
3583
+ * tokens - so it is required here rather than optional, because an MCP server
3584
+ * that omits it is one no agent can use.
3585
+ */
3586
+ declare function mcpProtectedResourceMetadata(input: {
3587
+ /** Your canonical resource URI - the same string clients send as `resource`. */
3588
+ resource: string;
3589
+ /** Your AuthOwl issuer: `<authHost>/api/projects/<projectId>/auth`. */
3590
+ authorizationServers: readonly string[];
3591
+ scopesSupported?: readonly string[];
3592
+ resourceName?: string;
3593
+ }): McpProtectedResourceMetadata;
3594
+ /**
3595
+ * The `WWW-Authenticate` value for a 401 from your MCP server.
3596
+ *
3597
+ * This header is where an agent's whole discovery starts: it names the metadata
3598
+ * URL, which names the authorization server, which is how the client learns
3599
+ * where to get a token. A 401 without it leaves the agent with nowhere to go,
3600
+ * and MCP requires it for that reason.
3601
+ *
3602
+ * Pass `error` when a token WAS presented and rejected - `invalid_token` for one
3603
+ * that is expired, malformed, or issued for another resource. Omit it for a
3604
+ * request that carried no token at all, which is not an error so much as a
3605
+ * conversation starting.
3606
+ */
3607
+ declare function mcpUnauthorizedChallenge(input: {
3608
+ resource: string;
3609
+ error?: 'invalid_token' | 'insufficient_scope';
3610
+ errorDescription?: string;
3611
+ }): string;
3612
+
3547
3613
  /** Server-only AuthOwl configuration, cookies, and generated Admin API client. */
3548
3614
 
3549
3615
  /**
@@ -3597,4 +3663,4 @@ declare function hasPermission(token: string, params: {
3597
3663
  permission: string;
3598
3664
  }, config?: VerifyTokenConfig): Promise<boolean>;
3599
3665
 
3600
- export { ADMIN_API_SPEC_SHA256, type components as AdminApiComponents, type operations as AdminApiOperations, type paths as AdminApiPaths, type AdminApiProblem, type AdminClient, type AdminClientConfig, type AdminOperationId, type AdminOperationInput, type AdminOperationResult, AuthOwlAdminApiError, AuthOwlAdminNetworkError, HasParams, OrganizationMembership, TokenVerificationError, type TokenVerificationErrorCode, type VerifiedProjectToken, type VerifyTokenConfig, type VerifyWebhookInput, createAdminClient, has, hasPermission, verifyProjectToken, verifyToken, verifyWebhook };
3666
+ export { ADMIN_API_SPEC_SHA256, type components as AdminApiComponents, type operations as AdminApiOperations, type paths as AdminApiPaths, type AdminApiProblem, type AdminClient, type AdminClientConfig, type AdminOperationId, type AdminOperationInput, type AdminOperationResult, AuthOwlAdminApiError, AuthOwlAdminNetworkError, HasParams, type McpProtectedResourceMetadata, OrganizationMembership, TokenVerificationError, type TokenVerificationErrorCode, type VerifiedProjectToken, type VerifyTokenConfig, type VerifyWebhookInput, createAdminClient, has, hasPermission, mcpProtectedResourceMetadata, mcpProtectedResourceMetadataUrl, mcpUnauthorizedChallenge, verifyProjectToken, verifyToken, verifyWebhook };
package/dist/server.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-B05mzhtA.js';
2
- export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, r as resolveAuthTarget, h as resolveConfig, s as sessionCookieName } from './organization-membership-B05mzhtA.js';
1
+ import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-DSqmZLkN.js';
2
+ export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, h as resolveAuthTarget, r as resolveConfig } from './organization-membership-DSqmZLkN.js';
3
+ export { s as sessionCookieName } from './cookie-BqcfagTw.js';
3
4
  export { a as SESSION_TRANSPORT_BEARER, b as SESSION_TRANSPORT_HEADER } from './session-transport-contract-HDPYRum8.js';
4
5
 
5
6
  /**
@@ -3544,6 +3545,71 @@ type VerifyWebhookInput = {
3544
3545
  */
3545
3546
  declare function verifyWebhook(input: VerifyWebhookInput): Promise<boolean>;
3546
3547
 
3548
+ /**
3549
+ * What an MCP server owes a client, so it can be authenticated by AuthOwl.
3550
+ *
3551
+ * An MCP server is a RESOURCE server, not an authorization server. AuthOwl
3552
+ * issues the tokens; these three things are the resource server's own side of
3553
+ * the protocol, and without them an agent cannot begin - it has no way to find
3554
+ * out who issues tokens for you.
3555
+ *
3556
+ * All pure. Nothing here talks to AuthOwl or reads a token; verification is
3557
+ * `verifyProjectToken`, which already checks the audience.
3558
+ */
3559
+ type McpProtectedResourceMetadata = Readonly<{
3560
+ resource: string;
3561
+ authorization_servers: readonly string[];
3562
+ scopes_supported?: readonly string[];
3563
+ resource_name?: string;
3564
+ bearer_methods_supported?: readonly string[];
3565
+ }>;
3566
+ /**
3567
+ * Where a client will look for your metadata.
3568
+ *
3569
+ * RFC 9728 §3 inserts the well-known suffix between the host and the resource's
3570
+ * path - the same construction RFC 8414 uses for an authorization server, and
3571
+ * NOT the OpenID-style append. A resource at `https://mcp.example.com/mcp`
3572
+ * publishes at `https://mcp.example.com/.well-known/oauth-protected-resource/mcp`.
3573
+ *
3574
+ * Getting this wrong is silent: the document exists, the client looks elsewhere,
3575
+ * and the agent reports only that it could not authenticate.
3576
+ */
3577
+ declare function mcpProtectedResourceMetadataUrl(resource: string): string;
3578
+ /**
3579
+ * The metadata document to serve at that URL.
3580
+ *
3581
+ * `resource` is the only field RFC 9728 requires. `authorization_servers` is
3582
+ * optional there and MANDATORY under MCP - a client uses it to find who issues
3583
+ * tokens - so it is required here rather than optional, because an MCP server
3584
+ * that omits it is one no agent can use.
3585
+ */
3586
+ declare function mcpProtectedResourceMetadata(input: {
3587
+ /** Your canonical resource URI - the same string clients send as `resource`. */
3588
+ resource: string;
3589
+ /** Your AuthOwl issuer: `<authHost>/api/projects/<projectId>/auth`. */
3590
+ authorizationServers: readonly string[];
3591
+ scopesSupported?: readonly string[];
3592
+ resourceName?: string;
3593
+ }): McpProtectedResourceMetadata;
3594
+ /**
3595
+ * The `WWW-Authenticate` value for a 401 from your MCP server.
3596
+ *
3597
+ * This header is where an agent's whole discovery starts: it names the metadata
3598
+ * URL, which names the authorization server, which is how the client learns
3599
+ * where to get a token. A 401 without it leaves the agent with nowhere to go,
3600
+ * and MCP requires it for that reason.
3601
+ *
3602
+ * Pass `error` when a token WAS presented and rejected - `invalid_token` for one
3603
+ * that is expired, malformed, or issued for another resource. Omit it for a
3604
+ * request that carried no token at all, which is not an error so much as a
3605
+ * conversation starting.
3606
+ */
3607
+ declare function mcpUnauthorizedChallenge(input: {
3608
+ resource: string;
3609
+ error?: 'invalid_token' | 'insufficient_scope';
3610
+ errorDescription?: string;
3611
+ }): string;
3612
+
3547
3613
  /** Server-only AuthOwl configuration, cookies, and generated Admin API client. */
3548
3614
 
3549
3615
  /**
@@ -3597,4 +3663,4 @@ declare function hasPermission(token: string, params: {
3597
3663
  permission: string;
3598
3664
  }, config?: VerifyTokenConfig): Promise<boolean>;
3599
3665
 
3600
- export { ADMIN_API_SPEC_SHA256, type components as AdminApiComponents, type operations as AdminApiOperations, type paths as AdminApiPaths, type AdminApiProblem, type AdminClient, type AdminClientConfig, type AdminOperationId, type AdminOperationInput, type AdminOperationResult, AuthOwlAdminApiError, AuthOwlAdminNetworkError, HasParams, OrganizationMembership, TokenVerificationError, type TokenVerificationErrorCode, type VerifiedProjectToken, type VerifyTokenConfig, type VerifyWebhookInput, createAdminClient, has, hasPermission, verifyProjectToken, verifyToken, verifyWebhook };
3666
+ export { ADMIN_API_SPEC_SHA256, type components as AdminApiComponents, type operations as AdminApiOperations, type paths as AdminApiPaths, type AdminApiProblem, type AdminClient, type AdminClientConfig, type AdminOperationId, type AdminOperationInput, type AdminOperationResult, AuthOwlAdminApiError, AuthOwlAdminNetworkError, HasParams, type McpProtectedResourceMetadata, OrganizationMembership, TokenVerificationError, type TokenVerificationErrorCode, type VerifiedProjectToken, type VerifyTokenConfig, type VerifyWebhookInput, createAdminClient, has, hasPermission, mcpProtectedResourceMetadata, mcpProtectedResourceMetadataUrl, mcpUnauthorizedChallenge, verifyProjectToken, verifyToken, verifyWebhook };