@authowl/core 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/dist/chunk-M4QJVSXT.js +1 -0
- package/dist/chunk-VZTAYWAD.js +1 -0
- package/dist/client-DOOkDLWg.d.cts +1322 -0
- package/dist/client-jpaYv3wu.d.ts +1322 -0
- package/dist/index-hIdXOzRp.d.cts +15 -0
- package/dist/index-hIdXOzRp.d.ts +15 -0
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +11 -1260
- package/dist/index.d.ts +11 -1260
- package/dist/index.js +3 -3
- package/dist/messages.cjs +1 -0
- package/dist/messages.d.cts +474 -0
- package/dist/messages.d.ts +474 -0
- package/dist/messages.js +1 -0
- package/dist/native.cjs +1 -0
- package/dist/native.d.cts +149 -0
- package/dist/native.d.ts +149 -0
- package/dist/native.js +1 -0
- package/dist/{transport-BObDKlIh.d.cts → organization-membership-B3m6PbmO.d.cts} +1 -15
- package/dist/{transport-BObDKlIh.d.ts → organization-membership-B3m6PbmO.d.ts} +1 -15
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +897 -54
- package/dist/server.d.ts +897 -54
- package/dist/server.js +1 -1
- package/dist/transport-DcWDTRd4.d.cts +15 -0
- package/dist/transport-DcWDTRd4.d.ts +15 -0
- package/package.json +25 -2
package/dist/native.d.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { R as ResolvedAuthConfig, A as AuthConfig } from './organization-membership-B3m6PbmO.js';
|
|
2
|
+
export { D as DecodedPublishableKey, H as HasParams, O as OrganizationMembership, c as createMembershipHas, d as decodePublishableKey, r as resolveConfig, s as sessionCookieName } from './organization-membership-B3m6PbmO.js';
|
|
3
|
+
import { k as AuthOwlClient, aL as SocialIdTokenOptions, bd as createAuthHttpClient, be as AuthHttpClient, al as PasskeySignInOptions, f as ActionFetchOptions, h as AuthActionResult, ak as PasskeyAuthData, g as AddPasskeyOptions, m as AuthPasskey } from './client-jpaYv3wu.js';
|
|
4
|
+
export { i as AuthClientError, p as AuthSession, q as AuthUser, a4 as Organization, a5 as OrganizationClient, a6 as OrganizationDetails, as as ProjectCapabilities, at as PublicConfig, aE as SessionState, aF as SessionStore, aG as SetActiveOrganizationOptions, aK as SocialAuthData, bb as getPublicConfig, bc as resolveProjectCapabilities } from './client-jpaYv3wu.js';
|
|
5
|
+
import { startAuthentication, startRegistration } from '@simplewebauthn/browser';
|
|
6
|
+
|
|
7
|
+
type AuthActionClient = Omit<AuthOwlClient, 'getToken' | 'getConsentStatus' | 'acceptConsent' | 'waitlist'>;
|
|
8
|
+
/** Native social sign-in uses an ID token obtained from the provider SDK. */
|
|
9
|
+
interface NativeSocialSignInOptions {
|
|
10
|
+
provider: string;
|
|
11
|
+
idToken: SocialIdTokenOptions;
|
|
12
|
+
requestSignUp?: boolean;
|
|
13
|
+
}
|
|
14
|
+
type NativeSignInClient = Omit<AuthActionClient['signIn'], 'social' | 'sso' | 'passkey'> & {
|
|
15
|
+
social(params: NativeSocialSignInOptions, fetchOptions?: Parameters<AuthActionClient['signIn']['social']>[1]): ReturnType<AuthActionClient['signIn']['social']>;
|
|
16
|
+
};
|
|
17
|
+
type NativePasskeyClient = Omit<AuthActionClient['passkey'], 'addPasskey'>;
|
|
18
|
+
interface PasskeyCeremonyClient {
|
|
19
|
+
signIn: AuthActionClient['signIn']['passkey'];
|
|
20
|
+
add: AuthActionClient['passkey']['addPasskey'];
|
|
21
|
+
}
|
|
22
|
+
type PasskeyCeremonyClientFactory = (http: ReturnType<typeof createAuthHttpClient>, sessionChanged: () => void) => PasskeyCeremonyClient;
|
|
23
|
+
/**
|
|
24
|
+
* Auth actions that can execute without browser navigation or WebAuthn.
|
|
25
|
+
*
|
|
26
|
+
* Social sign-in requires a provider ID token. Redirect OAuth, enterprise SSO,
|
|
27
|
+
* passkey sign-in, and passkey registration need browser state or WebAuthn and
|
|
28
|
+
* are deliberately absent from the native surface.
|
|
29
|
+
*/
|
|
30
|
+
type NativeAuthClient = Omit<AuthActionClient, 'signIn' | 'passkey'> & {
|
|
31
|
+
signIn: NativeSignInClient;
|
|
32
|
+
passkey: NativePasskeyClient;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* A native client whose host supplied a platform passkey ceremony.
|
|
36
|
+
*
|
|
37
|
+
* The passkey methods appear in the TYPE only when an adapter is passed, so an
|
|
38
|
+
* app without one cannot call a ceremony that would fail at runtime.
|
|
39
|
+
*/
|
|
40
|
+
type NativePasskeyCapableClient = Omit<NativeAuthClient, 'passkey' | 'signIn'> & {
|
|
41
|
+
passkey: NativePasskeyClient & Pick<AuthActionClient['passkey'], 'addPasskey'>;
|
|
42
|
+
signIn: NativeSignInClient & Pick<AuthActionClient['signIn'], 'passkey'>;
|
|
43
|
+
};
|
|
44
|
+
/** Build the runtime-native subset without leaving browser-only methods reachable. */
|
|
45
|
+
declare function createNativeAuthClient(config: ResolvedAuthConfig, onSessionMutation?: () => void): NativeAuthClient;
|
|
46
|
+
declare function createNativeAuthClient(config: ResolvedAuthConfig, onSessionMutation: (() => void) | undefined, createPasskeys: PasskeyCeremonyClientFactory): NativePasskeyCapableClient;
|
|
47
|
+
|
|
48
|
+
type AuthenticationOptions = Parameters<typeof startAuthentication>[0]['optionsJSON'];
|
|
49
|
+
type RegistrationOptions = Parameters<typeof startRegistration>[0]['optionsJSON'];
|
|
50
|
+
declare function decodeAuthenticationOptions(value: unknown): AuthenticationOptions;
|
|
51
|
+
declare function decodeRegistrationOptions(value: unknown): RegistrationOptions;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The two ceremony responses, as the server expects to receive them.
|
|
55
|
+
*
|
|
56
|
+
* Kept distinct: an assertion carries `authenticatorData`, an attestation
|
|
57
|
+
* carries `attestationObject`, and collapsing them into one type would let a
|
|
58
|
+
* registration response be posted to the authentication endpoint.
|
|
59
|
+
*/
|
|
60
|
+
type PasskeyRegistrationResponse = {
|
|
61
|
+
id: string;
|
|
62
|
+
rawId: string;
|
|
63
|
+
type: 'public-key';
|
|
64
|
+
response: {
|
|
65
|
+
clientDataJSON: string;
|
|
66
|
+
attestationObject: string;
|
|
67
|
+
transports?: string[];
|
|
68
|
+
publicKeyAlgorithm?: number;
|
|
69
|
+
publicKey?: string;
|
|
70
|
+
};
|
|
71
|
+
clientExtensionResults?: unknown;
|
|
72
|
+
authenticatorAttachment?: string;
|
|
73
|
+
};
|
|
74
|
+
type PasskeyAuthenticationResponse = {
|
|
75
|
+
id: string;
|
|
76
|
+
rawId: string;
|
|
77
|
+
type: 'public-key';
|
|
78
|
+
response: {
|
|
79
|
+
clientDataJSON: string;
|
|
80
|
+
authenticatorData: string;
|
|
81
|
+
signature: string;
|
|
82
|
+
userHandle?: string;
|
|
83
|
+
};
|
|
84
|
+
clientExtensionResults?: unknown;
|
|
85
|
+
authenticatorAttachment?: string;
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Runs the platform's WebAuthn ceremonies.
|
|
89
|
+
*
|
|
90
|
+
* Injected so a non-browser runtime can supply its own. React Native has no
|
|
91
|
+
* `navigator.credentials`, but it does have platform passkey APIs
|
|
92
|
+
* (`ASAuthorization` on iOS, Credential Manager on Android) whose libraries
|
|
93
|
+
* speak the same WebAuthn JSON. Parameterizing only the ceremony lets those
|
|
94
|
+
* runtimes reuse every line of option decoding, response projection, and
|
|
95
|
+
* in-flight de-duplication below, instead of reimplementing the protocol.
|
|
96
|
+
*/
|
|
97
|
+
interface PasskeyCeremony {
|
|
98
|
+
authenticate(input: {
|
|
99
|
+
optionsJSON: ReturnType<typeof decodeAuthenticationOptions>;
|
|
100
|
+
useBrowserAutofill?: boolean;
|
|
101
|
+
}): Promise<PasskeyAuthenticationResponse>;
|
|
102
|
+
register(input: {
|
|
103
|
+
optionsJSON: ReturnType<typeof decodeRegistrationOptions>;
|
|
104
|
+
}): Promise<PasskeyRegistrationResponse>;
|
|
105
|
+
/**
|
|
106
|
+
* Classify a ceremony failure, returning the platform's error code.
|
|
107
|
+
*
|
|
108
|
+
* Supplied by the ceremony because only it knows its own error type. The
|
|
109
|
+
* browser implementation tests `instanceof WebAuthnError`; doing that here
|
|
110
|
+
* would require importing the browser helper into this module, and a
|
|
111
|
+
* structural stand-in cannot work - a real WebAuthnError takes its `name`
|
|
112
|
+
* from the underlying cause, not from the class.
|
|
113
|
+
*/
|
|
114
|
+
errorCode?(error: unknown): string | undefined;
|
|
115
|
+
}
|
|
116
|
+
declare function createPasskeyClient(http: AuthHttpClient, sessionChanged: () => void, ceremony: PasskeyCeremony): {
|
|
117
|
+
signIn(options?: PasskeySignInOptions, fetchOptions?: ActionFetchOptions): Promise<AuthActionResult<PasskeyAuthData>>;
|
|
118
|
+
add(options?: AddPasskeyOptions, fetchOptions?: ActionFetchOptions): Promise<AuthActionResult<AuthPasskey>>;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Native (React Native / Expo) entry point.
|
|
123
|
+
*
|
|
124
|
+
* The browser client relies on the browser's cookie jar, `BroadcastChannel`, and
|
|
125
|
+
* `window.location` redirects - none of which exist on a phone. This entry
|
|
126
|
+
* exposes the native-safe auth surface built on `createNativeAuthClient`, which
|
|
127
|
+
* drops browser navigation and WebAuthn ceremonies, and leaves session storage
|
|
128
|
+
* to the caller:
|
|
129
|
+
*
|
|
130
|
+
* 1. WHERE the session lives. Pass a `fetch` that persists and replays the
|
|
131
|
+
* session cookie from secure storage (`@authowl/react-native` supplies one).
|
|
132
|
+
*
|
|
133
|
+
* Social providers are supported through ID tokens obtained from their native
|
|
134
|
+
* SDKs. Redirect OAuth cannot share state cookies with this client-side jar.
|
|
135
|
+
*
|
|
136
|
+
* Kept separate from `./index` so a React Native bundler never pulls the
|
|
137
|
+
* browser-only modules into an app that cannot use them.
|
|
138
|
+
*/
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Build a native auth client from a publishable key and API URL.
|
|
142
|
+
*
|
|
143
|
+
* `config.fetch` is the seam a native app must use to persist its session:
|
|
144
|
+
* without one, requests fall back to whatever cookie behaviour the platform's
|
|
145
|
+
* `fetch` happens to have, which does not survive an app restart.
|
|
146
|
+
*/
|
|
147
|
+
declare function createNativeClient(config: AuthConfig, onSessionMutation?: () => void): NativeAuthClient;
|
|
148
|
+
|
|
149
|
+
export { AddPasskeyOptions, AuthActionResult, AuthConfig, AuthOwlClient, AuthPasskey, type NativeAuthClient, type NativePasskeyCapableClient, type NativeSocialSignInOptions, PasskeyAuthData, type PasskeyAuthenticationResponse, type PasskeyCeremony, type PasskeyCeremonyClientFactory, type PasskeyRegistrationResponse, ResolvedAuthConfig, SocialIdTokenOptions, createNativeAuthClient, createNativeClient, createPasskeyClient };
|
package/dist/native.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {f}from'./chunk-VZTAYWAD.js';export{f as createNativeAuthClient,g as createPasskeyClient,k as getPublicConfig,a as resolveProjectCapabilities}from'./chunk-VZTAYWAD.js';import {e}from'./chunk-KPXCQZUX.js';export{v as createMembershipHas,a as decodePublishableKey,e as resolveConfig,b as sessionCookieName}from'./chunk-KPXCQZUX.js';function u(i,o){return f(e(i),o)}export{u as createNativeClient};
|
|
@@ -114,18 +114,4 @@ declare function createMembershipHas(membership: OrganizationMembership | null |
|
|
|
114
114
|
}) => boolean;
|
|
115
115
|
};
|
|
116
116
|
|
|
117
|
-
type
|
|
118
|
-
/**
|
|
119
|
-
* Stable, secret-safe failure from the shared HTTP boundary.
|
|
120
|
-
*
|
|
121
|
-
* Deliberately does not retain the request URL, headers, body, or underlying
|
|
122
|
-
* error. Server clients may carry secret authorization headers and hostile
|
|
123
|
-
* fetch implementations may echo those values in their error messages.
|
|
124
|
-
*/
|
|
125
|
-
declare class TransportError extends Error {
|
|
126
|
-
readonly kind: TransportErrorKind;
|
|
127
|
-
readonly requestId?: string;
|
|
128
|
-
constructor(kind: TransportErrorKind, requestId?: string);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export { type AuthConfig as A, type DecodedPublishableKey as D, type HasParams as H, type OrganizationMembership as O, type ResolvedAuthConfig as R, TransportError as T, type TransportErrorKind as a, membershipHasPermission as b, createMembershipHas as c, decodePublishableKey as d, membershipHasTeam as e, membershipHas as m, resolveConfig as r, sessionCookieName as s };
|
|
117
|
+
export { type AuthConfig as A, type DecodedPublishableKey as D, type HasParams as H, type OrganizationMembership as O, type ResolvedAuthConfig as R, membershipHasPermission as a, membershipHasTeam as b, createMembershipHas as c, decodePublishableKey as d, membershipHas as m, resolveConfig as r, sessionCookieName as s };
|
|
@@ -114,18 +114,4 @@ declare function createMembershipHas(membership: OrganizationMembership | null |
|
|
|
114
114
|
}) => boolean;
|
|
115
115
|
};
|
|
116
116
|
|
|
117
|
-
type
|
|
118
|
-
/**
|
|
119
|
-
* Stable, secret-safe failure from the shared HTTP boundary.
|
|
120
|
-
*
|
|
121
|
-
* Deliberately does not retain the request URL, headers, body, or underlying
|
|
122
|
-
* error. Server clients may carry secret authorization headers and hostile
|
|
123
|
-
* fetch implementations may echo those values in their error messages.
|
|
124
|
-
*/
|
|
125
|
-
declare class TransportError extends Error {
|
|
126
|
-
readonly kind: TransportErrorKind;
|
|
127
|
-
readonly requestId?: string;
|
|
128
|
-
constructor(kind: TransportErrorKind, requestId?: string);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export { type AuthConfig as A, type DecodedPublishableKey as D, type HasParams as H, type OrganizationMembership as O, type ResolvedAuthConfig as R, TransportError as T, type TransportErrorKind as a, membershipHasPermission as b, createMembershipHas as c, decodePublishableKey as d, membershipHasTeam as e, membershipHas as m, resolveConfig as r, sessionCookieName as s };
|
|
117
|
+
export { type AuthConfig as A, type DecodedPublishableKey as D, type HasParams as H, type OrganizationMembership as O, type ResolvedAuthConfig as R, membershipHasPermission as a, membershipHasTeam as b, createMembershipHas as c, decodePublishableKey as d, membershipHas as m, resolveConfig as r, sessionCookieName as s };
|
package/dist/server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var me=new Set(["__proto__","constructor","prototype"]);function S(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function V(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&S(),le(e,t,n)}function le(e,t=20,n=1e4){return N(e,0,{nodes:0},t,n)}function N(e,t,n,r,o){if(n.nodes+=1,(t>r||n.nodes>o)&&S(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||S(),e;if(Array.isArray(e))return e.map(c=>N(c,t+1,n,r,o));(!e||typeof e!="object")&&S();let s=Object.getPrototypeOf(e);s!==Object.prototype&&s!==null&&S();let i={};for(let[c,d]of Object.entries(e))me.has(c)&&S(),i[c]=N(d,t+1,n,r,o);return i}var C=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function b(e,t){throw new Error(`${e}: ${t}`)}function fe(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function q(e,{label:t,allowHttpLoopback:n}){(typeof e!="string"||e.length===0)&&b(t,"required"),e!==e.trim()&&b(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&b(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&b(t,"path must be unencoded");let r;try{r=new URL(e);}catch{b(t,"absolute URL required");}return (r.username||r.password)&&b(t,"credentials forbidden"),r.protocol!=="https:"&&r.protocol!=="http:"&&b(t,"HTTPS required"),r.protocol==="http:"&&(!n||!C.test(e))&&b(t,"HTTPS required except exact loopback"),r}function L(e,t){let n;try{n=new URL(String(e));}catch{throw new TypeError("Transport URL must be absolute.")}if(n.username||n.password||n.hash)throw new TypeError("Transport URL must not contain credentials or a fragment.");let r=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&C.test(r)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function B(e,t,n){let r=fe(e);(r.includes("//")||r.split("/").some(o=>o==="."||o==="..")||r!==""&&r!==t.pathname)&&b(n,"path traversal or duplicate separator");}function H(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&b("apiUrl","origin required");let n;try{n=new URL(e);}catch{b("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!C.test(e))&&b("apiUrl","HTTPS required except exact loopback"),n.origin}function F(e,t,n={allowHttpLoopback:false}){let r=q(e,{label:"issuer",allowHttpLoopback:n.allowHttpLoopback}),o=q(t,{label:"jwksUri",allowHttpLoopback:n.allowHttpLoopback});return B(e,r,"issuer"),B(t,o,"jwksUri"),r.pathname!=="/"&&r.pathname.endsWith("/")&&b("issuer","trailing slash forbidden"),{issuer:r.toString().replace(/\/$/,""),jwksUri:o.toString()}}var ye=1e4,he=1024*1024,A=class extends Error{kind;requestId;constructor(t,n){super(Oe(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},X=new WeakSet;function y(e,t){let n=new A(e,t);return X.add(n),n}async function j({fetchImpl:e,url:t,init:n={},timeoutMs:r=ye,maxResponseBytes:o=he,allowHttpLoopback:s=false,decode:i}){Y(r,"timeoutMs"),Y(o,"maxResponseBytes");let c=L(t,{allowHttpLoopback:s}),d=n.signal,u=new AbortController,m=null,g,p=new Promise(l=>{g=l;}),w=l=>{m===null&&(m=l,g({type:"abort",kind:l}),u.abort());},h=()=>w("aborted");d?.addEventListener("abort",h,{once:true});let _=setTimeout(()=>w("timeout"),r);d?.aborted&&h();try{if(m!==null)throw y(m);let l;try{l=await Promise.race([e(c.toString(),{...n,redirect:"error",signal:u.signal}).then(ue=>({type:"response",response:ue})),p]);}catch{throw y(m??"network")}if(l.type==="abort")throw y(l.kind);if(!ge(l.response))throw y("invalid_response");let f=l.response,k=Se(f.headers),de=await be(f,o,p,()=>m,k),W=_e(f,de,k),J;try{J=f.ok&&i?i(W,Object.freeze({status:f.status})):W;}catch{throw y("invalid_response",k)}return {response:f,data:J,...k===void 0?{}:{requestId:k}}}catch(l){throw l instanceof A&&X.has(l)?l:y(m??"network")}finally{clearTimeout(_),d?.removeEventListener("abort",h);}}function ge(e){if(!e||typeof e!="object")return false;let t=e;return Number.isInteger(t.status)&&t.status>=0&&t.status<=599&&typeof t.statusText=="string"&&typeof t.ok=="boolean"&&typeof t.headers?.get=="function"&&(t.body===null||typeof t.body=="object"&&typeof t.body?.getReader=="function"&&typeof t.body.cancel=="function")}async function be(e,t,n,r,o){let s=e.headers.get("content-length");if(s!==null){if(!/^\d+$/.test(s))throw G(e.body),y("invalid_response",o);if(Number(s)>t)throw G(e.body),y("response_too_large",o)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw y("network",o)}let c=[],d=0,u=null;try{for(;;){let p;try{p=await Promise.race([i.read(),n]);}catch{u=y(r()??"network",o);break}if(we(p)){u=y(p.kind,o);break}let{done:w,value:h}=p;if(w)break;if(h.byteLength!==0){if(d+=h.byteLength,d>t){u=y("response_too_large",o);break}c.push(h);}}}finally{u&&Ae(i);try{i.releaseLock();}catch{}}if(u)throw u;let m=new Uint8Array(d),g=0;for(let p of c)m.set(p,g),g+=p.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(m)}catch{throw y("invalid_response",o)}}function we(e){return "type"in e&&e.type==="abort"}function G(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function Ae(e){try{e.cancel().catch(()=>{});}catch{}}function _e(e,t,n){if(e.status===204||e.status===205)return null;let r=ke(e.headers.get("content-type"));if(!e.ok&&(!r||t.length===0))return null;if(!r||t.length===0)throw y("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw y("invalid_response",n)}}function ke(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function Se(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Y(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Oe(e){switch(e){case "aborted":return "The request was cancelled.";case "timeout":return "The request timed out.";case "response_too_large":return "The response exceeded the allowed size.";case "invalid_response":return "The service returned an invalid response.";case "network":return "The network request could not be completed."}}var a=class extends Error{code;constructor(t,n="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=n;}},Te=300*1e3,Ee=5e3,Ie=64*1024,Pe=64,xe=60*1e3,Z=new Map,Q=new Map;function z(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?t:t+"=".repeat(4-t.length%4),r=typeof atob=="function"?atob(n):globalThis.Buffer.from(n,"base64").toString("binary"),o=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}function ee(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(z(e)),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");return n}catch(t){throw t instanceof a?t:new a("Malformed JWT segment.","TOKEN_MALFORMED")}}function re(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function te(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&z(e).byteLength===32}function Re(e){if(!re(e))throw new a("JWKS contains a non-object key.","JWKS_KEY_INVALID");let t=new Set(["alg","crv","kid","kty","use","x","y"]),n=["d","p","q","dp","dq","qi","k","oth"];if("key_ops"in e||n.some(r=>r in e)||Object.keys(e).some(r=>!t.has(r)))throw new a("JWKS contains private, key_ops, or unexpected key members.","JWKS_KEY_INVALID");if(e.kty!=="EC"||e.crv!=="P-256"||e.alg!=="ES256"||e.use!=="sig"||typeof e.kid!="string"||e.kid.length===0||e.kid.length>128||!/^[A-Za-z0-9_-]+$/.test(e.kid)||!te(e.x)||!te(e.y))throw new a("JWKS contains a key outside the AuthOwl ES256 public-key schema.","JWKS_KEY_INVALID");return {alg:e.alg,crv:e.crv,kid:e.kid,kty:e.kty,use:e.use,x:e.x,y:e.y}}function Le(e){if(!re(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new a("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>Pe)throw new a("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(Re),n=new Set;for(let r of t){if(n.has(r.kid))throw new a("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");n.add(r.kid);}return t}async function ne(e,t){let n=Z.get(e);if(!t&&n&&Date.now()-n.fetchedAt<Te)return n.keys;try{let r=await j({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Ee,maxResponseBytes:Ie,allowHttpLoopback:new URL(e).protocol==="http:",decode:s=>V(s)});if(!r.response.ok)throw new a(`JWKS fetch returned ${r.response.status}.`,"JWKS_HTTP_ERROR");let o=Le(r.data);return Z.set(e,{keys:o,fetchedAt:Date.now()}),o}catch(r){if(r instanceof a)throw r;if(r instanceof A)switch(r.kind){case "timeout":throw new a("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new a("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new a("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new a("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function je(e,t){let n=o=>t?o.find(s=>s.kid===t):o[0],r=n(await ne(e,false));if(!r){let o=Q.get(e)??0;Date.now()-o>=xe&&(Q.set(e,Date.now()),r=n(await ne(e,true)));}if(!r)throw new a("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return r}function Ue(e){let t=globalThis.crypto?.subtle;if(!t)throw new a("WebCrypto is unavailable in this runtime.","WEBCRYPTO_UNAVAILABLE");return t.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y},{name:"ECDSA",namedCurve:"P-256"},false,["verify"])}function Ke(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function Ne(e){let t=e.membership;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,r=typeof n.role=="string"?n.role:"",o=Array.isArray(n.permissions)?n.permissions.filter(i=>typeof i=="string"):[],s=Array.isArray(n.teams)?n.teams.filter(i=>typeof i=="string"):void 0;return r===""&&o.length===0&&!s?.length?null:{role:r,permissions:o,...s===void 0?{}:{teams:s}}}async function Ce(e,t){return E(e,U(t))}function U(e,t=false){if(!e||typeof e!="object")throw new a("Token verification options are required.","TOKEN_CONFIG_INVALID");let n;try{n=F(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new a("Token verifier issuer or JWKS URL is invalid.","TOKEN_CONFIG_INVALID")}if(typeof e.audience!="string"||e.audience.length===0||e.audience.length>256)throw new a("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new a("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...n}}async function E(e,t){if(typeof e!="string"||e.length===0)throw new a("A token string is required.","TOKEN_MALFORMED");let n=e.split(".");if(n.length!==3)throw new a("Malformed JWT.","TOKEN_MALFORMED");let[r,o,s]=n,i=ee(r);if(i.alg!=="ES256")throw new a("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let c=await je(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),d;try{d=await Ue(c);}catch(_){throw _ instanceof a?_:new a("JWKS key could not be imported.","JWKS_KEY_INVALID")}let u;try{if(!/^[A-Za-z0-9_-]{86}$/.test(s))throw new Error("invalid signature encoding");if(u=z(s),u.byteLength!==64)throw new Error("invalid signature length")}catch{throw new a("Malformed JWT signature.","TOKEN_MALFORMED")}let m=new TextEncoder().encode(`${r}.${o}`),g;try{g=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,u,m);}catch{throw new a("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!g)throw new a("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let p=ee(o),w=t.clockToleranceSeconds??60,h=Math.floor(Date.now()/1e3);if(typeof p.exp!="number")throw new a("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(p.exp+w<h)throw new a("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof p.nbf=="number"&&p.nbf-w>h)throw new a("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof p.iss!="string"||p.iss!==t.issuer)throw new a("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!Ke(p.aud,t.audience))throw new a("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof p.sub=="string"?p.sub:null,membership:Ne(p),claims:p}}var ze=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,ve=/^sk_/i;function oe(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(ve.test(e))throw new Error("A secret key was passed where a publishable key was expected. Never embed secret keys in client code.");let t=ze.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1],env:t[2],projectId:t[3]}}function v(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=oe(e.publishableKey),n=H(e.apiUrl,{allowHttpLoopback:t.env==="test"}),r=`${n}/api/projects/${t.projectId}/auth`;return {...e,apiUrl:n,decoded:t,projectBaseURL:r}}function se(e,t){return !e||!t?false:e.permissions.includes(t)}function Me(e,t){return !e||!t?false:e.teams?.includes(t)??false}function ie(e,t){if(!e)return false;let{role:n,permission:r,teamId:o}=t;return !(n===void 0&&r===void 0&&o===void 0||n!==void 0&&e.role!==n||r!==void 0&&!e.permissions.includes(r)||o!==void 0&&!Me(e,o))}function $e(e,t){let n=`p_${e.replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}var De="dc1953d9d9b9e1f7002fa045f12788280e5865bacfda94b1d133e9580aa87d62",I={getOpenApiDocument:{method:"GET",path:"/openapi.json",successStatuses:[200],responseSchemas:{200:{type:"object"}}},listUsers:{method:"GET",path:"/users",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserPage"}}},createUser:{method:"POST",path:"/users",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/User"}}},startUserExport:{method:"POST",path:"/users/export",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getUser:{method:"GET",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},updateUser:{method:"PATCH",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},deleteUser:{method:"DELETE",path:"/users/{userId}",successStatuses:[204],responseSchemas:{204:null}},listUserSessions:{method:"GET",path:"/users/{userId}/sessions",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionPage"}}},revokeUserSessions:{method:"DELETE",path:"/users/{userId}/sessions",successStatuses:[204],responseSchemas:{204:null}},updateUserMetadata:{method:"PATCH",path:"/users/{userId}/metadata",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserMetadata"}}},verifySession:{method:"POST",path:"/sessions/verify",successStatuses:[200],responseSchemas:{200:{type:"object",required:["user","session"],properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}},getSession:{method:"GET",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Session"}}},updateSessionMetadata:{method:"PATCH",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionMetadata"}}},revokeSession:{method:"DELETE",path:"/sessions/{sessionId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizations:{method:"GET",path:"/organizations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationPage"}}},createOrganization:{method:"POST",path:"/organizations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Organization"}}},getOrganization:{method:"GET",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},updateOrganization:{method:"PATCH",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},deleteOrganization:{method:"DELETE",path:"/organizations/{organizationId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationMembers:{method:"GET",path:"/organizations/{organizationId}/members",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MemberPage"}}},addOrganizationMember:{method:"POST",path:"/organizations/{organizationId}/members",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationMember"}}},updateOrganizationMember:{method:"PATCH",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationMember"}}},removeOrganizationMember:{method:"DELETE",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationRoles:{method:"GET",path:"/organizations/{organizationId}/roles",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/RolePage"}}},createOrganizationRole:{method:"POST",path:"/organizations/{organizationId}/roles",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationRole"}}},updateOrganizationRole:{method:"PATCH",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationRole"}}},deleteOrganizationRole:{method:"DELETE",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[204],responseSchemas:{204:null}},listInvitations:{method:"GET",path:"/invitations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/InvitationPage"}}},createInvitation:{method:"POST",path:"/invitations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Invitation"}}},getInvitation:{method:"GET",path:"/invitations/{invitationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Invitation"}}},revokeInvitation:{method:"DELETE",path:"/invitations/{invitationId}",successStatuses:[204],responseSchemas:{204:null}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},M={Problem:{type:"object",required:["type","title","status","detail","instance","code"],properties:{type:{type:"string",format:"uri"},title:{type:"string"},status:{type:"integer"},detail:{type:"string"},instance:{type:"string",format:"uri"},code:{type:"string"}},additionalProperties:true},User:{type:"object",required:["id","email","phone","name","image","email_verified","banned","public_metadata","private_metadata","unsafe_metadata","metadata_version","created_at","updated_at"],properties:{id:{type:"string"},email:{type:"string",format:"email"},phone:{type:["string","null"]},name:{type:["string","null"]},image:{type:["string","null"],format:"uri"},email_verified:{type:"boolean"},banned:{type:"boolean"},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateUser:{type:"object",required:["email"],properties:{email:{type:"string",format:"email",maxLength:320},password:{type:"string",minLength:8,maxLength:128},name:{type:"string",minLength:1,maxLength:200},phone:{type:"string",minLength:1,maxLength:32}},additionalProperties:false},UpdateUser:{type:"object",minProperties:1,properties:{email:{type:"string",format:"email",maxLength:320},name:{type:["string","null"],minLength:1,maxLength:200},phone:{type:["string","null"],minLength:1,maxLength:32},banned:{type:"boolean"}},additionalProperties:false},MetadataObject:{type:"object",maxProperties:100,description:"JSON metadata object. Reserved prototype keys and the authowl_ prefix are rejected at every depth. Encoded object size is limited to 8192 bytes.",additionalProperties:true},UserMetadata:{type:"object",required:["public_metadata","private_metadata","unsafe_metadata","metadata_version"],properties:{public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateUserMetadata:{type:"object",required:["expected_version"],minProperties:2,properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Session:{type:"object",required:["id","user_id","expires_at","created_at","metadata","metadata_version"],properties:{id:{type:"string"},user_id:{type:"string"},expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},ip_address:{type:["string","null"]},user_agent:{type:["string","null"]},metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},SessionMetadata:{type:"object",required:["metadata","metadata_version"],properties:{metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateSessionMetadata:{type:"object",required:["expected_version","metadata"],properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Organization:{type:"object",required:["id","name","slug","created_at"],properties:{id:{type:"string"},name:{type:"string"},slug:{type:"string"},logo:{type:["string","null"],format:"uri"},metadata:{type:["object","null"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateOrganization:{type:"object",required:["name","slug"],properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:"string",format:"uri",maxLength:2048},metadata:{type:"object"}},additionalProperties:false},UpdateOrganization:{type:"object",minProperties:1,properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:["string","null"],format:"uri",maxLength:2048},metadata:{type:["object","null"]}},additionalProperties:false},OrganizationMember:{type:"object",required:["organization_id","user_id","role","created_at"],properties:{organization_id:{type:"string"},user_id:{type:"string"},role:{type:"string"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},AddMember:{type:"object",required:["user_id","role"],properties:{user_id:{type:"string"},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},OrganizationRole:{type:"object",required:["id","organization_id","name","permissions"],properties:{id:{type:"string"},organization_id:{type:"string"},name:{type:"string"},permissions:{type:"array",items:{$ref:"#/components/schemas/OrganizationPermissionId"}}},additionalProperties:false},OrganizationPermissionId:{type:"string",enum:["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","team:create","team:update","team:delete","ac:create","ac:read","ac:update","ac:delete"]},RoleInput:{type:"object",required:["name","permissions"],properties:{name:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9_-]*$"},permissions:{type:"array",maxItems:100,items:{$ref:"#/components/schemas/OrganizationPermissionId"},uniqueItems:true}},additionalProperties:false},Invitation:{type:"object",required:["id","organization_id","email","role","status","expires_at"],properties:{id:{type:"string"},organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100},status:{type:"string"},expires_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateInvitation:{type:"object",required:["organization_id","email","role"],properties:{organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},Event:{type:"object",required:["id","type","status","created_at"],properties:{id:{type:"string"},type:{type:"string"},status:{type:"string"},user_id:{type:["string","null"]},metadata:{type:"object"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},StatsOverview:{type:"object",required:["users_total","monthly_active_users","recent_sign_ins"],properties:{users_total:{type:"integer",minimum:0},monthly_active_users:{type:"integer",minimum:0},recent_sign_ins:{type:"integer",minimum:0}},additionalProperties:false},WebhookInput:{type:"object",required:["url","events"],properties:{url:{type:"string",format:"uri",maxLength:2048},description:{type:"string",maxLength:500},events:{type:"array",minItems:1,maxItems:20,items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"},uniqueItems:true}},additionalProperties:false},WebhookSubscriptionEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset"]},WebhookEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","webhook.test"]},WebhookEndpoint:{type:"object",required:["id","url","events","status","created_at","updated_at"],properties:{id:{type:"string",format:"uuid"},url:{type:"string",format:"uri"},description:{type:["string","null"]},events:{type:"array",items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"}},status:{type:"string",enum:["active","paused","auto_paused"]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookSecret:{type:"object",required:["secret","overlap_expires_at"],properties:{secret:{type:"string"},overlap_expires_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookWithSecret:{type:"object",required:["endpoint","secret"],properties:{endpoint:{$ref:"#/components/schemas/WebhookEndpoint"},secret:{type:"string"}},additionalProperties:false},WebhookDelivery:{type:"object",required:["id","event_id","attempt_id","attempt_number","webhook_id","event_type","status","response_status","response_body","error_code","created_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},event_id:{type:"string",format:"uuid"},attempt_id:{type:"string",format:"uuid"},attempt_number:{type:"integer",minimum:1},webhook_id:{type:"string",format:"uuid"},event_type:{$ref:"#/components/schemas/WebhookEventType"},status:{type:"string",enum:["queued","delivering","succeeded","failed"]},response_status:{type:["integer","null"]},response_body:{type:["string","null"]},error_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},ExportJob:{type:"object",required:["id","status","created_at"],properties:{id:{type:"string",format:"uuid"},status:{type:"string",enum:["pending","processing","completed","failed"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},Page:{type:"object",required:["data","next_cursor"],properties:{data:{type:"array"},next_cursor:{type:["string","null"]}},additionalProperties:false},UserPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/User"}}}}]},SessionPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}]},OrganizationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}]},MemberPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationMember"}}}}]},RolePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationRole"}}}}]},InvitationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Invitation"}}}}]},EventPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Event"}}}}]},WebhookPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookEndpoint"}}}}]},DeliveryPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookDelivery"}}}}]}};var We=new Set(["__proto__","constructor","prototype"]),Je=64,Ve=5e4;function ae(e,t,n){let o=I[e].responseSchemas;Object.hasOwn(o,String(t))||K();let s=o[String(t)];if(s===null){n!==null&&K();return}let i={nodes:0};return O(n,x(s),0,i)||K(),n}function O(e,t,n,r){if(r.nodes+=1,n>Je||r.nodes>Ve)return false;if(typeof t.$ref=="string"){let s=Xe(t.$ref);if(s===null||!O(e,s,n+1,r))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(s=>O(e,x(s),n+1,r))||Array.isArray(t.enum)&&!t.enum.some(s=>Object.is(s,e)))return false;let o=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!o.some(s=>qe(e,s))?false:e===null?t.type===void 0||o.includes("null"):typeof e=="string"?Be(e,t):typeof e=="number"?Fe(e,t):Array.isArray(e)?Ge(e,t,n,r):P(e)?Ye(e,t,n,r):typeof e=="boolean"}function qe(e,t){switch(t){case "null":return e===null;case "object":return P(e);case "array":return Array.isArray(e);case "string":return typeof e=="string";case "integer":return Number.isSafeInteger(e);case "number":return typeof e=="number"&&Number.isFinite(e);case "boolean":return typeof e=="boolean";default:return false}}function Be(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!He(e,t.pattern))return false;switch(t.format){case void 0:return true;case "uuid":return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e);case "date-time":return /^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e));case "email":return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);case "uri":try{return new URL(e).protocol.length>1}catch{return false}default:return false}}function He(e,t){switch(t){case "^[a-z0-9]+(?:-[a-z0-9]+)*$":return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e);case "^[a-z][a-z0-9_-]*$":return /^[a-z][a-z0-9_-]*$/.test(e);default:return false}}function Fe(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Ge(e,t,n,r){if(typeof t.minItems=="number"&&e.length<t.minItems||typeof t.maxItems=="number"&&e.length>t.maxItems||t.uniqueItems===true&&new Set(e.map(s=>JSON.stringify(s))).size!==e.length)return false;if(t.items===void 0)return true;let o=x(t.items);return e.every(s=>O(s,o,n+1,r))}function Ye(e,t,n,r){let o=Object.keys(e);if(o.some(i=>We.has(i))||typeof t.minProperties=="number"&&o.length<t.minProperties||typeof t.maxProperties=="number"&&o.length>t.maxProperties)return false;let s=P(t.properties)?t.properties:{};if(Array.isArray(t.required)&&t.required.some(i=>typeof i!="string"||!Object.hasOwn(e,i)))return false;for(let[i,c]of Object.entries(e)){let d=s[i];if(d!==void 0){if(!O(c,x(d),n+1,r))return false;continue}if(t.additionalProperties===false||P(t.additionalProperties)&&!O(c,t.additionalProperties,n+1,r))return false}return true}function Xe(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let n=e.slice(t.length);return Object.hasOwn(M,n)?x(M[n]):null}function x(e){return P(e)||K(),e}function P(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function K(){throw new TypeError("Admin API response does not match its generated contract.")}var Ze=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Qe=1024*1024,et=1e4,R=class extends Error{status;code;requestId;problem;retryAfter;constructor(t){super(t.problem.detail),this.name="AuthOwlAdminApiError",this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.problem=t.problem,this.retryAfter=t.retryAfter;}},T=class extends Error{kind;requestId;constructor(t,n){super(t==="aborted"?"The AuthOwl Admin API request was aborted.":t==="timeout"?"The AuthOwl Admin API request timed out.":t==="response_too_large"?"The AuthOwl Admin API response exceeded the allowed size.":t==="invalid_response"?"The AuthOwl Admin API returned an invalid response.":"The AuthOwl Admin API request could not be completed."),this.name="AuthOwlAdminNetworkError",this.kind=t,this.requestId=n;}};function tt(e){nt();let t=rt(e?.secretKey),n=ot(e?.apiUrl),r=e?.fetch??globalThis.fetch;if(typeof r!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let o=async(i,c)=>{let d=c??{},u=I[i],m=new URL(st(u.path,d).replace(/^\/+/,""),n);it(m,d);let g=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`}),p="body"in d?JSON.stringify(d.body):void 0;p!==void 0&&g.set("content-type","application/json");let w;try{w=await j({fetchImpl:r,url:m,init:{method:u.method,headers:g,body:p,signal:c?.signal},timeoutMs:et,maxResponseBytes:Qe,allowHttpLoopback:n.protocol==="http:",decode:(f,k)=>ae(i,k.status,f)});}catch(f){throw f instanceof R?f:f instanceof A?new T(f.kind,f.requestId):new T("network")}let{response:h,requestId:_,data:l}=w;if(!h.ok)throw at(h,l,_);if(!u.successStatuses.some(f=>f===h.status))throw new T("invalid_response",_);return l},s=Object.assign(Object.create(null),{request:o});for(let i of Object.keys(I))s[i]=c=>o(i,c);return Object.freeze(s)}function nt(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function rt(e){if(typeof e!="string"||!Ze.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function ot(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=L(e,{allowHttpLoopback:true});if(t.username||t.password||t.search||t.hash)throw new TypeError("apiUrl must not contain credentials, a query, or a fragment.");let n=t.pathname.replace(/\/+$/,"");if(n!==""&&n!=="/api/v1")throw new TypeError("apiUrl path must be empty or /api/v1.");return t.pathname="/api/v1/",t}function st(e,t){let n="path"in t&&$(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(r,o)=>{let s=n[o];if(typeof s!="string"&&typeof s!="number")throw new TypeError(`Missing Admin API path parameter: ${o}.`);return encodeURIComponent(String(s))})}function it(e,t){if(!(!("query"in t)||!$(t.query)))for(let[n,r]of Object.entries(t.query)){if(r==null)continue;let o=Array.isArray(r)?r:[r];for(let s of o)e.searchParams.append(n,String(s));}}function at(e,t,n){let r=n??ce(e.headers.get("x-request-id"),256),o=ce(e.headers.get("retry-after"),128),s=ct(e.status,r),i=pt(t)?t:s;return new R({status:e.status,code:i.code,requestId:r,problem:i,retryAfter:o})}function ct(e,t){return {type:"about:blank",title:"AuthOwl Admin API error",status:e,detail:"The AuthOwl Admin API rejected the request.",instance:`urn:authowl:request:${t??"unknown"}`,code:"UNKNOWN_ERROR"}}function pt(e){return $(e)?typeof e.type=="string"&&typeof e.title=="string"&&typeof e.status=="number"&&typeof e.detail=="string"&&typeof e.instance=="string"&&typeof e.code=="string":false}function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ce(e,t){let n=e?.trim();if(!(!n||n.length>t||!/^[\x21-\x7e]+$/.test(n)))return n}var dt=/^v1=([a-f0-9]{64})$/i,ut=/^whsec_[A-Za-z0-9_-]{1,256}$/,mt=/^(0|[1-9]\d{0,10})$/;async function lt(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=ft(e.secrets),n=e.toleranceSeconds??300;if(!Number.isSafeInteger(n)||n<0||n>3600)throw new TypeError("Webhook toleranceSeconds must be an integer from 0 to 3600.");let r=e.now??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(r)||r<0)throw new TypeError("Webhook now must be a non-negative Unix timestamp.");let o=ht(e.rawBody);if(o.byteLength>1048576||typeof e.timestamp!="string"||!mt.test(e.timestamp))return false;let s=Number(e.timestamp);if(!Number.isSafeInteger(s)||Math.abs(r-s)>n)return false;let i=yt(e.signatureHeader);if(i.length===0)return false;let c=new TextEncoder().encode(`${e.timestamp}.`),d=new Uint8Array(c.byteLength+o.byteLength);d.set(c),d.set(o,c.byteLength);let u=false;for(let m of t){let g=await crypto.subtle.importKey("raw",new TextEncoder().encode(m),{name:"HMAC",hash:"SHA-256"},false,["sign"]),p=new Uint8Array(await crypto.subtle.sign("HMAC",g,d));for(let w of i)u=bt(p,w)||u;}return u}function ft(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!ut.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function yt(e){if(typeof e!="string"||e.length>1024)return [];let t=e.split(",");if(t.length>4)return [];let n=[];for(let r of t){let o=dt.exec(r.trim());o&&n.push(gt(o[1]));}return n}function ht(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("Webhook rawBody must be a string, ArrayBuffer, or ArrayBuffer view.")}function gt(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}function bt(e,t){if(e.byteLength!==t.byteLength)return false;let n=0;for(let r=0;r<e.byteLength;r+=1)n|=e[r]^t[r];return n===0}var pe=["publishableKey","apiUrl","issuer","jwksUri","audience"],wt=new Set([...pe,"clockToleranceSeconds"]);function D(e){if(e!==void 0&&(!e||typeof e!="object"))throw new Error("AuthOwl token verification config must be an object.");if(e&&Object.keys(e).some(c=>!wt.has(c)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(pe.filter(c=>Object.prototype.hasOwnProperty.call(e??{},c))),n=t.has("publishableKey")||t.has("apiUrl"),r=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(n&&r)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(r){if(typeof e?.issuer!="string"||typeof e.jwksUri!="string"||typeof e.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return U({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let o,s;if(n){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");o=e.publishableKey,s=e.apiUrl;}else o=process.env.AUTHOWL_PUBLISHABLE_KEY,s=process.env.AUTHOWL_API_URL;if(!o||!s)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let i=v({publishableKey:o,apiUrl:s});return U({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},i.decoded.env==="test")}async function Bt(e,t){return E(e,D(t))}async function Ht(e,t,n){let r=D(n);try{let o=await E(e,r);return ie(o.membership,t)}catch{return false}}async function Ft(e,t,n){let r=D(n);try{let o=await E(e,r);return se(o.membership,t.permission)}catch{return false}}
|
|
2
|
-
exports.ADMIN_API_SPEC_SHA256=De;exports.AuthOwlAdminApiError=R;exports.AuthOwlAdminNetworkError=
|
|
1
|
+
'use strict';var ue=new Set(["__proto__","constructor","prototype"]);function T(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function q(e,t=20,r=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&T(),le(e,t,r)}function le(e,t=20,r=1e4){return K(e,0,{nodes:0},t,r)}function K(e,t,r,n,s){if(r.nodes+=1,(t>n||r.nodes>s)&&T(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||T(),e;if(Array.isArray(e))return e.map(p=>K(p,t+1,r,n,s));(!e||typeof e!="object")&&T();let o=Object.getPrototypeOf(e);o!==Object.prototype&&o!==null&&T();let i={};for(let[p,d]of Object.entries(e))ue.has(p)&&T(),i[p]=K(d,t+1,r,n,s);return i}var z=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function b(e,t){throw new Error(`${e}: ${t}`)}function fe(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function V(e,{label:t,allowHttpLoopback:r}){(typeof e!="string"||e.length===0)&&b(t,"required"),e!==e.trim()&&b(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&b(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&b(t,"path must be unencoded");let n;try{n=new URL(e);}catch{b(t,"absolute URL required");}return (n.username||n.password)&&b(t,"credentials forbidden"),n.protocol!=="https:"&&n.protocol!=="http:"&&b(t,"HTTPS required"),n.protocol==="http:"&&(!r||!z.test(e))&&b(t,"HTTPS required except exact loopback"),n}function j(e,t){let r;try{r=new URL(String(e));}catch{throw new TypeError("Transport URL must be absolute.")}if(r.username||r.password||r.hash)throw new TypeError("Transport URL must not contain credentials or a fragment.");let n=r.toString();if(r.protocol!=="https:"&&!(r.protocol==="http:"&&t.allowHttpLoopback&&z.test(n)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return r}function B(e,t,r){let n=fe(e);(n.includes("//")||n.split("/").some(s=>s==="."||s==="..")||n!==""&&n!==t.pathname)&&b(r,"path traversal or duplicate separator");}function H(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&b("apiUrl","origin required");let r;try{r=new URL(e);}catch{b("apiUrl","origin required");}return r.protocol==="http:"&&(!t.allowHttpLoopback||!z.test(e))&&b("apiUrl","HTTPS required except exact loopback"),r.origin}function F(e,t,r={allowHttpLoopback:false}){let n=V(e,{label:"issuer",allowHttpLoopback:r.allowHttpLoopback}),s=V(t,{label:"jwksUri",allowHttpLoopback:r.allowHttpLoopback});return B(e,n,"issuer"),B(t,s,"jwksUri"),n.pathname!=="/"&&n.pathname.endsWith("/")&&b("issuer","trailing slash forbidden"),{issuer:n.toString().replace(/\/$/,""),jwksUri:s.toString()}}var ye=1e4,he=1024*1024,_=class extends Error{kind;requestId;constructor(t,r){super(Oe(t)),this.name="TransportError",this.kind=t,this.requestId=r;}},Z=new WeakSet;function y(e,t){let r=new _(e,t);return Z.add(r),r}async function L({fetchImpl:e,url:t,init:r={},timeoutMs:n=ye,maxResponseBytes:s=he,allowHttpLoopback:o=false,decode:i}){Y(n,"timeoutMs"),Y(s,"maxResponseBytes");let p=j(t,{allowHttpLoopback:o}),d=r.signal,m=new AbortController,u=null,h,c=new Promise(l=>{h=l;}),w=l=>{u===null&&(u=l,h({type:"abort",kind:l}),m.abort());},g=()=>w("aborted");d?.addEventListener("abort",g,{once:true});let S=setTimeout(()=>w("timeout"),n);d?.aborted&&g();try{if(u!==null)throw y(u);let l;try{l=await Promise.race([e(p.toString(),{...r,redirect:"error",signal:m.signal}).then(me=>({type:"response",response:me})),c]);}catch{throw y(u??"network")}if(l.type==="abort")throw y(l.kind);if(!ge(l.response))throw y("invalid_response");let f=l.response,k=ke(f.headers),de=await be(f,s,c,()=>u,k),W=Ae(f,de,k),J;try{J=f.ok&&i?i(W,Object.freeze({status:f.status})):W;}catch{throw y("invalid_response",k)}return {response:f,data:J,...k===void 0?{}:{requestId:k}}}catch(l){throw l instanceof _&&Z.has(l)?l:y(u??"network")}finally{clearTimeout(S),d?.removeEventListener("abort",g);}}function ge(e){if(!e||typeof e!="object")return false;let t=e;return Number.isInteger(t.status)&&t.status>=0&&t.status<=599&&typeof t.statusText=="string"&&typeof t.ok=="boolean"&&typeof t.headers?.get=="function"&&(t.body===null||typeof t.body=="object"&&typeof t.body?.getReader=="function"&&typeof t.body.cancel=="function")}async function be(e,t,r,n,s){let o=e.headers.get("content-length");if(o!==null){if(!/^\d+$/.test(o))throw G(e.body),y("invalid_response",s);if(Number(o)>t)throw G(e.body),y("response_too_large",s)}if(!e.body)return "";let i;try{i=e.body.getReader();}catch{throw y("network",s)}let p=[],d=0,m=null;try{for(;;){let c;try{c=await Promise.race([i.read(),r]);}catch{m=y(n()??"network",s);break}if(we(c)){m=y(c.kind,s);break}let{done:w,value:g}=c;if(w)break;if(g.byteLength!==0){if(d+=g.byteLength,d>t){m=y("response_too_large",s);break}p.push(g);}}}finally{m&&_e(i);try{i.releaseLock();}catch{}}if(m)throw m;let u=new Uint8Array(d),h=0;for(let c of p)u.set(c,h),h+=c.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{throw y("invalid_response",s)}}function we(e){return "type"in e&&e.type==="abort"}function G(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function _e(e){try{e.cancel().catch(()=>{});}catch{}}function Ae(e,t,r){if(e.status===204||e.status===205)return null;let n=Se(e.headers.get("content-type"));if(!e.ok&&(!n||t.length===0))return null;if(!n||t.length===0)throw y("invalid_response",r);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw y("invalid_response",r)}}function Se(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function ke(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function Y(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Oe(e){switch(e){case "aborted":return "The request was cancelled.";case "timeout":return "The request timed out.";case "response_too_large":return "The response exceeded the allowed size.";case "invalid_response":return "The service returned an invalid response.";case "network":return "The network request could not be completed."}}var a=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Te=300*1e3,Ee=5e3,Ie=64*1024,Pe=64,xe=60*1e3,X=new Map,Q=new Map;function $(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4===0?t:t+"=".repeat(4-t.length%4),n=typeof atob=="function"?atob(r):globalThis.Buffer.from(r,"base64").toString("binary"),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}function ee(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode($(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new a("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof a?t:new a("Malformed JWT segment.","TOKEN_MALFORMED")}}function ne(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function te(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&$(e).byteLength===32}function Re(e){if(!ne(e))throw new a("JWKS contains a non-object key.","JWKS_KEY_INVALID");let t=new Set(["alg","crv","kid","kty","use","x","y"]),r=["d","p","q","dp","dq","qi","k","oth"];if("key_ops"in e||r.some(n=>n in e)||Object.keys(e).some(n=>!t.has(n)))throw new a("JWKS contains private, key_ops, or unexpected key members.","JWKS_KEY_INVALID");if(e.kty!=="EC"||e.crv!=="P-256"||e.alg!=="ES256"||e.use!=="sig"||typeof e.kid!="string"||e.kid.length===0||e.kid.length>128||!/^[A-Za-z0-9_-]+$/.test(e.kid)||!te(e.x)||!te(e.y))throw new a("JWKS contains a key outside the AuthOwl ES256 public-key schema.","JWKS_KEY_INVALID");return {alg:e.alg,crv:e.crv,kid:e.kid,kty:e.kty,use:e.use,x:e.x,y:e.y}}function je(e){if(!ne(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new a("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>Pe)throw new a("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(Re),r=new Set;for(let n of t){if(r.has(n.kid))throw new a("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function re(e,t){let r=X.get(e);if(!t&&r&&Date.now()-r.fetchedAt<Te)return r.keys;try{let n=await L({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Ee,maxResponseBytes:Ie,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>q(o)});if(!n.response.ok)throw new a(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=je(n.data);return X.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof a)throw n;if(n instanceof _)switch(n.kind){case "timeout":throw new a("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new a("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new a("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new a("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function Le(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await re(e,false));if(!n){let s=Q.get(e)??0;Date.now()-s>=xe&&(Q.set(e,Date.now()),n=r(await re(e,true)));}if(!n)throw new a("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function Ue(e){let t=globalThis.crypto?.subtle;if(!t)throw new a("WebCrypto is unavailable in this runtime.","WEBCRYPTO_UNAVAILABLE");return t.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y},{name:"ECDSA",namedCurve:"P-256"},false,["verify"])}function ve(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function Ne(e){let t=e.membership;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,n=typeof r.role=="string"?r.role:"",s=Array.isArray(r.permissions)?r.permissions.filter(i=>typeof i=="string"):[],o=Array.isArray(r.teams)?r.teams.filter(i=>typeof i=="string"):void 0;return n===""&&s.length===0&&!o?.length?null:{role:n,permissions:s,...o===void 0?{}:{teams:o}}}async function Ke(e,t){return I(e,U(t))}function U(e,t=false){if(!e||typeof e!="object")throw new a("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=F(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new a("Token verifier issuer or JWKS URL is invalid.","TOKEN_CONFIG_INVALID")}if(typeof e.audience!="string"||e.audience.length===0||e.audience.length>256)throw new a("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new a("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function I(e,t){if(typeof e!="string"||e.length===0)throw new a("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new a("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,i=ee(n);if(i.alg!=="ES256")throw new a("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await Le(t.jwksUri,typeof i.kid=="string"?i.kid:void 0),d;try{d=await Ue(p);}catch(S){throw S instanceof a?S:new a("JWKS key could not be imported.","JWKS_KEY_INVALID")}let m;try{if(!/^[A-Za-z0-9_-]{86}$/.test(o))throw new Error("invalid signature encoding");if(m=$(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new a("Malformed JWT signature.","TOKEN_MALFORMED")}let u=new TextEncoder().encode(`${n}.${s}`),h;try{h=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,m,u);}catch{throw new a("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!h)throw new a("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let c=ee(s),w=t.clockToleranceSeconds??60,g=Math.floor(Date.now()/1e3);if(typeof c.exp!="number")throw new a("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(c.exp+w<g)throw new a("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof c.nbf=="number"&&c.nbf-w>g)throw new a("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof c.iss!="string"||c.iss!==t.issuer)throw new a("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!ve(c.aud,t.audience))throw new a("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof c.sub=="string"?c.sub:null,membership:Ne(c),claims:c}}var ze=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,$e=/^sk_/i;function se(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if($e.test(e))throw new Error("A secret key was passed where a publishable key was expected. Never embed secret keys in client code.");let t=ze.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1],env:t[2],projectId:t[3]}}function M(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=se(e.publishableKey),r=H(e.apiUrl,{allowHttpLoopback:t.env==="test"}),n=`${r}/api/projects/${t.projectId}/auth`;return {...e,apiUrl:r,decoded:t,projectBaseURL:n}}function oe(e,t){return !e||!t?false:e.permissions.includes(t)}function Me(e,t){return !e||!t?false:e.teams?.includes(t)??false}function ie(e,t){if(!e)return false;let{role:r,permission:n,teamId:s}=t;return !(r===void 0&&n===void 0&&s===void 0||r!==void 0&&e.role!==r||n!==void 0&&!e.permissions.includes(n)||s!==void 0&&!Me(e,s))}function Ce(e,t){let r=`p_${e.replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${r}.session_token`}var De="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",P={getOpenApiDocument:{method:"GET",path:"/openapi.json",successStatuses:[200],responseSchemas:{200:{type:"object"}}},listUsers:{method:"GET",path:"/users",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserPage"}}},createUser:{method:"POST",path:"/users",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/User"}}},startUserExport:{method:"POST",path:"/users/export",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getUserExport:{method:"GET",path:"/users/export/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadUserExport:{method:"GET",path:"/users/export/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},startPasswordHashUserExport:{method:"POST",path:"/users/export/hashes",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},dryRunUserImport:{method:"POST",path:"/imports/dry-run",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportDryRun"}}},createUserImport:{method:"POST",path:"/imports",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportBatch"}}},getUserImport:{method:"GET",path:"/imports/{importId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ImportBatch"}}},downloadUserImportReport:{method:"GET",path:"/imports/{importId}/report",successStatuses:[200],responseSchemas:{200:null}},getUser:{method:"GET",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},updateUser:{method:"PATCH",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},deleteUser:{method:"DELETE",path:"/users/{userId}",successStatuses:[204],responseSchemas:{204:null}},listUserSessions:{method:"GET",path:"/users/{userId}/sessions",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionPage"}}},revokeUserSessions:{method:"DELETE",path:"/users/{userId}/sessions",successStatuses:[204],responseSchemas:{204:null}},updateUserMetadata:{method:"PATCH",path:"/users/{userId}/metadata",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserMetadata"}}},verifySession:{method:"POST",path:"/sessions/verify",successStatuses:[200],responseSchemas:{200:{type:"object",required:["user","session"],properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}},getSession:{method:"GET",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Session"}}},updateSessionMetadata:{method:"PATCH",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionMetadata"}}},revokeSession:{method:"DELETE",path:"/sessions/{sessionId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizations:{method:"GET",path:"/organizations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationPage"}}},createOrganization:{method:"POST",path:"/organizations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Organization"}}},getOrganization:{method:"GET",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},updateOrganization:{method:"PATCH",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},deleteOrganization:{method:"DELETE",path:"/organizations/{organizationId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationMembers:{method:"GET",path:"/organizations/{organizationId}/members",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MemberPage"}}},addOrganizationMember:{method:"POST",path:"/organizations/{organizationId}/members",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationMember"}}},updateOrganizationMember:{method:"PATCH",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationMember"}}},removeOrganizationMember:{method:"DELETE",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationRoles:{method:"GET",path:"/organizations/{organizationId}/roles",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/RolePage"}}},createOrganizationRole:{method:"POST",path:"/organizations/{organizationId}/roles",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationRole"}}},updateOrganizationRole:{method:"PATCH",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationRole"}}},deleteOrganizationRole:{method:"DELETE",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[204],responseSchemas:{204:null}},listInvitations:{method:"GET",path:"/invitations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/InvitationPage"}}},createInvitation:{method:"POST",path:"/invitations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Invitation"}}},getInvitation:{method:"GET",path:"/invitations/{invitationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Invitation"}}},revokeInvitation:{method:"DELETE",path:"/invitations/{invitationId}",successStatuses:[204],responseSchemas:{204:null}},listMessages:{method:"GET",path:"/messages",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MessagePage"}}},sendMessage:{method:"POST",path:"/messages",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/Message"}}},getMessage:{method:"GET",path:"/messages/{messageId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Message"}}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},C={Problem:{type:"object",required:["type","title","status","detail","instance","code"],properties:{type:{type:"string",format:"uri"},title:{type:"string"},status:{type:"integer"},detail:{type:"string"},instance:{type:"string",format:"uri"},code:{type:"string"}},additionalProperties:true},User:{type:"object",required:["id","email","phone","name","image","email_verified","banned","public_metadata","private_metadata","unsafe_metadata","metadata_version","created_at","updated_at"],properties:{id:{type:"string"},email:{type:"string",format:"email"},phone:{type:["string","null"]},name:{type:["string","null"]},image:{type:["string","null"],format:"uri"},email_verified:{type:"boolean"},banned:{type:"boolean"},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateUser:{type:"object",required:["email"],properties:{email:{type:"string",format:"email",maxLength:320},password:{type:"string",minLength:8,maxLength:128},name:{type:"string",minLength:1,maxLength:200},phone:{type:"string",minLength:1,maxLength:32}},additionalProperties:false},UpdateUser:{type:"object",minProperties:1,properties:{email:{type:"string",format:"email",maxLength:320},name:{type:["string","null"],minLength:1,maxLength:200},phone:{type:["string","null"],minLength:1,maxLength:32},banned:{type:"boolean"}},additionalProperties:false},ImportDryRun:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","errors","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"dry_run"},status:{type:"string",const:"validated"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},errors:{type:"array",maxItems:100,items:{type:"object",required:["line","code","path","message"],properties:{line:{type:"integer",minimum:2},code:{type:"string",enum:["INVALID_JSON","UNEXPECTED_RECORD","INVALID_USER","DUPLICATE_EXTERNAL_ID"]},path:{type:["string","null"]},message:{type:"string"}},additionalProperties:false}},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},ImportBatch:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","report_expires_at","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"commit"},status:{type:"string",const:"completed"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid","created","updated","unchanged","failed"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4},created:{type:"integer",minimum:0,maximum:1e4},updated:{type:"integer",minimum:0,maximum:1e4},unchanged:{type:"integer",minimum:0,maximum:1e4},failed:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},report_expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},MetadataObject:{type:"object",maxProperties:100,description:"JSON metadata object. Reserved prototype keys and the authowl_ prefix are rejected at every depth. Encoded object size is limited to 8192 bytes.",additionalProperties:true},UserMetadata:{type:"object",required:["public_metadata","private_metadata","unsafe_metadata","metadata_version"],properties:{public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateUserMetadata:{type:"object",required:["expected_version"],minProperties:2,properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Session:{type:"object",required:["id","user_id","expires_at","created_at","metadata","metadata_version"],properties:{id:{type:"string"},user_id:{type:"string"},expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},ip_address:{type:["string","null"]},user_agent:{type:["string","null"]},metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},SessionMetadata:{type:"object",required:["metadata","metadata_version"],properties:{metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateSessionMetadata:{type:"object",required:["expected_version","metadata"],properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Organization:{type:"object",required:["id","name","slug","created_at"],properties:{id:{type:"string"},name:{type:"string"},slug:{type:"string"},logo:{type:["string","null"],format:"uri"},metadata:{type:["object","null"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateOrganization:{type:"object",required:["name","slug"],properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:"string",format:"uri",maxLength:2048},metadata:{type:"object"}},additionalProperties:false},UpdateOrganization:{type:"object",minProperties:1,properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:["string","null"],format:"uri",maxLength:2048},metadata:{type:["object","null"]}},additionalProperties:false},OrganizationMember:{type:"object",required:["organization_id","user_id","role","created_at"],properties:{organization_id:{type:"string"},user_id:{type:"string"},role:{type:"string"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},AddMember:{type:"object",required:["user_id","role"],properties:{user_id:{type:"string"},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},OrganizationRole:{type:"object",required:["id","organization_id","name","permissions"],properties:{id:{type:"string"},organization_id:{type:"string"},name:{type:"string"},permissions:{type:"array",items:{$ref:"#/components/schemas/OrganizationPermissionId"}}},additionalProperties:false},OrganizationPermissionId:{type:"string",enum:["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","team:create","team:update","team:delete","ac:create","ac:read","ac:update","ac:delete"]},RoleInput:{type:"object",required:["name","permissions"],properties:{name:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9_-]*$"},permissions:{type:"array",maxItems:100,items:{$ref:"#/components/schemas/OrganizationPermissionId"},uniqueItems:true}},additionalProperties:false},Invitation:{type:"object",required:["id","organization_id","email","role","status","expires_at"],properties:{id:{type:"string"},organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100},status:{type:"string"},expires_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateInvitation:{type:"object",required:["organization_id","email","role"],properties:{organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},Event:{type:"object",required:["id","type","status","created_at"],properties:{id:{type:"string"},type:{type:"string"},status:{type:"string"},user_id:{type:["string","null"]},metadata:{type:"object"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},StatsOverview:{type:"object",required:["users_total","monthly_active_users","recent_sign_ins"],properties:{users_total:{type:"integer",minimum:0},monthly_active_users:{type:"integer",minimum:0},recent_sign_ins:{type:"integer",minimum:0}},additionalProperties:false},WebhookInput:{type:"object",required:["url","events"],properties:{url:{type:"string",format:"uri",maxLength:2048},description:{type:"string",maxLength:500},events:{type:"array",minItems:1,maxItems:20,items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"},uniqueItems:true}},additionalProperties:false},SendMessage:{type:"object",required:["to","template","variables"],properties:{to:{type:"string",minLength:7,maxLength:32},channel:{type:"string",enum:["sms","whatsapp","auto"],description:"Defaults to auto."},purpose:{type:"string",enum:["transactional"],description:"Defaults to transactional."},template:{type:"string",pattern:"^[a-z][a-z0-9_]{0,63}$"},locale:{type:"string",enum:["en","ar"],description:"Defaults to en."},variables:{type:"object",maxProperties:50,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_]{0,63}$"},additionalProperties:{type:"string",maxLength:1024}},customerReference:{type:"string",minLength:1,maxLength:255}},additionalProperties:false},MessageState:{type:"string",enum:["preparing","queued","accepted","skipped","delivered","failed","unknown","canceled"]},Message:{type:"object",required:["id","state","purpose","requested_channel","actual_channel","customer_reference","masked_recipient","sms","billing","failure","created_at","updated_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},state:{$ref:"#/components/schemas/MessageState"},purpose:{type:"string",enum:["transactional","auth_otp"]},requested_channel:{type:"string",enum:["sms","whatsapp","auto"]},actual_channel:{type:["string","null"],enum:["sms","whatsapp",null]},customer_reference:{type:["string","null"]},masked_recipient:{type:"string"},sms:{oneOf:[{type:"null"},{type:"object",required:["encoding","segments"],properties:{encoding:{type:["string","null"],enum:["gsm7","ucs2",null]},segments:{type:["integer","null"],minimum:1}},additionalProperties:false}]},billing:{type:"object",required:["credential_mode","unit","units","charged_piasters","reserved_piasters"],properties:{credential_mode:{type:"string",enum:["managed","byok"]},unit:{type:["string","null"]},units:{type:["integer","null"]},charged_piasters:{type:"integer",minimum:0},reserved_piasters:{type:"integer",minimum:0}},additionalProperties:false},failure:{oneOf:[{type:"null"},{type:"object",required:["code","retryable"],properties:{code:{type:"string"},retryable:{type:"boolean"}},additionalProperties:false}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},WebhookSubscriptionEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed"]},WebhookEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed","webhook.test"]},WebhookEndpoint:{type:"object",required:["id","url","events","status","created_at","updated_at"],properties:{id:{type:"string",format:"uuid"},url:{type:"string",format:"uri"},description:{type:["string","null"]},events:{type:"array",items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"}},status:{type:"string",enum:["active","paused","auto_paused"]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookSecret:{type:"object",required:["secret","overlap_expires_at"],properties:{secret:{type:"string"},overlap_expires_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookWithSecret:{type:"object",required:["endpoint","secret"],properties:{endpoint:{$ref:"#/components/schemas/WebhookEndpoint"},secret:{type:"string"}},additionalProperties:false},WebhookDelivery:{type:"object",required:["id","event_id","attempt_id","attempt_number","webhook_id","event_type","status","response_status","response_body","error_code","created_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},event_id:{type:"string",format:"uuid"},attempt_id:{type:"string",format:"uuid"},attempt_number:{type:"integer",minimum:1},webhook_id:{type:"string",format:"uuid"},event_type:{$ref:"#/components/schemas/WebhookEventType"},status:{type:"string",enum:["queued","delivering","succeeded","failed"]},response_status:{type:["integer","null"]},response_body:{type:["string","null"]},error_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},ExportJob:{type:"object",required:["id","format","status","includes_password_hashes","total_rows","artifact_bytes","failure_code","created_at","completed_at","expires_at","download_url"],properties:{id:{type:"string",format:"uuid"},format:{type:"string",enum:["ndjson","csv"]},status:{type:"string",enum:["pending","processing","completed","failed"]},includes_password_hashes:{type:"boolean"},total_rows:{type:"integer",minimum:0},artifact_bytes:{type:"integer",minimum:0},failure_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},completed_at:{type:["string","null"],format:"date-time"},expires_at:{type:["string","null"],format:"date-time"},download_url:{type:["string","null"]}},additionalProperties:false},ExportRequest:{type:"object",properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"}},additionalProperties:false},HashExportRequest:{type:"object",required:["approval_token"],properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"},approval_token:{type:"string",minLength:1,maxLength:256}},additionalProperties:false},Page:{type:"object",required:["data","next_cursor"],properties:{data:{type:"array"},next_cursor:{type:["string","null"]}},additionalProperties:false},UserPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/User"}}}}]},SessionPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}]},OrganizationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}]},MemberPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationMember"}}}}]},RolePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationRole"}}}}]},InvitationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Invitation"}}}}]},EventPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Event"}}}}]},WebhookPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookEndpoint"}}}}]},DeliveryPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookDelivery"}}}}]},MessagePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Message"}}}}]}};var We=new Set(["__proto__","constructor","prototype"]),Je=64,qe=5e4;function ae(e,t,r){let s=P[e].responseSchemas;Object.hasOwn(s,String(t))||v();let o=s[String(t)];if(o===null){r!==null&&v();return}let i={nodes:0};return A(r,O(o),0,i)||v(),r}function A(e,t,r,n){if(n.nodes+=1,r>Je||n.nodes>qe)return false;if(typeof t.$ref=="string"){let o=Ze(t.$ref);if(o===null||!A(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>A(e,O(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>A(e,O(o),r+1,n)).length!==1||Array.isArray(t.enum)&&!t.enum.some(o=>Object.is(o,e))||t.const!==void 0&&!Object.is(t.const,e))return false;let s=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!s.some(o=>Ve(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?Be(e,t):typeof e=="number"?Fe(e,t):Array.isArray(e)?Ge(e,t,r,n):x(e)?Ye(e,t,r,n):typeof e=="boolean"}function Ve(e,t){switch(t){case "null":return e===null;case "object":return x(e);case "array":return Array.isArray(e);case "string":return typeof e=="string";case "integer":return Number.isSafeInteger(e);case "number":return typeof e=="number"&&Number.isFinite(e);case "boolean":return typeof e=="boolean";default:return false}}function Be(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!He(e,t.pattern))return false;switch(t.format){case void 0:return true;case "uuid":return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e);case "date-time":return /^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e));case "email":return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);case "uri":try{return new URL(e).protocol.length>1}catch{return false}default:return false}}function He(e,t){switch(t){case "^[a-z0-9]+(?:-[a-z0-9]+)*$":return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e);case "^[a-z][a-z0-9_-]*$":return /^[a-z][a-z0-9_-]*$/.test(e);case "^[A-Za-z0-9][A-Za-z0-9._:/-]*$":return /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/.test(e);case "^[a-z][a-z0-9_]{0,63}$":return /^[a-z][a-z0-9_]{0,63}$/.test(e);case "^[A-Za-z][A-Za-z0-9_]{0,63}$":return /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(e);default:return false}}function Fe(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Ge(e,t,r,n){if(typeof t.minItems=="number"&&e.length<t.minItems||typeof t.maxItems=="number"&&e.length>t.maxItems||t.uniqueItems===true&&new Set(e.map(o=>JSON.stringify(o))).size!==e.length)return false;if(t.items===void 0)return true;let s=O(t.items);return e.every(o=>A(o,s,r+1,n))}function Ye(e,t,r,n){let s=Object.keys(e);if(s.some(i=>We.has(i))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=x(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(i=>!A(i,O(t.propertyNames),r+1,n))||Array.isArray(t.required)&&t.required.some(i=>typeof i!="string"||!Object.hasOwn(e,i)))return false;for(let[i,p]of Object.entries(e)){let d=o[i];if(d!==void 0){if(!A(p,O(d),r+1,n))return false;continue}if(t.additionalProperties===false||x(t.additionalProperties)&&!A(p,t.additionalProperties,r+1,n))return false}return true}function Ze(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(C,r)?O(C[r]):null}function O(e){return x(e)||v(),e}function x(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function v(){throw new TypeError("Admin API response does not match its generated contract.")}var Xe=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Qe=1024*1024,et=1e4,R=class extends Error{status;code;requestId;problem;retryAfter;constructor(t){super(t.problem.detail),this.name="AuthOwlAdminApiError",this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.problem=t.problem,this.retryAfter=t.retryAfter;}},E=class extends Error{kind;requestId;constructor(t,r){super(t==="aborted"?"The AuthOwl Admin API request was aborted.":t==="timeout"?"The AuthOwl Admin API request timed out.":t==="response_too_large"?"The AuthOwl Admin API response exceeded the allowed size.":t==="invalid_response"?"The AuthOwl Admin API returned an invalid response.":"The AuthOwl Admin API request could not be completed."),this.name="AuthOwlAdminNetworkError",this.kind=t,this.requestId=r;}};function tt(e){rt();let t=nt(e?.secretKey),r=st(e?.apiUrl),n=e?.fetch??globalThis.fetch;if(typeof n!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let s=async(i,p)=>{let d=p??{},m=P[i],u=new URL(ot(m.path,d).replace(/^\/+/,""),r);it(u,d);let h=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});at(h,d);let c="body"in d?JSON.stringify(d.body):void 0;c!==void 0&&h.set("content-type","application/json");let w;try{w=await L({fetchImpl:n,url:u,init:{method:m.method,headers:h,body:c,signal:p?.signal},timeoutMs:et,maxResponseBytes:Qe,allowHttpLoopback:r.protocol==="http:",decode:(f,k)=>ae(i,k.status,f)});}catch(f){throw f instanceof R?f:f instanceof _?new E(f.kind,f.requestId):new E("network")}let{response:g,requestId:S,data:l}=w;if(!g.ok)throw pt(g,l,S);if(!m.successStatuses.some(f=>f===g.status))throw new E("invalid_response",S);return l},o=Object.assign(Object.create(null),{request:s});for(let i of Object.keys(P))o[i]=p=>s(i,p);return Object.freeze(o)}function rt(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function nt(e){if(typeof e!="string"||!Xe.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function st(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=j(e,{allowHttpLoopback:true});if(t.username||t.password||t.search||t.hash)throw new TypeError("apiUrl must not contain credentials, a query, or a fragment.");let r=t.pathname.replace(/\/+$/,"");if(r!==""&&r!=="/api/v1")throw new TypeError("apiUrl path must be empty or /api/v1.");return t.pathname="/api/v1/",t}function ot(e,t){let r="path"in t&&N(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(n,s)=>{let o=r[s];if(typeof o!="string"&&typeof o!="number")throw new TypeError(`Missing Admin API path parameter: ${s}.`);return encodeURIComponent(String(o))})}function it(e,t){if(!(!("query"in t)||!N(t.query)))for(let[r,n]of Object.entries(t.query)){if(n==null)continue;let s=Array.isArray(n)?n:[n];for(let o of s)e.searchParams.append(r,String(o));}}function at(e,t){if(!(!("header"in t)||!N(t.header)))for(let[r,n]of Object.entries(t.header)){if(n==null)continue;if(r.toLowerCase()!=="idempotency-key")throw new TypeError(`Unsupported Admin API header parameter: ${r}.`);if(typeof n!="string"||n.length<1||n.length>255)throw new TypeError("Idempotency-Key must contain between 1 and 255 characters.");if(!/^[\x21-\x7e ]+$/.test(n))throw new TypeError("Idempotency-Key contains unsupported characters.");e.set("Idempotency-Key",n);}}function pt(e,t,r){let n=r??pe(e.headers.get("x-request-id"),256),s=pe(e.headers.get("retry-after"),128),o=ct(e.status,n),i=dt(t)?t:o;return new R({status:e.status,code:i.code,requestId:n,problem:i,retryAfter:s})}function ct(e,t){return {type:"about:blank",title:"AuthOwl Admin API error",status:e,detail:"The AuthOwl Admin API rejected the request.",instance:`urn:authowl:request:${t??"unknown"}`,code:"UNKNOWN_ERROR"}}function dt(e){return N(e)?typeof e.type=="string"&&typeof e.title=="string"&&typeof e.status=="number"&&typeof e.detail=="string"&&typeof e.instance=="string"&&typeof e.code=="string":false}function N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var mt=/^v1=([a-f0-9]{64})$/i,ut=/^whsec_[A-Za-z0-9_-]{1,256}$/,lt=/^(0|[1-9]\d{0,10})$/;async function ft(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=yt(e.secrets),r=e.toleranceSeconds??300;if(!Number.isSafeInteger(r)||r<0||r>3600)throw new TypeError("Webhook toleranceSeconds must be an integer from 0 to 3600.");let n=e.now??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(n)||n<0)throw new TypeError("Webhook now must be a non-negative Unix timestamp.");let s=gt(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!lt.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let i=ht(e.signatureHeader);if(i.length===0)return false;let p=new TextEncoder().encode(`${e.timestamp}.`),d=new Uint8Array(p.byteLength+s.byteLength);d.set(p),d.set(s,p.byteLength);let m=false;for(let u of t){let h=await crypto.subtle.importKey("raw",new TextEncoder().encode(u),{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=new Uint8Array(await crypto.subtle.sign("HMAC",h,d));for(let w of i)m=wt(c,w)||m;}return m}function yt(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!ut.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function ht(e){if(typeof e!="string"||e.length>1024)return [];let t=e.split(",");if(t.length>4)return [];let r=[];for(let n of t){let s=mt.exec(n.trim());s&&r.push(bt(s[1]));}return r}function gt(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("Webhook rawBody must be a string, ArrayBuffer, or ArrayBuffer view.")}function bt(e){let t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(r*2,r*2+2),16);return t}function wt(e,t){if(e.byteLength!==t.byteLength)return false;let r=0;for(let n=0;n<e.byteLength;n+=1)r|=e[n]^t[n];return r===0}var ce=["publishableKey","apiUrl","issuer","jwksUri","audience"],_t=new Set([...ce,"clockToleranceSeconds"]);function D(e){if(e!==void 0&&(!e||typeof e!="object"))throw new Error("AuthOwl token verification config must be an object.");if(e&&Object.keys(e).some(p=>!_t.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(ce.filter(p=>Object.prototype.hasOwnProperty.call(e??{},p))),r=t.has("publishableKey")||t.has("apiUrl"),n=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n){if(typeof e?.issuer!="string"||typeof e.jwksUri!="string"||typeof e.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return U({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let s,o;if(r){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e.publishableKey,o=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o=process.env.AUTHOWL_API_URL;if(!s||!o)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let i=M({publishableKey:s,apiUrl:o});return U({issuer:i.projectBaseURL,jwksUri:`${i.projectBaseURL}/jwks`,audience:i.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},i.decoded.env==="test")}async function Ht(e,t){return I(e,D(t))}async function Ft(e,t,r){let n=D(r);try{let s=await I(e,n);return ie(s.membership,t)}catch{return false}}async function Gt(e,t,r){let n=D(r);try{let s=await I(e,n);return oe(s.membership,t.permission)}catch{return false}}
|
|
2
|
+
exports.ADMIN_API_SPEC_SHA256=De;exports.AuthOwlAdminApiError=R;exports.AuthOwlAdminNetworkError=E;exports.TokenVerificationError=a;exports.createAdminClient=tt;exports.has=Ft;exports.hasPermission=Gt;exports.resolveConfig=M;exports.sessionCookieName=Ce;exports.verifyProjectToken=Ke;exports.verifyToken=Ht;exports.verifyWebhook=ft;
|