@authowl/core 0.22.0 → 0.23.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 ht=Object.defineProperty;var yt=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var gt=(e,t)=>{for(var r in t)ht(e,r,{get:t[r],enumerable:true});};var tt={};gt(tt,{abandonSession:()=>Fe,bindingNonce:()=>Qe,boundedSessionFetch:()=>re,clearSessionProofKeyMemoryForTests:()=>lr,cookieCapability:()=>He,createSessionProof:()=>et,createStoredSessionProof:()=>gr,prepareSenderConstrainedSession:()=>dr,sessionProofKey:()=>ne});async function re(e,t,r,n){let o=new AbortController,s,i=new Promise((a,p)=>{s=setTimeout(()=>{o.abort(),p(new Error("AuthOwl session transport request timed out."));},n);});try{return await Promise.race([e(t,{...r,signal:o.signal}),i])}finally{clearTimeout(s);}}async function He(e,t,r){let n=await re(e,t,{method:"POST",credentials:"include",headers:r},1e4);if(n.status===404||n.status===405)return "legacy";if(n.status!==204)throw new Error("AuthOwl cookie capability check failed.");let o=await re(e,t,{method:"GET",credentials:"include",headers:r},1e4);if(o.status===404||o.status===405)return "legacy";if(o.status!==200)throw new Error("AuthOwl cookie capability check failed.");let s=await o.text();if(new TextEncoder().encode(s).byteLength>128)throw new Error("AuthOwl cookie capability response is invalid.");let i;try{i=JSON.parse(s);}catch{throw new Error("AuthOwl cookie capability response is invalid.")}if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length!==1||typeof i.cookieSupported!="boolean")throw new Error("AuthOwl cookie capability response is invalid.");return i.cookieSupported}async function Fe(e,t,r,n){let o=new Headers(r);o.set("authorization",n),o.set("x-authowl-session-transport","bearer");try{await re(e,t,{method:"POST",credentials:"include",headers:o},2e3);}catch{}}async function dr(e){let{tokens:t}=e;if(t.beginSession(e.start),!e.clientOrigin)return {binding:null,cookieOnly:false};let r=null;if(t.hasToken()){let s=t.bindingThumbprint();if(s)try{let i=await ne(e.clientOrigin);if(i.thumbprint!==s)throw new Error("Session proof key changed.");r=i;}catch{let i=new Headers;t.declareOn(i);let a=i.get("authorization");a&&await Fe(e.fetcher,`${e.projectBaseURL}/session/abandon`,e.headers,a),t.endSession(),t.beginSession(e.start);}}let n;try{n=await He(e.fetcher,`${e.projectBaseURL}/session/cookie-capability`,e.headers);}catch{return t.useCookieTransport(),{binding:null,cookieOnly:false}}if(n==="legacy")return {binding:null,cookieOnly:false};if(n)return t.hasToken()?{binding:null,cookieOnly:true}:(t.useCookieTransport(),{binding:null,cookieOnly:false});let o=r??await ne(e.clientOrigin);return t.useBoundBearerTransport(o.thumbprint,o.persistent),{binding:{key:o,nonce:Qe()},cookieOnly:false}}function D(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function te(e){return new TextEncoder().encode(e)}async function Ge(e){return D(new Uint8Array(await crypto.subtle.digest("SHA-256",te(e))))}function Ye(e){return e.kty==="EC"&&e.crv==="P-256"&&typeof e.x=="string"&&e.x.length>0&&typeof e.y=="string"&&e.y.length>0&&e.d===void 0}async function Ze(e){return Ge(JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y}))}function ur(e){if(!e||typeof e!="object")return false;let t=e,r=t.algorithm;return t.type==="private"&&t.extractable===false&&t.usages.length===1&&t.usages[0]==="sign"&&r.name==="ECDSA"&&r.namedCurve==="P-256"}function lr(){ee.clear();}async function mr(e){if(!e||typeof e!="object")return null;let t=e;if(!ur(t.privateKey)||!t.publicJwk||!Ye(t.publicJwk))return null;let r=await Ze(t.publicJwk);return t.thumbprint!==r?null:{privateKey:t.privateKey,publicJwk:t.publicJwk,thumbprint:r,persistent:true}}function Xe(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise(e=>{let t;try{t=indexedDB.open(pr,1);}catch{e(null);return}t.onupgradeneeded=()=>{t.result.objectStoreNames.contains(M)||t.result.createObjectStore(M,{keyPath:"origin"});},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);})}async function We(e){let t=await Xe();if(!t)return null;try{let r=await new Promise(n=>{let o=t.transaction(M,"readonly").objectStore(M).get(e);o.onsuccess=()=>n(o.result),o.onerror=()=>n(null);});return await mr(r)}finally{t.close();}}async function fr(e,t){let r=await Xe();if(!r)return "unavailable";try{return await new Promise(n=>{let o;try{o=r.transaction(M,"readwrite"),o.objectStore(M).add({origin:e,privateKey:t.privateKey,publicJwk:t.publicJwk,thumbprint:t.thumbprint});}catch{n("unavailable");return}o.oncomplete=()=>n("stored"),o.onerror=()=>{let s=o.error;n(s?.name==="ConstraintError"?"conflict":"unavailable");},o.onabort=()=>{let s=o.error;n(s?.name==="ConstraintError"?"conflict":"unavailable");};})}finally{r.close();}}async function hr(){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},false,["sign","verify"]),t=await crypto.subtle.exportKey("jwk",e.publicKey);if(!Ye(t))throw new Error("The browser produced an invalid proof key.");return {privateKey:e.privateKey,publicJwk:t,thumbprint:await Ze(t),persistent:false}}function ne(e){let t=ee.get(e);if(t)return t;let r=(async()=>{let n=await We(e);if(n)return n;let o=await hr(),s=await fr(e,o);return s==="stored"?{...o,persistent:true}:s==="conflict"?await We(e)??o:o})();return ee.set(e,r),r.catch(()=>ee.delete(e)),r}function Qe(){return D(crypto.getRandomValues(new Uint8Array(32)))}function yr(e){let t=new URL(e);return t.search="",t.hash="",t.toString()}async function et(e){let t=D(te(JSON.stringify({typ:ar,alg:cr,jwk:e.key.publicJwk}))),r=D(te(JSON.stringify({htm:e.method.toUpperCase(),htu:yr(e.url),iat:Math.floor(Date.now()/1e3),jti:D(crypto.getRandomValues(new Uint8Array(16))),ath:await Ge(e.token)}))),n=`${t}.${r}`,o=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.key.privateKey,te(n));return `${n}.${D(new Uint8Array(o))}`}async function gr(e){let t=await ne(e.origin);if(t.thumbprint!==e.expectedThumbprint)throw new Error("Session proof key changed.");return et({key:t,method:e.method,url:e.url,token:e.token})}var ar,cr,pr,M,ee,rt=yt(()=>{"use strict";ar="pop+jwt",cr="ES256",pr="authowl-session-proof",M="origin-keys",ee=new Map;});var bt=new Set(["__proto__","constructor","prototype"]);function z(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function _e(e,t=20,r=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&z(),wt(e,t,r)}function wt(e,t=20,r=1e4){return pe(e,0,{nodes:0},t,r)}function pe(e,t,r,n,o){if(r.nodes+=1,(t>n||r.nodes>o)&&z(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||z(),e;if(Array.isArray(e))return e.map(a=>pe(a,t+1,r,n,o));(!e||typeof e!="object")&&z();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&z();let i={};for(let[a,p]of Object.entries(e))bt.has(a)&&z(),i[a]=pe(p,t+1,r,n,o);return i}var de=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function E(e,t){throw new Error(`${e}: ${t}`)}function St(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function ke(e,{label:t,allowHttpLoopback:r}){(typeof e!="string"||e.length===0)&&E(t,"required"),e!==e.trim()&&E(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&E(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&E(t,"path must be unencoded");let n;try{n=new URL(e);}catch{E(t,"absolute URL required");}return (n.username||n.password)&&E(t,"credentials forbidden"),n.protocol!=="https:"&&n.protocol!=="http:"&&E(t,"HTTPS required"),n.protocol==="http:"&&(!r||!de.test(e))&&E(t,"HTTPS required except exact loopback"),n}function Y(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&&de.test(n)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return r}function Ee(e,t,r){let n=St(e);(n.includes("//")||n.split("/").some(o=>o==="."||o==="..")||n!==""&&n!==t.pathname)&&E(r,"path traversal or duplicate separator");}function Ae(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&E("apiUrl","origin required");let r;try{r=new URL(e);}catch{E("apiUrl","origin required");}return r.protocol==="http:"&&(!t.allowHttpLoopback||!de.test(e))&&E("apiUrl","HTTPS required except exact loopback"),r.origin}function Oe(e,t,r={allowHttpLoopback:false}){let n=ke(e,{label:"issuer",allowHttpLoopback:r.allowHttpLoopback}),o=ke(t,{label:"jwksUri",allowHttpLoopback:r.allowHttpLoopback});return Ee(e,n,"issuer"),Ee(t,o,"jwksUri"),n.pathname!=="/"&&n.pathname.endsWith("/")&&E("issuer","trailing slash forbidden"),{issuer:n.toString().replace(/\/$/,""),jwksUri:o.toString()}}var Tt=1e4,_t=1024*1024,R=class extends Error{kind;requestId;constructor(t,r){super(Rt(t)),this.name="TransportError",this.kind=t,this.requestId=r;}},xe=new WeakSet;function _(e,t){let r=new R(e,t);return xe.add(r),r}async function Z({fetchImpl:e,url:t,init:r={},timeoutMs:n=Tt,maxResponseBytes:o=_t,allowHttpLoopback:s=false,decode:i}){Ie(n,"timeoutMs"),Ie(o,"maxResponseBytes");let a=Y(t,{allowHttpLoopback:s}),p=r.signal,l=new AbortController,y=null,b,c=new Promise(h=>{b=h;}),f=h=>{y===null&&(y=h,b({type:"abort",kind:h}),l.abort());},m=()=>f("aborted");p?.addEventListener("abort",m,{once:true});let w=setTimeout(()=>f("timeout"),n);p?.aborted&&m();try{if(y!==null)throw _(y);let h;try{h=await Promise.race([e(a.toString(),{...r,redirect:"error",signal:l.signal}).then(O=>({type:"response",response:O})),c]);}catch{throw _(y??"network")}if(h.type==="abort")throw _(h.kind);if(!kt(h.response))throw _("invalid_response");let T=h.response,g=xt(T.headers),k=await Et(T,o,c,()=>y,g),A=Pt(T,k,g),P;try{P=T.ok&&i?i(A,Object.freeze({status:T.status})):A;}catch{throw _("invalid_response",g)}return {response:T,data:P,...g===void 0?{}:{requestId:g}}}catch(h){throw h instanceof R&&xe.has(h)?h:_(y??"network")}finally{clearTimeout(w),p?.removeEventListener("abort",m);}}function kt(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 Et(e,t,r,n,o){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw Pe(e.body),_("invalid_response",o);if(Number(s)>t)throw Pe(e.body),_("response_too_large",o)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw _("network",o)}let a=[],p=0,l=null;try{for(;;){let c;try{c=await Promise.race([i.read(),r]);}catch{l=_(n()??"network",o);break}if(At(c)){l=_(c.kind,o);break}let{done:f,value:m}=c;if(f)break;if(m.byteLength!==0){if(p+=m.byteLength,p>t){l=_("response_too_large",o);break}a.push(m);}}}finally{l&&Ot(i);try{i.releaseLock();}catch{}}if(l)throw l;let y=new Uint8Array(p),b=0;for(let c of a)y.set(c,b),b+=c.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(y)}catch{throw _("invalid_response",o)}}function At(e){return "type"in e&&e.type==="abort"}function Pe(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function Ot(e){try{e.cancel().catch(()=>{});}catch{}}function Pt(e,t,r){if(e.status===204||e.status===205)return null;let n=It(e.headers.get("content-type"));if(!e.ok&&(!n||t.length===0))return null;if(!n||t.length===0)throw _("invalid_response",r);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw _("invalid_response",r)}}function It(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function xt(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Ie(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Rt(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 vt=new Set(["session","template","access","id"]);function Le(e){return typeof e=="string"&&vt.has(e)}var d=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Nt=300*1e3,jt=5e3,Lt=64*1024,Kt=64,Ct=60*1e3,Re=new Map,Ue=new Map;function ue(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 ve(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new d("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(ue(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new d("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof d?t:new d("Malformed JWT segment.","TOKEN_MALFORMED")}}function Ke(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function Ne(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&ue(e).byteLength===32}function zt(e){if(!Ke(e))throw new d("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 d("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)||!Ne(e.x)||!Ne(e.y))throw new d("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 Dt(e){if(!Ke(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new d("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>Kt)throw new d("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(zt),r=new Set;for(let n of t){if(r.has(n.kid))throw new d("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function je(e,t){let r=Re.get(e);if(!t&&r&&Date.now()-r.fetchedAt<Nt)return r.keys;try{let n=await Z({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:jt,maxResponseBytes:Lt,allowHttpLoopback:new URL(e).protocol==="http:",decode:s=>_e(s)});if(!n.response.ok)throw new d(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let o=Dt(n.data);return Re.set(e,{keys:o,fetchedAt:Date.now()}),o}catch(n){if(n instanceof d)throw n;if(n instanceof R)switch(n.kind){case "timeout":throw new d("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new d("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new d("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new d("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function Mt(e,t){let r=o=>t?o.find(s=>s.kid===t):o[0],n=r(await je(e,false));if(!n){let o=Ue.get(e)??0;Date.now()-o>=Ct&&(Ue.set(e,Date.now()),n=r(await je(e,true)));}if(!n)throw new d("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function $t(e){let t=globalThis.crypto?.subtle;if(!t)throw new d("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 qt(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function Bt(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 Vt(e,t){return I(e,X(t))}function X(e,t=false){if(!e||typeof e!="object")throw new d("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=Oe(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new d("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 d("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.tokenUse!==void 0&&!Le(e.tokenUse))throw new d("Token verifier tokenUse is invalid.","TOKEN_CONFIG_INVALID");if(e.requireTokenUse!==void 0&&typeof e.requireTokenUse!="boolean")throw new d("Token verifier requireTokenUse must be a boolean.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new d("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function I(e,t){if(typeof e!="string"||e.length===0)throw new d("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new d("Malformed JWT.","TOKEN_MALFORMED");let[n,o,s]=r,i=ve(n);if(i.alg!=="ES256")throw new d("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let a=await Mt(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),p;try{p=await $t(a);}catch(h){throw h instanceof d?h:new d("JWKS key could not be imported.","JWKS_KEY_INVALID")}let l;try{if(!/^[A-Za-z0-9_-]{86}$/.test(s))throw new Error("invalid signature encoding");if(l=ue(s),l.byteLength!==64)throw new Error("invalid signature length")}catch{throw new d("Malformed JWT signature.","TOKEN_MALFORMED")}let y=new TextEncoder().encode(`${n}.${o}`),b;try{b=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},p,l,y);}catch{throw new d("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!b)throw new d("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let c=ve(o),f=t.clockToleranceSeconds??60,m=Math.floor(Date.now()/1e3);if(typeof c.exp!="number")throw new d("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(c.exp+f<m)throw new d("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof c.nbf=="number"&&c.nbf-f>m)throw new d("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof c.iss!="string"||c.iss!==t.issuer)throw new d("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!qt(c.aud,t.audience))throw new d("Token audience mismatch.","TOKEN_CLAIM_INVALID");let w=c.token_use;if(w===void 0){if(t.requireTokenUse===true||i.typ!=="JWT")throw new d("Token purpose is missing or unsupported.","TOKEN_USE_UNSUPPORTED")}else if(!Le(w)||(t.tokenUse===void 0?w==="id":w!==t.tokenUse)||i.typ!==(w==="access"?"at+jwt":"JWT"))throw new d("Token purpose is missing or unsupported.","TOKEN_USE_UNSUPPORTED");return {sub:typeof c.sub=="string"?c.sub:null,membership:Bt(c),claims:c}}var Jt=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,Wt=/^sk_/i;function Ce(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(Wt.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=Jt.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 U(e,t){try{return e?.getItem(t)??null}catch{return null}}function v(e,t,r){try{r===null?e?.removeItem(t):e?.setItem(t,r);}catch{}}function L(){try{return globalThis.localStorage}catch{return}}function N(){try{return globalThis.sessionStorage}catch{return}}var Ht="authowl.session-challenge",Ft=e=>`${Ht}.${e}`,Gt="set-auth-challenge",ze="x-authowl-challenge";var Yt=2048,Q=e=>e!==null&&e.length<=Yt,De=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function Zt(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 Me(e){let t=Ft(e),r=new Map;function n(){return r.size===0?null:[...r].map(([a,p])=>`${a}=${p}`).join("; ")}function o(){let a=n();v(N(),t,Q(a)?a:null);}function s(a){for(let[p,l]of Zt(a))De.test(p)&&(l===""?r.delete(p):De.test(l)&&r.set(p,l));}let i=U(N(),t);return Q(i)&&s(i),{presentOn(a){let p=n();a.delete(ze),Q(p)&&a.set(ze,p);},observe(a){let p=a.get(Gt);Q(p)&&(s(p),o());},clear(){r.clear(),o();}}}var $e="set-auth-token",le="x-authowl-session-transport",me="bearer";var Xt="authowl.session-token",Qt="authowl.session-binding",er="authowl.cookie-transport",Be="ok",Ve="bearer",tr=e=>`${Xt}.${e}`,rr=e=>`${Qt}.${e}`,nr=e=>`${er}.${e}`;function or(e){return e===Be?"cookies":e===Ve?"bearer":"unknown"}function sr(e){return e==="cookies"?Be:e==="bearer"?Ve:null}function ir(e){let t=tr(e),r=rr(e),n=nr(e),o=Me(e),s=null,i=null,a=null,p=false,l=null,y=or(U(L(),n)),b=()=>y==="unknown",c=0,f=null,m=false;function w(){let u=U(N(),t);if(u!==null)return p=true,u;let S=U(L(),t);return S!==null?(p=false,S):null}function h(){return U(N(),r)??U(L(),r)}s=w(),i=s===null?null:h(),s!==null&&b()&&(m=true);function T(){if(!(!m||!f)){m=false;try{f();}catch{}}}function g(){let u=y==="bearer"?s:null,S=u===null?null:i,[q,Te]=p?[N(),L()]:[L(),N()];v(Te,t,null),v(Te,r,null),v(q,t,u),v(q,r,S);}function k(u){u!==null&&l!==null&&(p=l,l=null),u!==null&&a!==null?(i=a,a=null):u===null&&(i=null),s=u,g(),u!==null&&b()&&(m=true,T());}function A(u){y=u,v(L(),n,sr(u));}function P(){A("unknown"),m=false;}function O(){return s===null&&(s=w(),i=s===null?null:h()),s}function G(){let u=w();return u!==null&&(s=u,i=h()),s}function ft(u){G()===u&&g();}function we(){c+=1,l=null,a=null,p=false,k(null),o.clear(),P();}let Se=()=>y!=="cookies";return {hasToken:()=>O()!==null,bindingThumbprint:()=>(O(),i),declareOn(u){if(u.has("authorization"))return false;let S=O();return !S&&!Se()?false:(S&&u.set("authorization",`Bearer ${S}`),u.set(le,me),o.presentOn(u),true)},wantsToken:Se,needsProbe:b,observe(u){let S=u.get($e);S&&k(S),o.observe(u);},dropChallenge:o.clear,measureWith(u){f=u,T();},beginRead(){let u=O(),S=c;return {carriedToken:u!==null,endIfDead(){u!==null&&G()===u&&c===S&&we();},recordCookieVerdict(q){if(c===S&&b()){if(A(q?"cookies":"bearer"),q){k(null);return}ft(u);}}}},beginSession({remember:u}){c+=1,l=!u,o.clear(),P();},useCookieTransport(){O()===null&&(a=null,A("cookies"));},completeCookieTransport(){A("cookies"),k(null);},useBoundBearerTransport(u,S){if(!u)throw new Error("A session proof thumbprint is required.");a=u,S||(l=true),A("bearer");},endSession:we}}var qe=new Map;function Je(e){let t=qe.get(e);if(t)return t;let r=ir(e);return qe.set(e,r),r}var fe="x-authowl-session-proof",nt="x-authowl-session-binding",ot="x-authowl-session-binding-proof",oe=()=>Promise.resolve().then(()=>(rt(),tt));function br(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function st(e,t){let r=Je(e.projectId),n=(c,f)=>(t??globalThis.fetch)(c,f),o=typeof globalThis.location=="object"&&typeof globalThis.location.origin=="string"&&globalThis.location.origin!=="null"?globalThis.location.origin:null,s=null,i=false,a=()=>new Headers({"x-publishable-key":e.publishableKey});async function p(c){let f=c.get("authorization");f&&await oe().then(m=>m.abandonSession(n,`${e.projectBaseURL}/session/abandon`,a(),f));}async function l(c){s=null,i=false;let f=await oe().then(m=>m.prepareSenderConstrainedSession({tokens:r,start:c,clientOrigin:o,fetcher:n,projectBaseURL:e.projectBaseURL,headers:a()}));s=f.binding,i=f.cookieOnly;}return {fetch:async(c,f)=>{if(f?.credentials==="omit"||!r.wantsToken())return n(c,f);let m=br(c,f),w=r.declareOn(m),h=m.get("authorization"),T=(f?.method??(typeof c=="object"&&c!==null&&"method"in c?c.method:"GET")).toUpperCase(),g=typeof c=="string"?c:c instanceof URL?c.toString():c.url;if(w&&o){let A=!!h;if(h){let P=h.replace(/^Bearer\s+/i,""),O=r.bindingThumbprint();if(O)try{m.set(fe,await oe().then(G=>G.createStoredSessionProof({origin:o,expectedThumbprint:O,method:T,url:g,token:P})));}catch{await p(m),r.endSession(),m.delete("authorization"),m.delete(fe),m.delete(nt),m.delete(ot),A=false;}}if(s){let P=s;m.set(nt,P.nonce),m.set(A?ot:fe,await oe().then(O=>O.createSessionProof({key:P.key,method:T,url:g,token:P.nonce})));}}let k=await n(c,{...f,headers:m});return w&&(k.status===401&&h&&(new URL(g).pathname.endsWith("/get-session")||new URL(g).pathname.endsWith("/sign-out"))?(await p(m),r.endSession(),s=null,i=false):(r.observe(k.headers),k.headers.has("set-auth-token")&&(i&&r.completeCookieTransport(),s=null,i=false))),k},probe:n,tokens:r,prepareSession:l}}function it(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=Ce(e.publishableKey),r=Ae(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:r,decoded:t,projectBaseURL:`${r}/api/projects/${t.projectId}/auth`}}function he(e){let t=it(e),{fetch:r,...n}=st({projectId:t.decoded.projectId,projectBaseURL:t.projectBaseURL,publishableKey:t.publishableKey},e.fetch);return {...e,...t,fetch:r,session:n}}function se(e,t){return !e||!t?false:e.permissions.includes(t)}function wr(e,t){return !e||!t?false:e.teams?.includes(t)??false}function Sr(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function ie(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&&!Sr(e,r)||n!==void 0&&!e.permissions.includes(n)||o!==void 0&&!wr(e,o))}var ye="Authentication is required.",x=class extends Error{reason;status;cause;constructor(t,r,n){super(r),this.name="AuthorizationError",this.reason=t,this.status=t==="unauthenticated"?401:403,Object.defineProperty(this,"cause",{value:n,enumerable:false,writable:false,configurable:true});}};function Tr(e){if(typeof e!="object"||e===null)return false;let t=e;return t.name==="AuthorizationError"&&typeof t.message=="string"&&(t.reason==="unauthenticated"&&t.status===401||t.reason==="forbidden"&&t.status===403)}var _r=new Set(["TOKEN_VERIFICATION_FAILED","TOKEN_MALFORMED","TOKEN_ALGORITHM_UNSUPPORTED","TOKEN_SIGNATURE_INVALID","TOKEN_CLAIM_INVALID","TOKEN_USE_UNSUPPORTED","JWKS_KEY_NOT_FOUND"]);function kr(e){if(typeof e!="string"||e.trim().length===0)throw new x("unauthenticated",ye);return e}function B(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`${t} needs a non-empty value.`)}async function V(e,t){let r=kr(t),n;try{n=await e(r);}catch(o){throw o instanceof d&&_r.has(o.code)?new x("unauthenticated",ye,o):o}if(n.sub===null||n.sub.trim().length===0)throw new x("unauthenticated",ye);return n}async function at(e,t,r){if(r.role===void 0&&r.permission===void 0&&r.teamId===void 0)throw new TypeError("requireGrant needs at least one of role, permission, or teamId.");r.role!==void 0&&B(r.role,"requireGrant role"),r.permission!==void 0&&B(r.permission,"requireGrant permission"),r.teamId!==void 0&&B(r.teamId,"requireGrant teamId");let n=await V(e,t);if(!ie(n.membership,r))throw new x("forbidden","Token does not grant the required access.");return n}async function ct(e,t,r){B(r,"requireOrg organization id");let n=await V(e,t);if(n.claims.org_id!==r)throw new x("forbidden","Token was not minted for this organization.");return n}async function pt(e,t,r){B(r,"requirePermission permission");let n=await V(e,t);if(!se(n.membership,r))throw new x("forbidden","Token does not grant the required permission.");return n}function Er(e,t){let r=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${r}.session_token`}var Ar="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",J={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"}}}},ge={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 Or=new Set(["__proto__","constructor","prototype"]),Pr=64,Ir=5e4;function dt(e,t,r){let o=J[e].responseSchemas;Object.hasOwn(o,String(t))||ae();let s=o[String(t)];if(s===null){r!==null&&ae();return}let i={nodes:0};return j(r,K(s),0,i)||ae(),r}function j(e,t,r,n){if(n.nodes+=1,r>Pr||n.nodes>Ir)return false;if(typeof t.$ref=="string"){let s=Lr(t.$ref);if(s===null||!j(e,s,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(s=>j(e,K(s),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(s=>j(e,K(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=>xr(e,s))?false:e===null?t.type===void 0||o.includes("null"):typeof e=="string"?Rr(e,t):typeof e=="number"?vr(e,t):Array.isArray(e)?Nr(e,t,r,n):W(e)?jr(e,t,r,n):typeof e=="boolean"}function xr(e,t){switch(t){case "null":return e===null;case "object":return W(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 Rr(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!Ur(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 Ur(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 vr(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Nr(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=K(t.items);return e.every(s=>j(s,o,r+1,n))}function jr(e,t,r,n){let o=Object.keys(e);if(o.some(i=>Or.has(i))||typeof t.minProperties=="number"&&o.length<t.minProperties||typeof t.maxProperties=="number"&&o.length>t.maxProperties)return false;let s=W(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&o.some(i=>!j(i,K(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=s[i];if(p!==void 0){if(!j(a,K(p),r+1,n))return false;continue}if(t.additionalProperties===false||W(t.additionalProperties)&&!j(a,t.additionalProperties,r+1,n))return false}return true}function Lr(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(ge,r)?K(ge[r]):null}function K(e){return W(e)||ae(),e}function W(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function ae(){throw new TypeError("Admin API response does not match its generated contract.")}var Kr=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Cr=1024*1024,zr=1e4,H=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;}},$=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 Dr(e){Mr();let t=$r(e?.secretKey),r=qr(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,p)=>{let l=p??{},y=J[a],b=new URL(Br(y.path,l).replace(/^\/+/,""),r);Vr(b,l);let c=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Jr(c,l);let f="body"in l?JSON.stringify(l.body):void 0;f!==void 0&&c.set("content-type","application/json");let m;try{m=await Z({fetchImpl:o,url:b,init:{method:y.method,headers:c,body:f,signal:p?.signal},timeoutMs:zr,maxResponseBytes:Cr,allowHttpLoopback:r.protocol==="http:",decode:(g,k)=>dt(a,k.status,g)});}catch(g){throw g instanceof H?g:g instanceof R?new $(g.kind,g.requestId):new $("network")}let{response:w,requestId:h,data:T}=m;if(!w.ok)throw Wr(w,T,h);if(!y.successStatuses.some(g=>g===w.status))throw new $("invalid_response",h);return T},i=Object.assign(Object.create(null),{request:s});for(let a of Object.keys(J))i[a]=p=>s(a,p);return Object.freeze(i)}function Mr(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function $r(e){if(typeof e!="string"||!Kr.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function qr(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=Y(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 Br(e,t){let r="path"in t&&ce(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 Vr(e,t){if(!(!("query"in t)||!ce(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 Jr(e,t){if(!(!("header"in t)||!ce(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 Wr(e,t,r){let n=r??ut(e.headers.get("x-request-id"),256),o=ut(e.headers.get("retry-after"),128),s=Hr(e.status,n),i=Fr(t)?t:s;return new H({status:e.status,code:i.code,requestId:n,problem:i,retryAfter:o})}function Hr(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 Fr(e){return ce(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 ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ut(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var Gr=/^v1=([a-f0-9]{64})$/i,Yr=/^whsec_[A-Za-z0-9_-]{1,256}$/,Zr=/^(0|[1-9]\d{0,10})$/;async function Xr(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=Qr(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=tn(e.rawBody);if(o.byteLength>1048576||typeof e.timestamp!="string"||!Zr.test(e.timestamp))return false;let s=Number(e.timestamp);if(!Number.isSafeInteger(s)||Math.abs(n-s)>r)return false;let i=en(e.signatureHeader);if(i.length===0)return false;let a=new TextEncoder().encode(`${e.timestamp}.`),p=new Uint8Array(a.byteLength+o.byteLength);p.set(a),p.set(o,a.byteLength);let l=false;for(let y of t){let b=await crypto.subtle.importKey("raw",new TextEncoder().encode(y),{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=new Uint8Array(await crypto.subtle.sign("HMAC",b,p));for(let f of i)l=nn(c,f)||l;}return l}function Qr(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!Yr.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function en(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=Gr.exec(n.trim());o&&r.push(rn(o[1]));}return r}function tn(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 rn(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 nn(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 on="/.well-known/oauth-protected-resource";function be(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 lt(e){let t=be(e,"resource"),r=t.pathname==="/"?"":t.pathname.replace(/\/+$/,"");return `${t.origin}${on}${r}${t.search}`}function sn(e){if(be(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)be(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 an(e){let t=[`resource_metadata="${lt(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 mt=["publishableKey","apiUrl","issuer","jwksUri","audience"],cn=new Set([...mt,"clockToleranceSeconds","tokenUse","requireTokenUse"]);function C(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=>!cn.has(a)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(mt.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 X({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds,tokenUse:e.tokenUse,requireTokenUse:e.requireTokenUse})}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=he({publishableKey:o,apiUrl:s});return X({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds,tokenUse:e?.tokenUse,requireTokenUse:e?.requireTokenUse},i.decoded.env==="test")}function F(e){return {...e,tokenUse:"session"}}async function Xn(e,t){return I(e,C(t))}async function Qn(e,t,r){let n=C(r);try{let o=await I(e,F(n));return ie(o.membership,t)}catch{return false}}async function eo(e,t,r){let n=C(r);try{let o=await I(e,F(n));return se(o.membership,t.permission)}catch{return false}}async function to(e,t){let r=C(t);return V(n=>I(n,r),e)}async function ro(e,t,r){let n=C(r);return pt(o=>I(o,F(n)),e,t)}async function no(e,t,r){let n=C(r);return at(o=>I(o,F(n)),e,t)}async function oo(e,t,r){let n=C(r);return ct(o=>I(o,F(n)),e,t)}
2
- exports.ADMIN_API_SPEC_SHA256=Ar;exports.AuthOwlAdminApiError=H;exports.AuthOwlAdminNetworkError=$;exports.AuthorizationError=x;exports.SESSION_TRANSPORT_BEARER=me;exports.SESSION_TRANSPORT_HEADER=le;exports.TokenVerificationError=d;exports.createAdminClient=Dr;exports.has=Qn;exports.hasPermission=eo;exports.isAuthorizationError=Tr;exports.mcpProtectedResourceMetadata=sn;exports.mcpProtectedResourceMetadataUrl=lt;exports.mcpUnauthorizedChallenge=an;exports.requireAuth=to;exports.requireGrant=no;exports.requireOrg=oo;exports.requirePermission=ro;exports.resolveAuthTarget=it;exports.resolveConfig=he;exports.sessionCookieName=Er;exports.verifyProjectToken=Vt;exports.verifyToken=Xn;exports.verifyWebhook=Xr;
1
+ 'use strict';var bt=Object.defineProperty;var wt=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var St=(e,t)=>{for(var r in t)bt(e,r,{get:t[r],enumerable:true});};var ot={};St(ot,{abandonSession:()=>Ze,bindingNonce:()=>rt,boundedSessionFetch:()=>ne,clearSessionProofKeyMemoryForTests:()=>hr,cookieCapability:()=>Ye,createSessionProof:()=>nt,createStoredSessionProof:()=>Tr,prepareSenderConstrainedSession:()=>fr,sessionProofKey:()=>oe});async function ne(e,t,r,n){let o=new AbortController,s,i=new Promise((a,p)=>{s=setTimeout(()=>{o.abort(),p(new Error("AuthOwl session transport request timed out."));},n);});try{return await Promise.race([e(t,{...r,signal:o.signal}),i])}finally{clearTimeout(s);}}async function Ye(e,t,r){let n=await ne(e,t,{method:"POST",credentials:"include",headers:r},1e4);if(n.status===404||n.status===405)return "legacy";if(n.status!==204)throw new Error("AuthOwl cookie capability check failed.");let o=await ne(e,t,{method:"GET",credentials:"include",headers:r},1e4);if(o.status===404||o.status===405)return "legacy";if(o.status!==200)throw new Error("AuthOwl cookie capability check failed.");let s=await o.text();if(new TextEncoder().encode(s).byteLength>128)throw new Error("AuthOwl cookie capability response is invalid.");let i;try{i=JSON.parse(s);}catch{throw new Error("AuthOwl cookie capability response is invalid.")}if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length!==1||typeof i.cookieSupported!="boolean")throw new Error("AuthOwl cookie capability response is invalid.");return i.cookieSupported}async function Ze(e,t,r,n){let o=new Headers(r);o.set("authorization",n),o.set("x-authowl-session-transport","bearer");try{await ne(e,t,{method:"POST",credentials:"include",headers:o},2e3);}catch{}}async function fr(e){let{tokens:t}=e;if(t.beginSession(e.start),!e.clientOrigin)return {binding:null,cookieOnly:false};let r=null;if(t.hasToken()){let s=t.bindingThumbprint();if(s)try{let i=await oe(e.clientOrigin);if(i.thumbprint!==s)throw new Error("Session proof key changed.");r=i;}catch{let i=new Headers;t.declareOn(i);let a=i.get("authorization");a&&await Ze(e.fetcher,`${e.projectBaseURL}/session/abandon`,e.headers,a),t.endSession(),t.beginSession(e.start);}}let n;try{n=await Ye(e.fetcher,`${e.projectBaseURL}/session/cookie-capability`,e.headers);}catch{return t.useCookieTransport(),{binding:null,cookieOnly:false}}if(n==="legacy")return {binding:null,cookieOnly:false};if(n)return t.hasToken()?{binding:null,cookieOnly:true}:(t.useCookieTransport(),{binding:null,cookieOnly:false});let o=r??await oe(e.clientOrigin);return t.useBoundBearerTransport(o.thumbprint,o.persistent),{binding:{key:o,nonce:rt()},cookieOnly:false}}function D(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function re(e){return new TextEncoder().encode(e)}async function Xe(e){return D(new Uint8Array(await crypto.subtle.digest("SHA-256",re(e))))}function Qe(e){return e.kty==="EC"&&e.crv==="P-256"&&typeof e.x=="string"&&e.x.length>0&&typeof e.y=="string"&&e.y.length>0&&e.d===void 0}async function et(e){return Xe(JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y}))}function yr(e){if(!e||typeof e!="object")return false;let t=e,r=t.algorithm;return t.type==="private"&&t.extractable===false&&t.usages.length===1&&t.usages[0]==="sign"&&r.name==="ECDSA"&&r.namedCurve==="P-256"}function hr(){te.clear();}async function gr(e){if(!e||typeof e!="object")return null;let t=e;if(!yr(t.privateKey)||!t.publicJwk||!Qe(t.publicJwk))return null;let r=await et(t.publicJwk);return t.thumbprint!==r?null:{privateKey:t.privateKey,publicJwk:t.publicJwk,thumbprint:r,persistent:true}}function tt(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise(e=>{let t;try{t=indexedDB.open(mr,1);}catch{e(null);return}t.onupgradeneeded=()=>{t.result.objectStoreNames.contains(M)||t.result.createObjectStore(M,{keyPath:"origin"});},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);})}async function Ge(e){let t=await tt();if(!t)return null;try{let r=await new Promise(n=>{let o=t.transaction(M,"readonly").objectStore(M).get(e);o.onsuccess=()=>n(o.result),o.onerror=()=>n(null);});return await gr(r)}finally{t.close();}}async function br(e,t){let r=await tt();if(!r)return "unavailable";try{return await new Promise(n=>{let o;try{o=r.transaction(M,"readwrite"),o.objectStore(M).add({origin:e,privateKey:t.privateKey,publicJwk:t.publicJwk,thumbprint:t.thumbprint});}catch{n("unavailable");return}o.oncomplete=()=>n("stored"),o.onerror=()=>{let s=o.error;n(s?.name==="ConstraintError"?"conflict":"unavailable");},o.onabort=()=>{let s=o.error;n(s?.name==="ConstraintError"?"conflict":"unavailable");};})}finally{r.close();}}async function wr(){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},false,["sign","verify"]),t=await crypto.subtle.exportKey("jwk",e.publicKey);if(!Qe(t))throw new Error("The browser produced an invalid proof key.");return {privateKey:e.privateKey,publicJwk:t,thumbprint:await et(t),persistent:false}}function oe(e){let t=te.get(e);if(t)return t;let r=(async()=>{let n=await Ge(e);if(n)return n;let o=await wr(),s=await br(e,o);return s==="stored"?{...o,persistent:true}:s==="conflict"?await Ge(e)??o:o})();return te.set(e,r),r.catch(()=>te.delete(e)),r}function rt(){return D(crypto.getRandomValues(new Uint8Array(32)))}function Sr(e){let t=new URL(e);return t.search="",t.hash="",t.toString()}async function nt(e){let t=D(re(JSON.stringify({typ:ur,alg:lr,jwk:e.key.publicJwk}))),r=D(re(JSON.stringify({htm:e.method.toUpperCase(),htu:Sr(e.url),iat:Math.floor(Date.now()/1e3),jti:D(crypto.getRandomValues(new Uint8Array(16))),ath:await Xe(e.token)}))),n=`${t}.${r}`,o=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.key.privateKey,re(n));return `${n}.${D(new Uint8Array(o))}`}async function Tr(e){let t=await oe(e.origin);if(t.thumbprint!==e.expectedThumbprint)throw new Error("Session proof key changed.");return nt({key:t,method:e.method,url:e.url,token:e.token})}var ur,lr,mr,M,te,st=wt(()=>{"use strict";ur="pop+jwt",lr="ES256",mr="authowl-session-proof",M="origin-keys",te=new Map;});var Tt=new Set(["__proto__","constructor","prototype"]);function z(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function Ee(e,t=20,r=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&z(),_t(e,t,r)}function _t(e,t=20,r=1e4){return de(e,0,{nodes:0},t,r)}function de(e,t,r,n,o){if(r.nodes+=1,(t>n||r.nodes>o)&&z(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||z(),e;if(Array.isArray(e))return e.map(a=>de(a,t+1,r,n,o));(!e||typeof e!="object")&&z();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&z();let i={};for(let[a,p]of Object.entries(e))Tt.has(a)&&z(),i[a]=de(p,t+1,r,n,o);return i}var ue=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function E(e,t){throw new Error(`${e}: ${t}`)}function kt(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function Ae(e,{label:t,allowHttpLoopback:r}){(typeof e!="string"||e.length===0)&&E(t,"required"),e!==e.trim()&&E(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&E(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&E(t,"path must be unencoded");let n;try{n=new URL(e);}catch{E(t,"absolute URL required");}return (n.username||n.password)&&E(t,"credentials forbidden"),n.protocol!=="https:"&&n.protocol!=="http:"&&E(t,"HTTPS required"),n.protocol==="http:"&&(!r||!ue.test(e))&&E(t,"HTTPS required except exact loopback"),n}function Z(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&&ue.test(n)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return r}function Oe(e,t,r){let n=kt(e);(n.includes("//")||n.split("/").some(o=>o==="."||o==="..")||n!==""&&n!==t.pathname)&&E(r,"path traversal or duplicate separator");}function Pe(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&E("apiUrl","origin required");let r;try{r=new URL(e);}catch{E("apiUrl","origin required");}return r.protocol==="http:"&&(!t.allowHttpLoopback||!ue.test(e))&&E("apiUrl","HTTPS required except exact loopback"),r.origin}function Ie(e,t,r={allowHttpLoopback:false}){let n=Ae(e,{label:"issuer",allowHttpLoopback:r.allowHttpLoopback}),o=Ae(t,{label:"jwksUri",allowHttpLoopback:r.allowHttpLoopback});return Oe(e,n,"issuer"),Oe(t,o,"jwksUri"),n.pathname!=="/"&&n.pathname.endsWith("/")&&E("issuer","trailing slash forbidden"),{issuer:n.toString().replace(/\/$/,""),jwksUri:o.toString()}}var Et=1e4,At=1024*1024,x=class extends Error{kind;requestId;constructor(t,r){super(Nt(t)),this.name="TransportError",this.kind=t,this.requestId=r;}},Ue=new WeakSet;function _(e,t){let r=new x(e,t);return Ue.add(r),r}async function X({fetchImpl:e,url:t,init:r={},timeoutMs:n=Et,maxResponseBytes:o=At,allowHttpLoopback:s=false,decode:i}){xe(n,"timeoutMs"),xe(o,"maxResponseBytes");let a=Z(t,{allowHttpLoopback:s}),p=r.signal,l=new AbortController,h=null,b,c=new Promise(y=>{b=y;}),f=y=>{h===null&&(h=y,b({type:"abort",kind:y}),l.abort());},m=()=>f("aborted");p?.addEventListener("abort",m,{once:true});let w=setTimeout(()=>f("timeout"),n);p?.aborted&&m();try{if(h!==null)throw _(h);let y;try{y=await Promise.race([e(a.toString(),{...r,redirect:"error",signal:l.signal}).then(A=>({type:"response",response:A})),c]);}catch{throw _(h??"network")}if(y.type==="abort")throw _(y.kind);if(!Ot(y.response))throw _("invalid_response");let T=y.response,g=vt(T.headers),O=await Pt(T,o,c,()=>h,g),P=xt(T,O,g),k;try{k=T.ok&&i?i(P,Object.freeze({status:T.status})):P;}catch{throw _("invalid_response",g)}return {response:T,data:k,...g===void 0?{}:{requestId:g}}}catch(y){throw y instanceof x&&Ue.has(y)?y:_(h??"network")}finally{clearTimeout(w),p?.removeEventListener("abort",m);}}function Ot(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 Pt(e,t,r,n,o){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw Re(e.body),_("invalid_response",o);if(Number(s)>t)throw Re(e.body),_("response_too_large",o)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw _("network",o)}let a=[],p=0,l=null;try{for(;;){let c;try{c=await Promise.race([i.read(),r]);}catch{l=_(n()??"network",o);break}if(It(c)){l=_(c.kind,o);break}let{done:f,value:m}=c;if(f)break;if(m.byteLength!==0){if(p+=m.byteLength,p>t){l=_("response_too_large",o);break}a.push(m);}}}finally{l&&Rt(i);try{i.releaseLock();}catch{}}if(l)throw l;let h=new Uint8Array(p),b=0;for(let c of a)h.set(c,b),b+=c.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(h)}catch{throw _("invalid_response",o)}}function It(e){return "type"in e&&e.type==="abort"}function Re(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function Rt(e){try{e.cancel().catch(()=>{});}catch{}}function xt(e,t,r){if(e.status===204||e.status===205)return null;let n=Ut(e.headers.get("content-type"));if(!e.ok&&(!n||t.length===0))return null;if(!n||t.length===0)throw _("invalid_response",r);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw _("invalid_response",r)}}function Ut(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function vt(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function xe(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Nt(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 jt=new Set(["session","template","access","id"]);function Ce(e){return typeof e=="string"&&jt.has(e)}var u=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Kt=300*1e3,Ct=5e3,zt=64*1024,Dt=64,Mt=60*1e3,ve=new Map,Ne=new Map;function le(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 u("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(le(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new u("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof u?t:new u("Malformed JWT segment.","TOKEN_MALFORMED")}}function ze(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function je(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&le(e).byteLength===32}function $t(e){if(!ze(e))throw new u("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 u("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)||!je(e.x)||!je(e.y))throw new u("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 qt(e){if(!ze(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new u("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>Dt)throw new u("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map($t),r=new Set;for(let n of t){if(r.has(n.kid))throw new u("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function Ke(e,t){let r=ve.get(e);if(!t&&r&&Date.now()-r.fetchedAt<Kt)return r.keys;try{let n=await X({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Ct,maxResponseBytes:zt,allowHttpLoopback:new URL(e).protocol==="http:",decode:s=>Ee(s)});if(!n.response.ok)throw new u(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let o=qt(n.data);return ve.set(e,{keys:o,fetchedAt:Date.now()}),o}catch(n){if(n instanceof u)throw n;if(n instanceof x)switch(n.kind){case "timeout":throw new u("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new u("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new u("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new u("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function Bt(e,t){let r=o=>t?o.find(s=>s.kid===t):o[0],n=r(await Ke(e,false));if(!n){let o=Ne.get(e)??0;Date.now()-o>=Mt&&(Ne.set(e,Date.now()),n=r(await Ke(e,true)));}if(!n)throw new u("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function Vt(e){let t=globalThis.crypto?.subtle;if(!t)throw new u("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 Jt(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function Wt(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 Ht(e,t){return I(e,Q(t))}function Q(e,t=false){if(!e||typeof e!="object")throw new u("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=Ie(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new u("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 u("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.tokenUse!==void 0&&!Ce(e.tokenUse))throw new u("Token verifier tokenUse is invalid.","TOKEN_CONFIG_INVALID");if(e.requireTokenUse!==void 0&&typeof e.requireTokenUse!="boolean")throw new u("Token verifier requireTokenUse must be a boolean.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new u("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function I(e,t){if(typeof e!="string"||e.length===0)throw new u("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new u("Malformed JWT.","TOKEN_MALFORMED");let[n,o,s]=r,i=Le(n);if(i.alg!=="ES256")throw new u("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let a=await Bt(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),p;try{p=await Vt(a);}catch(y){throw y instanceof u?y:new u("JWKS key could not be imported.","JWKS_KEY_INVALID")}let l;try{if(!/^[A-Za-z0-9_-]{86}$/.test(s))throw new Error("invalid signature encoding");if(l=le(s),l.byteLength!==64)throw new Error("invalid signature length")}catch{throw new u("Malformed JWT signature.","TOKEN_MALFORMED")}let h=new TextEncoder().encode(`${n}.${o}`),b;try{b=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},p,l,h);}catch{throw new u("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!b)throw new u("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let c=Le(o),f=t.clockToleranceSeconds??60,m=Math.floor(Date.now()/1e3);if(typeof c.exp!="number")throw new u("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(c.exp+f<m)throw new u("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof c.nbf=="number"&&c.nbf-f>m)throw new u("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof c.iss!="string"||c.iss!==t.issuer)throw new u("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!Jt(c.aud,t.audience))throw new u("Token audience mismatch.","TOKEN_CLAIM_INVALID");let w=c.token_use;if(w===void 0){if(t.requireTokenUse===true||i.typ!=="JWT")throw new u("Token purpose is missing or unsupported.","TOKEN_USE_UNSUPPORTED")}else if(!Ce(w)||(t.tokenUse===void 0?w==="id":w!==t.tokenUse)||i.typ!==(w==="access"?"at+jwt":"JWT"))throw new u("Token purpose is missing or unsupported.","TOKEN_USE_UNSUPPORTED");return {sub:typeof c.sub=="string"?c.sub:null,membership:Wt(c),claims:c}}var Ft=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,Gt=/^sk_/i;function De(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(Gt.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=Ft.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 U(e,t){try{return e?.getItem(t)??null}catch{return null}}function v(e,t,r){try{r===null?e?.removeItem(t):e?.setItem(t,r);}catch{}}function j(){try{return globalThis.localStorage}catch{return}}function N(){try{return globalThis.sessionStorage}catch{return}}var Yt="authowl.session-challenge",Zt=e=>`${Yt}.${e}`,Xt="set-auth-challenge",Me="x-authowl-challenge";var Qt=2048,ee=e=>e!==null&&e.length<=Qt,$e=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function er(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 qe(e){let t=Zt(e),r=new Map;function n(){return r.size===0?null:[...r].map(([a,p])=>`${a}=${p}`).join("; ")}function o(){let a=n();v(N(),t,ee(a)?a:null);}function s(a){for(let[p,l]of er(a))$e.test(p)&&(l===""?r.delete(p):$e.test(l)&&r.set(p,l));}let i=U(N(),t);return ee(i)&&s(i),{presentOn(a){let p=n();a.delete(Me),ee(p)&&a.set(Me,p);},observe(a){let p=a.get(Xt);ee(p)&&(s(p),o());},clear(){r.clear(),o();}}}var Be="set-auth-token",me="x-authowl-session-transport",fe="bearer";var tr="authowl.session-token",rr="authowl.session-binding",nr="authowl.cookie-transport",Je="ok",We="bearer",or=e=>`${tr}.${e}`,sr=e=>`${rr}.${e}`,ir=e=>`${nr}.${e}`;function ar(e){return e===Je?"cookies":e===We?"bearer":"unknown"}function cr(e){return e==="cookies"?Je:e==="bearer"?We:null}function pr(e){let t=or(e),r=sr(e),n=ir(e),o=qe(e),s=new Set;function i(d){for(let S of s)try{S(d);}catch{}}let a=null,p=null,l=null,h=false,b=null,c=ar(U(j(),n)),f=()=>c==="unknown",m=0,w=null,y=false;function T(){let d=U(N(),t);if(d!==null)return h=true,d;let S=U(j(),t);return S!==null?(h=false,S):null}function g(){return U(N(),r)??U(j(),r)}a=T(),p=a===null?null:g(),a!==null&&f()&&(y=true);function O(){if(!(!y||!w)){y=false;try{w();}catch{}}}function P(){let d=c==="bearer"?a:null,S=d===null?null:p,[B,ke]=h?[N(),j()]:[j(),N()];v(ke,t,null),v(ke,r,null),v(B,t,d),v(B,r,S);}function k(d){d!==null&&b!==null&&(h=b,b=null),d!==null&&l!==null?(p=l,l=null):d===null&&(p=null),a=d,P(),d!==null&&f()&&(y=true,O());}function A(d){c=d,v(j(),n,cr(d));}function Y(){A("unknown"),y=false;}function q(){return a===null&&(a=T(),p=a===null?null:g()),a}function Se(){let d=T();return d!==null&&(a=d,p=g()),a}function gt(d){Se()===d&&P();}function Te(){m+=1,b=null,l=null,h=false,k(null),o.clear(),Y(),i({type:"endSession"});}let _e=()=>c!=="cookies";return {subscribeLifecycle(d){return s.add(d),()=>s.delete(d)},hasToken:()=>q()!==null,bindingThumbprint:()=>(q(),p),declareOn(d){if(d.has("authorization"))return false;let S=q();return !S&&!_e()?false:(S&&d.set("authorization",`Bearer ${S}`),d.set(me,fe),o.presentOn(d),true)},wantsToken:_e,needsProbe:f,observe(d){let S=d.get(Be);S&&k(S),o.observe(d);},dropChallenge:o.clear,measureWith(d){w=d,O();},beginRead(){let d=q(),S=m;return {carriedToken:d!==null,endIfDead(){d!==null&&Se()===d&&m===S&&Te();},recordCookieVerdict(B){if(m===S&&f()){if(A(B?"cookies":"bearer"),B){k(null);return}gt(d);}}}},beginSession({remember:d}){m+=1,b=!d,o.clear(),Y(),i({type:"beginSession",remember:d});},useCookieTransport(){q()===null&&(l=null,A("cookies"));},completeCookieTransport(){A("cookies"),k(null);},useBoundBearerTransport(d,S){if(!d)throw new Error("A session proof thumbprint is required.");l=d,S||(b=true),A("bearer");},endSession:Te}}var Ve=new Map;function He(e){let t=Ve.get(e);if(t)return t;let r=pr(e);return Ve.set(e,r),r}var dr=Symbol.for("authowl.session-transport-integration.v1");function Fe(e){return e?e[dr]??null:null}var ye="x-authowl-session-proof",it="x-authowl-session-binding",at="x-authowl-session-binding-proof",se=()=>Promise.resolve().then(()=>(st(),ot));function _r(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function ct(e,t){let r=He(e.projectId),n=(c,f)=>(t??globalThis.fetch)(c,f),o=typeof globalThis.location=="object"&&typeof globalThis.location.origin=="string"&&globalThis.location.origin!=="null"?globalThis.location.origin:null,s=null,i=false,a=()=>new Headers({"x-publishable-key":e.publishableKey});async function p(c){let f=c.get("authorization");f&&await se().then(m=>m.abandonSession(n,`${e.projectBaseURL}/session/abandon`,a(),f));}async function l(c){s=null,i=false;let f=await se().then(m=>m.prepareSenderConstrainedSession({tokens:r,start:c,clientOrigin:o,fetcher:n,projectBaseURL:e.projectBaseURL,headers:a()}));s=f.binding,i=f.cookieOnly;}return {fetch:async(c,f)=>{if(f?.credentials==="omit"||!r.wantsToken())return n(c,f);let m=_r(c,f),w=r.declareOn(m),y=m.get("authorization"),T=(f?.method??(typeof c=="object"&&c!==null&&"method"in c?c.method:"GET")).toUpperCase(),g=typeof c=="string"?c:c instanceof URL?c.toString():c.url;if(w&&o){let P=!!y;if(y){let k=y.replace(/^Bearer\s+/i,""),A=r.bindingThumbprint();if(A)try{m.set(ye,await se().then(Y=>Y.createStoredSessionProof({origin:o,expectedThumbprint:A,method:T,url:g,token:k})));}catch{await p(m),r.endSession(),m.delete("authorization"),m.delete(ye),m.delete(it),m.delete(at),P=false;}}if(s){let k=s;m.set(it,k.nonce),m.set(P?at:ye,await se().then(A=>A.createSessionProof({key:k.key,method:T,url:g,token:k.nonce})));}}let O=await n(c,{...f,headers:m});return w&&(O.status===401&&y&&(new URL(g).pathname.endsWith("/get-session")||new URL(g).pathname.endsWith("/sign-out"))?(await p(m),r.endSession(),s=null,i=false):(r.observe(O.headers),O.headers.has("set-auth-token")&&(i&&r.completeCookieTransport(),s=null,i=false))),O},probe:n,tokens:r,integration:Fe(t),prepareSession:l}}function pt(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=De(e.publishableKey),r=Pe(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:r,decoded:t,projectBaseURL:`${r}/api/projects/${t.projectId}/auth`}}function he(e){let t=pt(e),{fetch:r,...n}=ct({projectId:t.decoded.projectId,projectBaseURL:t.projectBaseURL,publishableKey:t.publishableKey},e.fetch);return {...e,...t,fetch:r,session:n}}function ie(e,t){return !e||!t?false:e.permissions.includes(t)}function kr(e,t){return !e||!t?false:e.teams?.includes(t)??false}function Er(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function ae(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&&!Er(e,r)||n!==void 0&&!e.permissions.includes(n)||o!==void 0&&!kr(e,o))}var ge="Authentication is required.",R=class extends Error{reason;status;cause;constructor(t,r,n){super(r),this.name="AuthorizationError",this.reason=t,this.status=t==="unauthenticated"?401:403,Object.defineProperty(this,"cause",{value:n,enumerable:false,writable:false,configurable:true});}};function Ar(e){if(typeof e!="object"||e===null)return false;let t=e;return t.name==="AuthorizationError"&&typeof t.message=="string"&&(t.reason==="unauthenticated"&&t.status===401||t.reason==="forbidden"&&t.status===403)}var Or=new Set(["TOKEN_VERIFICATION_FAILED","TOKEN_MALFORMED","TOKEN_ALGORITHM_UNSUPPORTED","TOKEN_SIGNATURE_INVALID","TOKEN_CLAIM_INVALID","TOKEN_USE_UNSUPPORTED","JWKS_KEY_NOT_FOUND"]);function Pr(e){if(typeof e!="string"||e.trim().length===0)throw new R("unauthenticated",ge);return e}function V(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`${t} needs a non-empty value.`)}async function J(e,t){let r=Pr(t),n;try{n=await e(r);}catch(o){throw o instanceof u&&Or.has(o.code)?new R("unauthenticated",ge,o):o}if(n.sub===null||n.sub.trim().length===0)throw new R("unauthenticated",ge);return n}async function dt(e,t,r){if(r.role===void 0&&r.permission===void 0&&r.teamId===void 0)throw new TypeError("requireGrant needs at least one of role, permission, or teamId.");r.role!==void 0&&V(r.role,"requireGrant role"),r.permission!==void 0&&V(r.permission,"requireGrant permission"),r.teamId!==void 0&&V(r.teamId,"requireGrant teamId");let n=await J(e,t);if(!ae(n.membership,r))throw new R("forbidden","Token does not grant the required access.");return n}async function ut(e,t,r){V(r,"requireOrg organization id");let n=await J(e,t);if(n.claims.org_id!==r)throw new R("forbidden","Token was not minted for this organization.");return n}async function lt(e,t,r){V(r,"requirePermission permission");let n=await J(e,t);if(!ie(n.membership,r))throw new R("forbidden","Token does not grant the required permission.");return n}function Ir(e,t){let r=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${r}.session_token`}var Rr="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",W={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"}}}},be={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 xr=new Set(["__proto__","constructor","prototype"]),Ur=64,vr=5e4;function mt(e,t,r){let o=W[e].responseSchemas;Object.hasOwn(o,String(t))||ce();let s=o[String(t)];if(s===null){r!==null&&ce();return}let i={nodes:0};return L(r,K(s),0,i)||ce(),r}function L(e,t,r,n){if(n.nodes+=1,r>Ur||n.nodes>vr)return false;if(typeof t.$ref=="string"){let s=Dr(t.$ref);if(s===null||!L(e,s,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(s=>L(e,K(s),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(s=>L(e,K(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=>Nr(e,s))?false:e===null?t.type===void 0||o.includes("null"):typeof e=="string"?Lr(e,t):typeof e=="number"?Kr(e,t):Array.isArray(e)?Cr(e,t,r,n):H(e)?zr(e,t,r,n):typeof e=="boolean"}function Nr(e,t){switch(t){case "null":return e===null;case "object":return H(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 Lr(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!jr(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 jr(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 Kr(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Cr(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=K(t.items);return e.every(s=>L(s,o,r+1,n))}function zr(e,t,r,n){let o=Object.keys(e);if(o.some(i=>xr.has(i))||typeof t.minProperties=="number"&&o.length<t.minProperties||typeof t.maxProperties=="number"&&o.length>t.maxProperties)return false;let s=H(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&o.some(i=>!L(i,K(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=s[i];if(p!==void 0){if(!L(a,K(p),r+1,n))return false;continue}if(t.additionalProperties===false||H(t.additionalProperties)&&!L(a,t.additionalProperties,r+1,n))return false}return true}function Dr(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(be,r)?K(be[r]):null}function K(e){return H(e)||ce(),e}function H(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function ce(){throw new TypeError("Admin API response does not match its generated contract.")}var Mr=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,$r=1024*1024,qr=1e4,F=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;}},$=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 Br(e){Vr();let t=Jr(e?.secretKey),r=Wr(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,p)=>{let l=p??{},h=W[a],b=new URL(Hr(h.path,l).replace(/^\/+/,""),r);Fr(b,l);let c=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Gr(c,l);let f="body"in l?JSON.stringify(l.body):void 0;f!==void 0&&c.set("content-type","application/json");let m;try{m=await X({fetchImpl:o,url:b,init:{method:h.method,headers:c,body:f,signal:p?.signal},timeoutMs:qr,maxResponseBytes:$r,allowHttpLoopback:r.protocol==="http:",decode:(g,O)=>mt(a,O.status,g)});}catch(g){throw g instanceof F?g:g instanceof x?new $(g.kind,g.requestId):new $("network")}let{response:w,requestId:y,data:T}=m;if(!w.ok)throw Yr(w,T,y);if(!h.successStatuses.some(g=>g===w.status))throw new $("invalid_response",y);return T},i=Object.assign(Object.create(null),{request:s});for(let a of Object.keys(W))i[a]=p=>s(a,p);return Object.freeze(i)}function Vr(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function Jr(e){if(typeof e!="string"||!Mr.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function Wr(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=Z(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 Hr(e,t){let r="path"in t&&pe(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 Fr(e,t){if(!(!("query"in t)||!pe(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 Gr(e,t){if(!(!("header"in t)||!pe(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 Yr(e,t,r){let n=r??ft(e.headers.get("x-request-id"),256),o=ft(e.headers.get("retry-after"),128),s=Zr(e.status,n),i=Xr(t)?t:s;return new F({status:e.status,code:i.code,requestId:n,problem:i,retryAfter:o})}function Zr(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 Xr(e){return pe(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 pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ft(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var Qr=/^v1=([a-f0-9]{64})$/i,en=/^whsec_[A-Za-z0-9_-]{1,256}$/,tn=/^(0|[1-9]\d{0,10})$/;async function rn(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=nn(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=sn(e.rawBody);if(o.byteLength>1048576||typeof e.timestamp!="string"||!tn.test(e.timestamp))return false;let s=Number(e.timestamp);if(!Number.isSafeInteger(s)||Math.abs(n-s)>r)return false;let i=on(e.signatureHeader);if(i.length===0)return false;let a=new TextEncoder().encode(`${e.timestamp}.`),p=new Uint8Array(a.byteLength+o.byteLength);p.set(a),p.set(o,a.byteLength);let l=false;for(let h of t){let b=await crypto.subtle.importKey("raw",new TextEncoder().encode(h),{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=new Uint8Array(await crypto.subtle.sign("HMAC",b,p));for(let f of i)l=cn(c,f)||l;}return l}function nn(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!en.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function on(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=Qr.exec(n.trim());o&&r.push(an(o[1]));}return r}function sn(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 an(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 cn(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 pn="/.well-known/oauth-protected-resource";function we(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 yt(e){let t=we(e,"resource"),r=t.pathname==="/"?"":t.pathname.replace(/\/+$/,"");return `${t.origin}${pn}${r}${t.search}`}function dn(e){if(we(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)we(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 un(e){let t=[`resource_metadata="${yt(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 ht=["publishableKey","apiUrl","issuer","jwksUri","audience"],ln=new Set([...ht,"clockToleranceSeconds","tokenUse","requireTokenUse"]);function C(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=>!ln.has(a)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(ht.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 Q({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds,tokenUse:e.tokenUse,requireTokenUse:e.requireTokenUse})}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=he({publishableKey:o,apiUrl:s});return Q({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds,tokenUse:e?.tokenUse,requireTokenUse:e?.requireTokenUse},i.decoded.env==="test")}function G(e){return {...e,tokenUse:"session"}}async function oo(e,t){return I(e,C(t))}async function so(e,t,r){let n=C(r);try{let o=await I(e,G(n));return ae(o.membership,t)}catch{return false}}async function io(e,t,r){let n=C(r);try{let o=await I(e,G(n));return ie(o.membership,t.permission)}catch{return false}}async function ao(e,t){let r=C(t);return J(n=>I(n,r),e)}async function co(e,t,r){let n=C(r);return lt(o=>I(o,G(n)),e,t)}async function po(e,t,r){let n=C(r);return dt(o=>I(o,G(n)),e,t)}async function uo(e,t,r){let n=C(r);return ut(o=>I(o,G(n)),e,t)}
2
+ exports.ADMIN_API_SPEC_SHA256=Rr;exports.AuthOwlAdminApiError=F;exports.AuthOwlAdminNetworkError=$;exports.AuthorizationError=R;exports.SESSION_TRANSPORT_BEARER=fe;exports.SESSION_TRANSPORT_HEADER=me;exports.TokenVerificationError=u;exports.createAdminClient=Br;exports.has=so;exports.hasPermission=io;exports.isAuthorizationError=Ar;exports.mcpProtectedResourceMetadata=dn;exports.mcpProtectedResourceMetadataUrl=yt;exports.mcpUnauthorizedChallenge=un;exports.requireAuth=ao;exports.requireGrant=po;exports.requireOrg=uo;exports.requirePermission=co;exports.resolveAuthTarget=pt;exports.resolveConfig=he;exports.sessionCookieName=Ir;exports.verifyProjectToken=Ht;exports.verifyToken=oo;exports.verifyWebhook=rn;
package/dist/server.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-BIify9hZ.cjs';
2
- export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, h as resolveAuthTarget, r as resolveConfig } from './organization-membership-BIify9hZ.cjs';
1
+ import { l as OrganizationMembership, bg as TransportErrorKind, H as HasParams } from './config-CyUwyJ9B.cjs';
2
+ export { f as AuthConfig, R as ResolvedAuthConfig, b1 as ResolvedAuthTarget, bO as resolveAuthTarget, B as resolveConfig } from './config-CyUwyJ9B.cjs';
3
3
  export { s as sessionCookieName } from './cookie-BqcfagTw.cjs';
4
4
  export { a as SESSION_TRANSPORT_BEARER, b as SESSION_TRANSPORT_HEADER } from './session-transport-contract-HDPYRum8.cjs';
5
5
 
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-BIify9hZ.js';
2
- export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, h as resolveAuthTarget, r as resolveConfig } from './organization-membership-BIify9hZ.js';
1
+ import { l as OrganizationMembership, bg as TransportErrorKind, H as HasParams } from './config-CyUwyJ9B.js';
2
+ export { f as AuthConfig, R as ResolvedAuthConfig, b1 as ResolvedAuthTarget, bO as resolveAuthTarget, B as resolveConfig } from './config-CyUwyJ9B.js';
3
3
  export { s as sessionCookieName } from './cookie-BqcfagTw.js';
4
4
  export { a as SESSION_TRANSPORT_BEARER, b as SESSION_TRANSPORT_HEADER } from './session-transport-contract-HDPYRum8.js';
5
5