@authowl/core 0.21.1 → 0.22.1
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 +56 -5
- package/dist/{chunk-GFSJFTD7.js → chunk-DVVGVPDH.js} +1 -1
- package/dist/chunk-IB6TFQFD.js +2 -0
- package/dist/{client-BRDFS1ln.d.cts → client-BwZ1bqU4.d.cts} +6 -2
- package/dist/{client-DhUE4JL1.d.ts → client-DXypEWpf.d.ts} +6 -2
- package/dist/{idempotency-DmDFUS3e.d.ts → idempotency-BWMPd3B7.d.ts} +2 -2
- package/dist/{idempotency-kuv3HQVN.d.cts → idempotency-BfRYS8qn.d.cts} +2 -2
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/messages.cjs +1 -1
- package/dist/messages.d.cts +1 -0
- package/dist/messages.d.ts +1 -0
- package/dist/messages.js +1 -1
- package/dist/native.cjs +2 -2
- package/dist/native.d.cts +6 -6
- package/dist/native.d.ts +6 -6
- package/dist/native.js +1 -1
- package/dist/{organization-membership-DSqmZLkN.d.cts → organization-membership-BIify9hZ.d.cts} +10 -0
- package/dist/{organization-membership-DSqmZLkN.d.ts → organization-membership-BIify9hZ.d.ts} +10 -0
- package/dist/privacy.d.cts +2 -2
- package/dist/privacy.d.ts +2 -2
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +139 -4
- package/dist/server.d.ts +139 -4
- package/dist/server.js +1 -1
- package/dist/{session-handoff-6FBH3GFJ.js → session-handoff-ICVIFI3C.js} +2 -2
- package/dist/session-proof-client-JPZY63IN.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-V3MSLXXB.js +0 -2
package/dist/server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-
|
|
2
|
-
export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, h as resolveAuthTarget, r as resolveConfig } from './organization-membership-
|
|
1
|
+
import { O as OrganizationMembership, b as TransportErrorKind, H as HasParams } from './organization-membership-BIify9hZ.js';
|
|
2
|
+
export { A as AuthConfig, R as ResolvedAuthConfig, a as ResolvedAuthTarget, h as resolveAuthTarget, r as resolveConfig } from './organization-membership-BIify9hZ.js';
|
|
3
3
|
export { s as sessionCookieName } from './cookie-BqcfagTw.js';
|
|
4
4
|
export { a as SESSION_TRANSPORT_BEARER, b as SESSION_TRANSPORT_HEADER } from './session-transport-contract-HDPYRum8.js';
|
|
5
5
|
|
|
@@ -33,12 +33,21 @@ interface VerifyProjectTokenOptions {
|
|
|
33
33
|
audience: string;
|
|
34
34
|
/** Clock skew tolerance for exp/nbf, in seconds (default 60). */
|
|
35
35
|
clockToleranceSeconds?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Narrow verification to one declared token purpose. When omitted, session,
|
|
38
|
+
* template, and access tokens are accepted; ID tokens are never accepted by
|
|
39
|
+
* default on this backend authorization surface.
|
|
40
|
+
*/
|
|
41
|
+
tokenUse?: ProjectTokenUse;
|
|
42
|
+
/** Reject legacy tokens that do not carry `token_use` (default false). */
|
|
43
|
+
requireTokenUse?: boolean;
|
|
36
44
|
}
|
|
45
|
+
type ProjectTokenUse = 'session' | 'template' | 'access' | 'id';
|
|
37
46
|
declare class TokenVerificationError extends Error {
|
|
38
47
|
readonly code: TokenVerificationErrorCode;
|
|
39
48
|
constructor(message: string, code?: TokenVerificationErrorCode);
|
|
40
49
|
}
|
|
41
|
-
type TokenVerificationErrorCode = 'TOKEN_VERIFICATION_FAILED' | 'TOKEN_CONFIG_INVALID' | 'TOKEN_MALFORMED' | 'TOKEN_ALGORITHM_UNSUPPORTED' | 'TOKEN_SIGNATURE_INVALID' | 'TOKEN_CLAIM_INVALID' | 'JWKS_FETCH_FAILED' | 'JWKS_FETCH_TIMEOUT' | 'JWKS_HTTP_ERROR' | 'JWKS_RESPONSE_TOO_LARGE' | 'JWKS_DOCUMENT_INVALID' | 'JWKS_TOO_MANY_KEYS' | 'JWKS_KEY_INVALID' | 'JWKS_DUPLICATE_KID' | 'JWKS_KEY_NOT_FOUND' | 'WEBCRYPTO_UNAVAILABLE';
|
|
50
|
+
type TokenVerificationErrorCode = 'TOKEN_VERIFICATION_FAILED' | 'TOKEN_CONFIG_INVALID' | 'TOKEN_MALFORMED' | 'TOKEN_ALGORITHM_UNSUPPORTED' | 'TOKEN_SIGNATURE_INVALID' | 'TOKEN_CLAIM_INVALID' | 'TOKEN_USE_UNSUPPORTED' | 'JWKS_FETCH_FAILED' | 'JWKS_FETCH_TIMEOUT' | 'JWKS_HTTP_ERROR' | 'JWKS_RESPONSE_TOO_LARGE' | 'JWKS_DOCUMENT_INVALID' | 'JWKS_TOO_MANY_KEYS' | 'JWKS_KEY_INVALID' | 'JWKS_DUPLICATE_KID' | 'JWKS_KEY_NOT_FOUND' | 'WEBCRYPTO_UNAVAILABLE';
|
|
42
51
|
/**
|
|
43
52
|
* Verify an AuthOwl project JWT and return its subject, membership, and claims.
|
|
44
53
|
* Throws {@link TokenVerificationError} on any failure (bad signature, wrong
|
|
@@ -46,6 +55,72 @@ type TokenVerificationErrorCode = 'TOKEN_VERIFICATION_FAILED' | 'TOKEN_CONFIG_IN
|
|
|
46
55
|
*/
|
|
47
56
|
declare function verifyProjectToken(token: string, options: VerifyProjectTokenOptions): Promise<VerifiedProjectToken>;
|
|
48
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Ergonomic authorization gates over the verified primitives, plan 41.1.
|
|
60
|
+
*
|
|
61
|
+
* These add no trust decision of their own. `requireAuth` is `verifyToken` that
|
|
62
|
+
* throws a typed error instead of returning; the rest layer `has()`-style
|
|
63
|
+
* membership evaluation on top. Everything still fails closed, because the
|
|
64
|
+
* primitives underneath already do.
|
|
65
|
+
*
|
|
66
|
+
* They exist because the shortest path should be the correct one. Before this,
|
|
67
|
+
* a tenant reaching for something middleware-shaped found
|
|
68
|
+
* `createAuthRedirectMiddleware`, which checks cookie NAME presence for UX
|
|
69
|
+
* redirects and verifies nothing at all.
|
|
70
|
+
*
|
|
71
|
+
* **What these cannot do.** They answer who the caller is and what they hold.
|
|
72
|
+
* They cannot know whether that user owns invoice 4471. Resource ownership is a
|
|
73
|
+
* query only your application can write:
|
|
74
|
+
*
|
|
75
|
+
* ```ts
|
|
76
|
+
* const { sub } = await requireAuth(token);
|
|
77
|
+
* const invoice = await db.invoice.find(id);
|
|
78
|
+
* if (invoice.userId !== sub) throw new ForbiddenError('not yours');
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* That last check is yours, on every route, and no auth provider can do it for
|
|
82
|
+
* you.
|
|
83
|
+
*/
|
|
84
|
+
/**
|
|
85
|
+
* Why a gate refused.
|
|
86
|
+
*
|
|
87
|
+
* `unauthenticated` and `forbidden` are separate on purpose, because they are
|
|
88
|
+
* different HTTP answers and collapsing them is a real bug in both directions:
|
|
89
|
+
* answering 401 to an authenticated-but-unauthorized caller invites a
|
|
90
|
+
* pointless re-login loop, and answering 403 to an anonymous one tells them an
|
|
91
|
+
* identity they do not have would not have helped either.
|
|
92
|
+
*/
|
|
93
|
+
type AuthorizationFailureReason = 'unauthenticated' | 'forbidden';
|
|
94
|
+
declare class AuthorizationError extends Error {
|
|
95
|
+
readonly reason: AuthorizationFailureReason;
|
|
96
|
+
/** 401 for `unauthenticated`, 403 for `forbidden`. */
|
|
97
|
+
readonly status: 401 | 403;
|
|
98
|
+
/**
|
|
99
|
+
* Why verification failed, when a token was supplied. For your logs.
|
|
100
|
+
*
|
|
101
|
+
* Non-enumerable, which is load-bearing rather than tidiness. As a plain
|
|
102
|
+
* class field it survived `JSON.stringify(error)`, so the extremely common
|
|
103
|
+
* `res.status(err.status).json(err)` would have published the per-check
|
|
104
|
+
* oracle - `TOKEN_SIGNATURE_INVALID` versus `TOKEN_CLAIM_INVALID` versus
|
|
105
|
+
* `JWKS_KEY_NOT_FOUND` - that this module's own docs say must never reach a
|
|
106
|
+
* response body. Reading `error.cause` still works; serializing it no longer
|
|
107
|
+
* happens by accident.
|
|
108
|
+
*/
|
|
109
|
+
readonly cause?: TokenVerificationError;
|
|
110
|
+
constructor(reason: AuthorizationFailureReason, message: string, cause?: TokenVerificationError);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Type guard for `AuthorizationError`, for callers who cannot rely on
|
|
114
|
+
* `instanceof`.
|
|
115
|
+
*
|
|
116
|
+
* A tenant can end up with two physical copies of `@authowl/core` - depending
|
|
117
|
+
* on it directly alongside `@authowl/next`, or an ESM/CJS split in one process
|
|
118
|
+
* - and then `instanceof` misses and their 401/403 handling silently falls
|
|
119
|
+
* through to a 500. The request is still denied, so this is ergonomics rather
|
|
120
|
+
* than a hole, but a silent one.
|
|
121
|
+
*/
|
|
122
|
+
declare function isAuthorizationError(value: unknown): value is AuthorizationError;
|
|
123
|
+
|
|
49
124
|
interface paths {
|
|
50
125
|
readonly "/openapi.json": {
|
|
51
126
|
readonly parameters: {
|
|
@@ -3621,6 +3696,8 @@ declare function mcpUnauthorizedChallenge(input: {
|
|
|
3621
3696
|
*/
|
|
3622
3697
|
type VerifyTokenConfigCommon = {
|
|
3623
3698
|
clockToleranceSeconds?: number;
|
|
3699
|
+
tokenUse?: ProjectTokenUse;
|
|
3700
|
+
requireTokenUse?: boolean;
|
|
3624
3701
|
};
|
|
3625
3702
|
type VerifyTokenConfig = (VerifyTokenConfigCommon & {
|
|
3626
3703
|
publishableKey: string;
|
|
@@ -3663,4 +3740,62 @@ declare function hasPermission(token: string, params: {
|
|
|
3663
3740
|
permission: string;
|
|
3664
3741
|
}, config?: VerifyTokenConfig): Promise<boolean>;
|
|
3665
3742
|
|
|
3666
|
-
|
|
3743
|
+
/**
|
|
3744
|
+
* Verify a token and return its identity, or throw {@link AuthorizationError}
|
|
3745
|
+
* with `status: 401`. The gate form of {@link verifyToken}.
|
|
3746
|
+
*
|
|
3747
|
+
* ```ts
|
|
3748
|
+
* const { sub, membership } = await requireAuth(bearerToken);
|
|
3749
|
+
* ```
|
|
3750
|
+
*
|
|
3751
|
+
* Ownership is still yours: this proves who is calling, not what they may
|
|
3752
|
+
* touch. See the note on {@link requirePermission}.
|
|
3753
|
+
*/
|
|
3754
|
+
declare function requireAuth(token: string | null | undefined, config?: VerifyTokenConfig): Promise<VerifiedProjectToken>;
|
|
3755
|
+
/**
|
|
3756
|
+
* Verify a token and require it to grant `permission`, or throw
|
|
3757
|
+
* {@link AuthorizationError} - `401` when the token is missing or unverifiable,
|
|
3758
|
+
* `403` when it verified but lacks the permission.
|
|
3759
|
+
*
|
|
3760
|
+
* ```ts
|
|
3761
|
+
* await requirePermission(bearerToken, 'org:invoices:read');
|
|
3762
|
+
* ```
|
|
3763
|
+
*
|
|
3764
|
+
* **This does not check resource ownership, and cannot.** AuthOwl knows the
|
|
3765
|
+
* caller holds `org:invoices:read`; it does not know whether invoice 4471 is
|
|
3766
|
+
* theirs. That comparison lives in your handler, against your data:
|
|
3767
|
+
*
|
|
3768
|
+
* ```ts
|
|
3769
|
+
* const { sub } = await requirePermission(token, 'org:invoices:read');
|
|
3770
|
+
* const invoice = await db.invoice.find(id);
|
|
3771
|
+
* if (invoice.userId !== sub) return forbidden();
|
|
3772
|
+
* ```
|
|
3773
|
+
*/
|
|
3774
|
+
declare function requirePermission(token: string | null | undefined, permission: string, config?: VerifyTokenConfig): Promise<VerifiedProjectToken>;
|
|
3775
|
+
/**
|
|
3776
|
+
* Verify a token and require it to satisfy a {@link has} check - any
|
|
3777
|
+
* combination of `role`, `permission`, `teamId`. Same status semantics as
|
|
3778
|
+
* {@link requirePermission}.
|
|
3779
|
+
*
|
|
3780
|
+
* `teamId` checks GROUP membership, not authority: teams grant nothing on their
|
|
3781
|
+
* own, so requiring one alone is a filter rather than a gate.
|
|
3782
|
+
*/
|
|
3783
|
+
declare function requireGrant(token: string | null | undefined, params: HasParams, config?: VerifyTokenConfig): Promise<VerifiedProjectToken>;
|
|
3784
|
+
/**
|
|
3785
|
+
* Verify a token and require it to have been minted for `organizationId`, or
|
|
3786
|
+
* throw {@link AuthorizationError}.
|
|
3787
|
+
*
|
|
3788
|
+
* ```ts
|
|
3789
|
+
* const { sub } = await requireOrg(token, params.orgId);
|
|
3790
|
+
* ```
|
|
3791
|
+
*
|
|
3792
|
+
* This is the strongest cross-tenant check available from the token alone: it
|
|
3793
|
+
* proves which organization the session is acting in. Use it to scope the
|
|
3794
|
+
* query, then still compare ownership on the row - knowing the caller is in
|
|
3795
|
+
* org X does not establish that invoice 4471 belongs to org X.
|
|
3796
|
+
*
|
|
3797
|
+
* Fails closed when the token carries no `org_id`.
|
|
3798
|
+
*/
|
|
3799
|
+
declare function requireOrg(token: string | null | undefined, organizationId: string, config?: VerifyTokenConfig): Promise<VerifiedProjectToken>;
|
|
3800
|
+
|
|
3801
|
+
export { ADMIN_API_SPEC_SHA256, type components as AdminApiComponents, type operations as AdminApiOperations, type paths as AdminApiPaths, type AdminApiProblem, type AdminClient, type AdminClientConfig, type AdminOperationId, type AdminOperationInput, type AdminOperationResult, AuthOwlAdminApiError, AuthOwlAdminNetworkError, AuthorizationError, type AuthorizationFailureReason, HasParams, type McpProtectedResourceMetadata, OrganizationMembership, type ProjectTokenUse, TokenVerificationError, type TokenVerificationErrorCode, type VerifiedProjectToken, type VerifyTokenConfig, type VerifyWebhookInput, createAdminClient, has, hasPermission, isAuthorizationError, mcpProtectedResourceMetadata, mcpProtectedResourceMetadataUrl, mcpUnauthorizedChallenge, requireAuth, requireGrant, requireOrg, requirePermission, verifyProjectToken, verifyToken, verifyWebhook };
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,c,E as E$1,B as B$1,p,o,n,z}from'./chunk-V3MSLXXB.js';export{l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,m as resolveAuthTarget,n as resolveConfig,b as sessionCookieName}from'./chunk-V3MSLXXB.js';var i=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},se=300*1e3,oe=5e3,ie=64*1024,ae=64,pe=60*1e3,W=new Map,q=new Map;function v(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 J(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(v(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof i?t:new i("Malformed JWT segment.","TOKEN_MALFORMED")}}function H(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function V(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&v(e).byteLength===32}function ce(e){if(!H(e))throw new i("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 i("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)||!V(e.x)||!V(e.y))throw new i("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 de(e){if(!H(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new i("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>ae)throw new i("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(ce),r=new Set;for(let n of t){if(r.has(n.kid))throw new i("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function B(e,t){let r=W.get(e);if(!t&&r&&Date.now()-r.fetchedAt<se)return r.keys;try{let n=await p({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:oe,maxResponseBytes:ie,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>z(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=de(n.data);return W.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof o)switch(n.kind){case "timeout":throw new i("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new i("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new i("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new i("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function me(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await B(e,false));if(!n){let s=q.get(e)??0;Date.now()-s>=pe&&(q.set(e,Date.now()),n=r(await B(e,true)));}if(!n)throw new i("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 i("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 le(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function fe(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(p=>typeof p=="string"):[],o=Array.isArray(r.roles)?r.roles.filter(p=>typeof p=="string"):void 0,a=Array.isArray(r.teams)?r.teams.filter(p=>typeof p=="string"):void 0;return n===""&&s.length===0&&!o?.length&&!a?.length?null:{role:n,...o===void 0?{}:{roles:o},permissions:s,...a===void 0?{}:{teams:a}}}async function ye(e,t){return w(e,k(t))}function k(e,t=false){if(!e||typeof e!="object")throw new i("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=d(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new i("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 i("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 i("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function w(e,t){if(typeof e!="string"||e.length===0)throw new i("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new i("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,a=J(n);if(a.alg!=="ES256")throw new i("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await me(t.jwksUri,typeof a.kid=="string"?a.kid:void 0),d;try{d=await ue(p);}catch(b){throw b instanceof i?b:new i("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=v(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new i("Malformed JWT signature.","TOKEN_MALFORMED")}let f=new TextEncoder().encode(`${n}.${s}`),y;try{y=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,m,f);}catch{throw new i("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!y)throw new i("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let c=J(s),h=t.clockToleranceSeconds??60,S=Math.floor(Date.now()/1e3);if(typeof c.exp!="number")throw new i("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(c.exp+h<S)throw new i("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof c.nbf=="number"&&c.nbf-h>S)throw new i("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof c.iss!="string"||c.iss!==t.issuer)throw new i("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!le(c.aud,t.audience))throw new i("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof c.sub=="string"?c.sub:null,membership:fe(c),claims:c}}var he="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",A={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"}}}},L={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 ge=new Set(["__proto__","constructor","prototype"]),be=64,_e=5e4;function F(e,t,r){let s=A[e].responseSchemas;Object.hasOwn(s,String(t))||P();let o=s[String(t)];if(o===null){r!==null&&P();return}let a={nodes:0};return l(r,g(o),0,a)||P(),r}function l(e,t,r,n){if(n.nodes+=1,r>be||n.nodes>_e)return false;if(typeof t.$ref=="string"){let o=Ie(t.$ref);if(o===null||!l(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>l(e,g(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>l(e,g(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=>Se(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?we(e,t):typeof e=="number"?Ee(e,t):Array.isArray(e)?Oe(e,t,r,n):E(e)?Te(e,t,r,n):typeof e=="boolean"}function Se(e,t){switch(t){case "null":return e===null;case "object":return E(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 we(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!Ae(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 Ae(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 Ee(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Oe(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=g(t.items);return e.every(o=>l(o,s,r+1,n))}function Te(e,t,r,n){let s=Object.keys(e);if(s.some(a=>ge.has(a))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=E(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(a=>!l(a,g(t.propertyNames),r+1,n))||Array.isArray(t.required)&&t.required.some(a=>typeof a!="string"||!Object.hasOwn(e,a)))return false;for(let[a,p]of Object.entries(e)){let d=o[a];if(d!==void 0){if(!l(p,g(d),r+1,n))return false;continue}if(t.additionalProperties===false||E(t.additionalProperties)&&!l(p,t.additionalProperties,r+1,n))return false}return true}function Ie(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(L,r)?g(L[r]):null}function g(e){return E(e)||P(),e}function E(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function P(){throw new TypeError("Admin API response does not match its generated contract.")}var ke=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Pe=1024*1024,xe=1e4,O=class extends Error{status;code;requestId;problem;retryAfter;constructor(t){super(t.problem.detail),this.name="AuthOwlAdminApiError",this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.problem=t.problem,this.retryAfter=t.retryAfter;}},_=class extends Error{kind;requestId;constructor(t,r){super(t==="aborted"?"The AuthOwl Admin API request was aborted.":t==="timeout"?"The AuthOwl Admin API request timed out.":t==="response_too_large"?"The AuthOwl Admin API response exceeded the allowed size.":t==="invalid_response"?"The AuthOwl Admin API returned an invalid response.":"The AuthOwl Admin API request could not be completed."),this.name="AuthOwlAdminNetworkError",this.kind=t,this.requestId=r;}};function je(e){ve();let t=Le(e?.secretKey),r=Re(e?.apiUrl),n=e?.fetch??globalThis.fetch;if(typeof n!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let s=n,o$1=async(p$1,d)=>{let m=d??{},f=A[p$1],y=new URL(Ne(f.path,m).replace(/^\/+/,""),r);ze(y,m);let c=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});$e(c,m);let h="body"in m?JSON.stringify(m.body):void 0;h!==void 0&&c.set("content-type","application/json");let S;try{S=await p({fetchImpl:s,url:y,init:{method:f.method,headers:c,body:h,signal:d?.signal},timeoutMs:xe,maxResponseBytes:Pe,allowHttpLoopback:r.protocol==="http:",decode:(u,X)=>F(p$1,X.status,u)});}catch(u){throw u instanceof O?u:u instanceof o?new _(u.kind,u.requestId):new _("network")}let{response:b,requestId:z,data:$}=S;if(!b.ok)throw Ue(b,$,z);if(!f.successStatuses.some(u=>u===b.status))throw new _("invalid_response",z);return $},a=Object.assign(Object.create(null),{request:o$1});for(let p of Object.keys(A))a[p]=d=>o$1(p,d);return Object.freeze(a)}function ve(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function Le(e){if(typeof e!="string"||!ke.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function Re(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=c(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 Ne(e,t){let r="path"in t&&x(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 ze(e,t){if(!(!("query"in t)||!x(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 $e(e,t){if(!(!("header"in t)||!x(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 Ue(e,t,r){let n=r??G(e.headers.get("x-request-id"),256),s=G(e.headers.get("retry-after"),128),o=Me(e.status,n),a=Ke(t)?t:o;return new O({status:e.status,code:a.code,requestId:n,problem:a,retryAfter:s})}function Me(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 Ke(e){return x(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 x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function G(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var Ce=/^v1=([a-f0-9]{64})$/i,De=/^whsec_[A-Za-z0-9_-]{1,256}$/,We=/^(0|[1-9]\d{0,10})$/;async function qe(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=Je(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=Be(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!We.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let a=Ve(e.signatureHeader);if(a.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 f of t){let y=await crypto.subtle.importKey("raw",new TextEncoder().encode(f),{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=new Uint8Array(await crypto.subtle.sign("HMAC",y,d));for(let h of a)m=Fe(c,h)||m;}return m}function Je(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!De.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function Ve(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=Ce.exec(n.trim());s&&r.push(He(s[1]));}return r}function Be(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 He(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 Fe(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 Ge="/.well-known/oauth-protected-resource";function R(e,t){let r;try{r=new URL(e);}catch{throw new TypeError(`${t} must be an absolute URL.`)}let n=r.hostname==="localhost"||r.hostname==="127.0.0.1"||r.hostname==="[::1]";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n))throw new TypeError(`${t} must use HTTPS, except on a loopback host.`);if(r.hash)throw new TypeError(`${t} must not contain a fragment.`);if(r.username||r.password)throw new TypeError(`${t} must not contain embedded credentials.`);return r}function Y(e){let t=R(e,"resource"),r=t.pathname==="/"?"":t.pathname.replace(/\/+$/,"");return `${t.origin}${Ge}${r}${t.search}`}function Ye(e){if(R(e.resource,"resource"),e.authorizationServers.length===0)throw new Error("An MCP server must name at least one authorization server, or no client can authenticate to it.");for(let t of e.authorizationServers)R(t,"authorization server");return Object.freeze({resource:e.resource,authorization_servers:Object.freeze([...e.authorizationServers]),bearer_methods_supported:Object.freeze(["header"]),...e.scopesSupported?.length?{scopes_supported:Object.freeze([...e.scopesSupported])}:{},...e.resourceName?{resource_name:e.resourceName}:{}})}function Ze(e){let t=[`resource_metadata="${Y(e.resource)}"`];return e.error&&t.push(`error="${e.error}"`),e.error&&e.errorDescription&&t.push(`error_description="${e.errorDescription.replace(/["\\\r\n]/g,"")}"`),`Bearer ${t.join(", ")}`}var Z=["publishableKey","apiUrl","issuer","jwksUri","audience"],Xe=new Set([...Z,"clockToleranceSeconds"]);function N(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=>!Xe.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(Z.filter(p=>Object.prototype.hasOwnProperty.call(e??{},p))),r=t.has("publishableKey")||t.has("apiUrl"),n$1=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n$1)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n$1){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 k({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 a=n({publishableKey:s,apiUrl:o});return k({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},a.decoded.env==="test")}async function ht(e,t){return w(e,N(t))}async function gt(e,t,r){let n=N(r);try{let s=await w(e,n);return E$1(s.membership,t)}catch{return false}}async function bt(e,t,r){let n=N(r);try{let s=await w(e,n);return B$1(s.membership,t.permission)}catch{return false}}export{he as ADMIN_API_SPEC_SHA256,O as AuthOwlAdminApiError,_ as AuthOwlAdminNetworkError,i as TokenVerificationError,je as createAdminClient,gt as has,bt as hasPermission,Ye as mcpProtectedResourceMetadata,Y as mcpProtectedResourceMetadataUrl,Ze as mcpUnauthorizedChallenge,ye as verifyProjectToken,ht as verifyToken,qe as verifyWebhook};
|
|
1
|
+
import {d,c,E,B,p,o,n,z as z$1}from'./chunk-IB6TFQFD.js';export{l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,m as resolveAuthTarget,n as resolveConfig,b as sessionCookieName}from'./chunk-IB6TFQFD.js';var le=new Set(["session","template","access","id"]);function X(e){return typeof e=="string"&&le.has(e)}var i=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},fe=300*1e3,he=5e3,ye=64*1024,ge=64,be=60*1e3,H=new Map,F=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 G(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new i("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 i("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof i?t:new i("Malformed JWT segment.","TOKEN_MALFORMED")}}function Q(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function Y(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&$(e).byteLength===32}function _e(e){if(!Q(e))throw new i("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 i("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)||!Y(e.x)||!Y(e.y))throw new i("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 we(e){if(!Q(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new i("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>ge)throw new i("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(_e),r=new Set;for(let n of t){if(r.has(n.kid))throw new i("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function Z(e,t){let r=H.get(e);if(!t&&r&&Date.now()-r.fetchedAt<fe)return r.keys;try{let n=await p({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:he,maxResponseBytes:ye,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>z$1(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=we(n.data);return H.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof o)switch(n.kind){case "timeout":throw new i("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new i("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new i("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new i("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function Se(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await Z(e,false));if(!n){let s=F.get(e)??0;Date.now()-s>=be&&(F.set(e,Date.now()),n=r(await Z(e,true)));}if(!n)throw new i("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function Te(e){let t=globalThis.crypto?.subtle;if(!t)throw new i("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 Ae(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function Ee(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(p=>typeof p=="string"):[],o=Array.isArray(r.roles)?r.roles.filter(p=>typeof p=="string"):void 0,a=Array.isArray(r.teams)?r.teams.filter(p=>typeof p=="string"):void 0;return n===""&&s.length===0&&!o?.length&&!a?.length?null:{role:n,...o===void 0?{}:{roles:o},permissions:s,...a===void 0?{}:{teams:a}}}async function ke(e,t){return f(e,L(t))}function L(e,t=false){if(!e||typeof e!="object")throw new i("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=d(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new i("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 i("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.tokenUse!==void 0&&!X(e.tokenUse))throw new i("Token verifier tokenUse is invalid.","TOKEN_CONFIG_INVALID");if(e.requireTokenUse!==void 0&&typeof e.requireTokenUse!="boolean")throw new i("Token verifier requireTokenUse must be a boolean.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new i("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function f(e,t){if(typeof e!="string"||e.length===0)throw new i("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new i("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,a=G(n);if(a.alg!=="ES256")throw new i("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await Se(t.jwksUri,typeof a.kid=="string"?a.kid:void 0),c;try{c=await Te(p);}catch(E){throw E instanceof i?E:new i("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 i("Malformed JWT signature.","TOKEN_MALFORMED")}let g=new TextEncoder().encode(`${n}.${s}`),b;try{b=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},c,m,g);}catch{throw new i("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!b)throw new i("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let d=G(s),_=t.clockToleranceSeconds??60,A=Math.floor(Date.now()/1e3);if(typeof d.exp!="number")throw new i("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(d.exp+_<A)throw new i("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof d.nbf=="number"&&d.nbf-_>A)throw new i("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof d.iss!="string"||d.iss!==t.issuer)throw new i("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!Ae(d.aud,t.audience))throw new i("Token audience mismatch.","TOKEN_CLAIM_INVALID");let u=d.token_use;if(u===void 0){if(t.requireTokenUse===true||a.typ!=="JWT")throw new i("Token purpose is missing or unsupported.","TOKEN_USE_UNSUPPORTED")}else if(!X(u)||(t.tokenUse===void 0?u==="id":u!==t.tokenUse)||a.typ!==(u==="access"?"at+jwt":"JWT"))throw new i("Token purpose is missing or unsupported.","TOKEN_USE_UNSUPPORTED");return {sub:typeof d.sub=="string"?d.sub:null,membership:Ee(d),claims:d}}var M="Authentication is required.",h=class extends Error{reason;status;cause;constructor(t,r,n){super(r),this.name="AuthorizationError",this.reason=t,this.status=t==="unauthenticated"?401:403,Object.defineProperty(this,"cause",{value:n,enumerable:false,writable:false,configurable:true});}};function Oe(e){if(typeof e!="object"||e===null)return false;let t=e;return t.name==="AuthorizationError"&&typeof t.message=="string"&&(t.reason==="unauthenticated"&&t.status===401||t.reason==="forbidden"&&t.status===403)}var Ie=new Set(["TOKEN_VERIFICATION_FAILED","TOKEN_MALFORMED","TOKEN_ALGORITHM_UNSUPPORTED","TOKEN_SIGNATURE_INVALID","TOKEN_CLAIM_INVALID","TOKEN_USE_UNSUPPORTED","JWKS_KEY_NOT_FOUND"]);function Pe(e){if(typeof e!="string"||e.trim().length===0)throw new h("unauthenticated",M);return e}function k(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`${t} needs a non-empty value.`)}async function O(e,t){let r=Pe(t),n;try{n=await e(r);}catch(s){throw s instanceof i&&Ie.has(s.code)?new h("unauthenticated",M,s):s}if(n.sub===null||n.sub.trim().length===0)throw new h("unauthenticated",M);return n}async function ee(e,t,r){if(r.role===void 0&&r.permission===void 0&&r.teamId===void 0)throw new TypeError("requireGrant needs at least one of role, permission, or teamId.");r.role!==void 0&&k(r.role,"requireGrant role"),r.permission!==void 0&&k(r.permission,"requireGrant permission"),r.teamId!==void 0&&k(r.teamId,"requireGrant teamId");let n=await O(e,t);if(!E(n.membership,r))throw new h("forbidden","Token does not grant the required access.");return n}async function te(e,t,r){k(r,"requireOrg organization id");let n=await O(e,t);if(n.claims.org_id!==r)throw new h("forbidden","Token was not minted for this organization.");return n}async function re(e,t,r){k(r,"requirePermission permission");let n=await O(e,t);if(!B(n.membership,r))throw new h("forbidden","Token does not grant the required permission.");return n}var xe="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",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"}}},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"}}}},D={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 je=new Set(["__proto__","constructor","prototype"]),Ue=64,Ne=5e4;function ne(e,t,r){let s=I[e].responseSchemas;Object.hasOwn(s,String(t))||z();let o=s[String(t)];if(o===null){r!==null&&z();return}let a={nodes:0};return y(r,w(o),0,a)||z(),r}function y(e,t,r,n){if(n.nodes+=1,r>Ue||n.nodes>Ne)return false;if(typeof t.$ref=="string"){let o=$e(t.$ref);if(o===null||!y(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>y(e,w(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>y(e,w(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"?Re(e,t):typeof e=="number"?ze(e,t):Array.isArray(e)?Ke(e,t,r,n):P(e)?Ce(e,t,r,n):typeof e=="boolean"}function ve(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 Re(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!Le(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 Le(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 ze(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Ke(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=w(t.items);return e.every(o=>y(o,s,r+1,n))}function Ce(e,t,r,n){let s=Object.keys(e);if(s.some(a=>je.has(a))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=P(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(a=>!y(a,w(t.propertyNames),r+1,n))||Array.isArray(t.required)&&t.required.some(a=>typeof a!="string"||!Object.hasOwn(e,a)))return false;for(let[a,p]of Object.entries(e)){let c=o[a];if(c!==void 0){if(!y(p,w(c),r+1,n))return false;continue}if(t.additionalProperties===false||P(t.additionalProperties)&&!y(p,t.additionalProperties,r+1,n))return false}return true}function $e(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(D,r)?w(D[r]):null}function w(e){return P(e)||z(),e}function P(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function z(){throw new TypeError("Admin API response does not match its generated contract.")}var Me=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,De=1024*1024,qe=1e4,x=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,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 We(e){Ve();let t=Je(e?.secretKey),r=Be(e?.apiUrl),n=e?.fetch??globalThis.fetch;if(typeof n!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let s=n,o$1=async(p$1,c)=>{let m=c??{},g=I[p$1],b=new URL(He(g.path,m).replace(/^\/+/,""),r);Fe(b,m);let d=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Ge(d,m);let _="body"in m?JSON.stringify(m.body):void 0;_!==void 0&&d.set("content-type","application/json");let A;try{A=await p({fetchImpl:s,url:b,init:{method:g.method,headers:d,body:_,signal:c?.signal},timeoutMs:qe,maxResponseBytes:De,allowHttpLoopback:r.protocol==="http:",decode:(l,ae)=>ne(p$1,ae.status,l)});}catch(l){throw l instanceof x?l:l instanceof o?new T(l.kind,l.requestId):new T("network")}let{response:u,requestId:E,data:W}=A;if(!u.ok)throw Ye(u,W,E);if(!g.successStatuses.some(l=>l===u.status))throw new T("invalid_response",E);return W},a=Object.assign(Object.create(null),{request:o$1});for(let p of Object.keys(I))a[p]=c=>o$1(p,c);return Object.freeze(a)}function Ve(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function Je(e){if(typeof e!="string"||!Me.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function Be(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=c(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 He(e,t){let r="path"in t&&K(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 Fe(e,t){if(!(!("query"in t)||!K(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 Ge(e,t){if(!(!("header"in t)||!K(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 Ye(e,t,r){let n=r??se(e.headers.get("x-request-id"),256),s=se(e.headers.get("retry-after"),128),o=Ze(e.status,n),a=Xe(t)?t:o;return new x({status:e.status,code:a.code,requestId:n,problem:a,retryAfter:s})}function Ze(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 Xe(e){return K(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 K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function se(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var Qe=/^v1=([a-f0-9]{64})$/i,et=/^whsec_[A-Za-z0-9_-]{1,256}$/,tt=/^(0|[1-9]\d{0,10})$/;async function rt(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=nt(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=ot(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!tt.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let a=st(e.signatureHeader);if(a.length===0)return false;let p=new TextEncoder().encode(`${e.timestamp}.`),c=new Uint8Array(p.byteLength+s.byteLength);c.set(p),c.set(s,p.byteLength);let m=false;for(let g of t){let b=await crypto.subtle.importKey("raw",new TextEncoder().encode(g),{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=new Uint8Array(await crypto.subtle.sign("HMAC",b,c));for(let _ of a)m=at(d,_)||m;}return m}function nt(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!et.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function st(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=Qe.exec(n.trim());s&&r.push(it(s[1]));}return r}function ot(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 it(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 at(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 pt="/.well-known/oauth-protected-resource";function q(e,t){let r;try{r=new URL(e);}catch{throw new TypeError(`${t} must be an absolute URL.`)}let n=r.hostname==="localhost"||r.hostname==="127.0.0.1"||r.hostname==="[::1]";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n))throw new TypeError(`${t} must use HTTPS, except on a loopback host.`);if(r.hash)throw new TypeError(`${t} must not contain a fragment.`);if(r.username||r.password)throw new TypeError(`${t} must not contain embedded credentials.`);return r}function oe(e){let t=q(e,"resource"),r=t.pathname==="/"?"":t.pathname.replace(/\/+$/,"");return `${t.origin}${pt}${r}${t.search}`}function dt(e){if(q(e.resource,"resource"),e.authorizationServers.length===0)throw new Error("An MCP server must name at least one authorization server, or no client can authenticate to it.");for(let t of e.authorizationServers)q(t,"authorization server");return Object.freeze({resource:e.resource,authorization_servers:Object.freeze([...e.authorizationServers]),bearer_methods_supported:Object.freeze(["header"]),...e.scopesSupported?.length?{scopes_supported:Object.freeze([...e.scopesSupported])}:{},...e.resourceName?{resource_name:e.resourceName}:{}})}function ct(e){let t=[`resource_metadata="${oe(e.resource)}"`];return e.error&&t.push(`error="${e.error}"`),e.error&&e.errorDescription&&t.push(`error_description="${e.errorDescription.replace(/["\\\r\n]/g,"")}"`),`Bearer ${t.join(", ")}`}var ie=["publishableKey","apiUrl","issuer","jwksUri","audience"],mt=new Set([...ie,"clockToleranceSeconds","tokenUse","requireTokenUse"]);function S(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=>!mt.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(ie.filter(p=>Object.prototype.hasOwnProperty.call(e??{},p))),r=t.has("publishableKey")||t.has("apiUrl"),n$1=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n$1)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n$1){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 L({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds,tokenUse:e.tokenUse,requireTokenUse:e.requireTokenUse})}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 a=n({publishableKey:s,apiUrl:o});return L({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds,tokenUse:e?.tokenUse,requireTokenUse:e?.requireTokenUse},a.decoded.env==="test")}function j(e){return {...e,tokenUse:"session"}}async function vt(e,t){return f(e,S(t))}async function Rt(e,t,r){let n=S(r);try{let s=await f(e,j(n));return E(s.membership,t)}catch{return false}}async function Lt(e,t,r){let n=S(r);try{let s=await f(e,j(n));return B(s.membership,t.permission)}catch{return false}}async function zt(e,t){let r=S(t);return O(n=>f(n,r),e)}async function Kt(e,t,r){let n=S(r);return re(s=>f(s,j(n)),e,t)}async function Ct(e,t,r){let n=S(r);return ee(s=>f(s,j(n)),e,t)}async function $t(e,t,r){let n=S(r);return te(s=>f(s,j(n)),e,t)}export{xe as ADMIN_API_SPEC_SHA256,x as AuthOwlAdminApiError,T as AuthOwlAdminNetworkError,h as AuthorizationError,i as TokenVerificationError,We as createAdminClient,Rt as has,Lt as hasPermission,Oe as isAuthorizationError,dt as mcpProtectedResourceMetadata,oe as mcpProtectedResourceMetadataUrl,ct as mcpUnauthorizedChallenge,zt as requireAuth,Ct as requireGrant,$t as requireOrg,Kt as requirePermission,ke as verifyProjectToken,vt as verifyToken,rt as verifyWebhook};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-T5SH3ZZP.js';var p="authowl_handoff_verifier",c="authowl_code",S=32,m=900,w=["email","providerId","domain","organizationSlug"];function g(e){let n="";for(let o of e)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function h(e){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return g(new Uint8Array(n))}function y(){return g(crypto.getRandomValues(new Uint8Array(S)))}function d(e,n){let o=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${p}=${e}; Path=/; Max-Age=${n}; SameSite=Lax${o}`;}function R(){for(let e of document.cookie.split(";")){let n=e.indexOf("=");if(!(n<0)&&e.slice(0,n).trim()===p)return e.slice(n+1).trim()||null}return null}function
|
|
2
|
-
export{
|
|
1
|
+
import {a}from'./chunk-T5SH3ZZP.js';var p="authowl_handoff_verifier",c="authowl_code",S=32,m=900,w=["email","providerId","domain","organizationSlug"];function g(e){let n="";for(let o of e)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function h(e){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return g(new Uint8Array(n))}function y(){return g(crypto.getRandomValues(new Uint8Array(S)))}function d(e,n){let o=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${p}=${e}; Path=/; Max-Age=${n}; SameSite=Lax${o}`;}function R(){for(let e of document.cookie.split(";")){let n=e.indexOf("=");if(!(n<0)&&e.slice(0,n).trim()===p)return e.slice(n+1).trim()||null}return null}function U(){d("",0);}function u(e){return new URL(e,window.location.href).toString()}async function P(e,n){let o=n.callbackURL?u(n.callbackURL):null;if(o&&new URL(o).origin!==window.location.origin)return null;let r=y(),i=new URL(`${e.projectBaseURL}/session/start`);if(i.searchParams.set("pk",e.publishableKey),i.searchParams.set("kind",n.kind),n.kind==="social")i.searchParams.set("provider",n.provider),n.scopes?.length&&i.searchParams.set("scopes",n.scopes.join(",")),n.loginHint&&i.searchParams.set("loginHint",n.loginHint),n.requestSignUp!==void 0&&i.searchParams.set("requestSignUp",n.requestSignUp?"1":"0");else for(let s of w){let t=n[s];t&&i.searchParams.set(s,t);}let a=`${window.location.origin}${window.location.pathname}${window.location.search}`;i.searchParams.set("cb",o??a);for(let[s,t]of [["err",n.errorCallbackURL],["new",n.newUserCallbackURL]])t&&i.searchParams.set(s,u(t));return i.searchParams.set("challenge",await h(r)),d(r,m),i.toString()}function f(e){if(typeof window>"u")return null;let n=window.location.hash;if(!n.includes(c))return null;let o=new URLSearchParams(n.replace(/^#/,"")),r=o.get(c);if(!r||e!==void 0&&r!==e)return null;o.delete(c);let i=o.toString();return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${i?`#${i}`:""}`),r}async function k(e,n,o){if(!a())return false;let r=o??f();if(!r)return false;o&&f(o);let i=R();if(U(),!i)return false;await n.prepareSession({remember:true});let{error:a$1}=await e.request("/session/exchange",{method:"POST",body:{code:r,verifier:i}});return a$1===null}
|
|
2
|
+
export{P as beginCrossSiteSignIn,h as challengeFor,k as completeCrossSiteSignIn,f as takeHandoffCode};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var S="pop+jwt",k="ES256",P="authowl-session-proof",c="origin-keys";var l=new Map;async function f(e,t,n,o){let r=new AbortController,i,s=new Promise((y,m)=>{i=setTimeout(()=>{r.abort(),m(new Error("AuthOwl session transport request timed out."));},o);});try{return await Promise.race([e(t,{...n,signal:r.signal}),s])}finally{clearTimeout(i);}}async function T(e,t,n){let o=await f(e,t,{method:"POST",credentials:"include",headers:n},1e4);if(o.status===404||o.status===405)return "legacy";if(o.status!==204)throw new Error("AuthOwl cookie capability check failed.");let r=await f(e,t,{method:"GET",credentials:"include",headers:n},1e4);if(r.status===404||r.status===405)return "legacy";if(r.status!==200)throw new Error("AuthOwl cookie capability check failed.");let i=await r.text();if(new TextEncoder().encode(i).byteLength>128)throw new Error("AuthOwl cookie capability response is invalid.");let s;try{s=JSON.parse(i);}catch{throw new Error("AuthOwl cookie capability response is invalid.")}if(!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).length!==1||typeof s.cookieSupported!="boolean")throw new Error("AuthOwl cookie capability response is invalid.");return s.cookieSupported}async function O(e,t,n,o){let r=new Headers(n);r.set("authorization",o),r.set("x-authowl-session-transport","bearer");try{await f(e,t,{method:"POST",credentials:"include",headers:r},2e3);}catch{}}async function C(e){let{tokens:t}=e;if(t.beginSession(e.start),!e.clientOrigin)return {binding:null,cookieOnly:false};let n=null;if(t.hasToken()){let i=t.bindingThumbprint();if(i)try{let s=await d(e.clientOrigin);if(s.thumbprint!==i)throw new Error("Session proof key changed.");n=s;}catch{let s=new Headers;t.declareOn(s);let y=s.get("authorization");y&&await O(e.fetcher,`${e.projectBaseURL}/session/abandon`,e.headers,y),t.endSession(),t.beginSession(e.start);}}let o;try{o=await T(e.fetcher,`${e.projectBaseURL}/session/cookie-capability`,e.headers);}catch{return t.useCookieTransport(),{binding:null,cookieOnly:false}}if(o==="legacy")return {binding:null,cookieOnly:false};if(o)return t.hasToken()?{binding:null,cookieOnly:true}:(t.useCookieTransport(),{binding:null,cookieOnly:false});let r=n??await d(e.clientOrigin);return t.useBoundBearerTransport(r.thumbprint,r.persistent),{binding:{key:r,nonce:_()},cookieOnly:false}}function a(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function u(e){return new TextEncoder().encode(e)}async function b(e){return a(new Uint8Array(await crypto.subtle.digest("SHA-256",u(e))))}function g(e){return e.kty==="EC"&&e.crv==="P-256"&&typeof e.x=="string"&&e.x.length>0&&typeof e.y=="string"&&e.y.length>0&&e.d===void 0}async function w(e){return b(JSON.stringify({crv:e.crv,kty:e.kty,x:e.x,y:e.y}))}function A(e){if(!e||typeof e!="object")return false;let t=e,n=t.algorithm;return t.type==="private"&&t.extractable===false&&t.usages.length===1&&t.usages[0]==="sign"&&n.name==="ECDSA"&&n.namedCurve==="P-256"}function J(){l.clear();}async function K(e){if(!e||typeof e!="object")return null;let t=e;if(!A(t.privateKey)||!t.publicJwk||!g(t.publicJwk))return null;let n=await w(t.publicJwk);return t.thumbprint!==n?null:{privateKey:t.privateKey,publicJwk:t.publicJwk,thumbprint:n,persistent:true}}function h(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise(e=>{let t;try{t=indexedDB.open(P,1);}catch{e(null);return}t.onupgradeneeded=()=>{t.result.objectStoreNames.contains(c)||t.result.createObjectStore(c,{keyPath:"origin"});},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);})}async function p(e){let t=await h();if(!t)return null;try{let n=await new Promise(o=>{let r=t.transaction(c,"readonly").objectStore(c).get(e);r.onsuccess=()=>o(r.result),r.onerror=()=>o(null);});return await K(n)}finally{t.close();}}async function E(e,t){let n=await h();if(!n)return "unavailable";try{return await new Promise(o=>{let r;try{r=n.transaction(c,"readwrite"),r.objectStore(c).add({origin:e,privateKey:t.privateKey,publicJwk:t.publicJwk,thumbprint:t.thumbprint});}catch{o("unavailable");return}r.oncomplete=()=>o("stored"),r.onerror=()=>{let i=r.error;o(i?.name==="ConstraintError"?"conflict":"unavailable");},r.onabort=()=>{let i=r.error;o(i?.name==="ConstraintError"?"conflict":"unavailable");};})}finally{n.close();}}async function B(){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},false,["sign","verify"]),t=await crypto.subtle.exportKey("jwk",e.publicKey);if(!g(t))throw new Error("The browser produced an invalid proof key.");return {privateKey:e.privateKey,publicJwk:t,thumbprint:await w(t),persistent:false}}function d(e){let t=l.get(e);if(t)return t;let n=(async()=>{let o=await p(e);if(o)return o;let r=await B(),i=await E(e,r);return i==="stored"?{...r,persistent:true}:i==="conflict"?await p(e)??r:r})();return l.set(e,n),n.catch(()=>l.delete(e)),n}function _(){return a(crypto.getRandomValues(new Uint8Array(32)))}function I(e){let t=new URL(e);return t.search="",t.hash="",t.toString()}async function x(e){let t=a(u(JSON.stringify({typ:S,alg:k,jwk:e.key.publicJwk}))),n=a(u(JSON.stringify({htm:e.method.toUpperCase(),htu:I(e.url),iat:Math.floor(Date.now()/1e3),jti:a(crypto.getRandomValues(new Uint8Array(16))),ath:await b(e.token)}))),o=`${t}.${n}`,r=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.key.privateKey,u(o));return `${o}.${a(new Uint8Array(r))}`}async function v(e){let t=await d(e.origin);if(t.thumbprint!==e.expectedThumbprint)throw new Error("Session proof key changed.");return x({key:t,method:e.method,url:e.url,token:e.token})}
|
|
2
|
+
export{O as abandonSession,_ as bindingNonce,f as boundedSessionFetch,J as clearSessionProofKeyMemoryForTests,T as cookieCapability,x as createSessionProof,v as createStoredSessionProof,C as prepareSenderConstrainedSession,d as sessionProofKey};
|
package/package.json
CHANGED
package/dist/chunk-V3MSLXXB.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var ce=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,de=/^sk_/i;function J(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(de.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=ce.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1].toLowerCase(),env:t[2].toLowerCase(),projectId:t[3].toLowerCase()}}function $e(e,t){let n=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}function O(e,t){try{return e?.getItem(t)??null}catch{return null}}function A(e,t,n){try{n===null?e?.removeItem(t):e?.setItem(t,n);}catch{}}function _(){try{return globalThis.localStorage}catch{return}}function x(){try{return globalThis.sessionStorage}catch{return}}var pe="authowl.session-challenge",fe=e=>`${pe}.${e}`,he="set-auth-challenge",D="x-authowl-challenge";function Ge(e){let t=e.get(D);return H(t)?z(t).some(([n,r])=>n.endsWith(".dont_remember")&&r.length>0):false}var Ye="INVALID_TWO_FACTOR_COOKIE",be=2048,H=e=>e!==null&&e.length<=be,$=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function z(e){let t=[];for(let n of e.split(";")){let r=n.trimStart(),o=r.indexOf("=");o<=0||t.push([r.slice(0,o).trimEnd(),r.slice(o+1)]);}return t}function M(e){let t=fe(e),n=new Map;function r(){return n.size===0?null:[...n].map(([s,a])=>`${s}=${a}`).join("; ")}function o(){let s=r();A(x(),t,H(s)?s:null);}function c(s){for(let[a,l]of z(s))$.test(a)&&(l===""?n.delete(a):$.test(l)&&n.set(a,l));}let u=O(x(),t);return H(u)&&c(u),{presentOn(s){let a=r();s.delete(D),H(a)&&s.set(D,a);},observe(s){let a=s.get(he);H(a)&&(c(a),o());},clear(){n.clear(),o();}}}var W="set-auth-token",G="x-authowl-session-transport",Y="bearer";var j=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function m(e,t){throw new Error(`${e}: ${t}`)}function ge(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function Q(e,{label:t,allowHttpLoopback:n}){(typeof e!="string"||e.length===0)&&m(t,"required"),e!==e.trim()&&m(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&m(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&m(t,"path must be unencoded");let r;try{r=new URL(e);}catch{m(t,"absolute URL required");}return (r.username||r.password)&&m(t,"credentials forbidden"),r.protocol!=="https:"&&r.protocol!=="http:"&&m(t,"HTTPS required"),r.protocol==="http:"&&(!n||!j.test(e))&&m(t,"HTTPS required except exact loopback"),r}function Z(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&&j.test(r)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function X(e,t,n){let r=ge(e);(r.includes("//")||r.split("/").some(o=>o==="."||o==="..")||r!==""&&r!==t.pathname)&&m(n,"path traversal or duplicate separator");}function ee(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&m("apiUrl","origin required");let n;try{n=new URL(e);}catch{m("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!j.test(e))&&m("apiUrl","HTTPS required except exact loopback"),n.origin}function Ze(e,t,n={allowHttpLoopback:false}){let r=Q(e,{label:"issuer",allowHttpLoopback:n.allowHttpLoopback}),o=Q(t,{label:"jwksUri",allowHttpLoopback:n.allowHttpLoopback});return X(e,r,"issuer"),X(t,o,"jwksUri"),r.pathname!=="/"&&r.pathname.endsWith("/")&&m("issuer","trailing slash forbidden"),{issuer:r.toString().replace(/\/$/,""),jwksUri:o.toString()}}var me="authowl.session-token",ye="authowl.cookie-transport",ne="ok",re="bearer",we=e=>`${me}.${e}`,Re=e=>`${ye}.${e}`;function Te(e){return e===ne?"cookies":e===re?"bearer":"unknown"}function ke(e){return e==="cookies"?ne:e==="bearer"?re:null}function Se(e){let t=we(e),n=Re(e),r=M(e),o=null,c=false,u=null,s=Te(O(_(),n)),a=()=>s==="unknown",l=0,d=null,w=false;function b(){let i=O(x(),t);if(i!==null)return c=true,i;let g=O(_(),t);return g!==null?(c=false,g):null}o=b(),o!==null&&a()&&(w=true);function E(){if(!(!w||!d)){w=false;try{d();}catch{}}}function R(){let i=s==="bearer"?o:null,[g,K]=c?[x(),_()]:[_(),x()];A(K,t,null),A(g,t,i);}function L(i){i!==null&&u!==null&&(c=u,u=null),o=i,R(),i!==null&&a()&&(w=true,E());}function p(i){s=i,A(_(),n,ke(i));}function T(){p("unknown"),w=false;}function k(){return o===null&&(o=b()),o}function P(){let i=b();return i!==null&&(o=i),o}function C(i){P()===i&&R();}function U(){l+=1,u=null,c=false,L(null),r.clear(),T();}let v=()=>s!=="cookies";return {hasToken:()=>k()!==null,declareOn(i){if(i.has("authorization"))return false;let g=k();return !g&&!v()?false:(g&&i.set("authorization",`Bearer ${g}`),i.set(G,Y),r.presentOn(i),true)},wantsToken:v,needsProbe:a,observe(i){let g=i.get(W);g&&L(g),r.observe(i);},dropChallenge:r.clear,measureWith(i){d=i,E();},beginRead(){let i=k(),g=l;return {carriedToken:i!==null,endIfDead(){i!==null&&P()===i&&l===g&&U();},recordCookieVerdict(K){if(l===g&&a()){if(p(K?"cookies":"bearer"),K){L(null);return}C(i);}}}},beginSession({remember:i}){l+=1,u=!i,r.clear(),T();},endSession:U}}var te=new Map;function oe(e){let t=te.get(e);if(t)return t;let n=Se(e);return te.set(e,n),n}function Ee(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function se(e,t){let n=oe(e),r=(u,s)=>(t??globalThis.fetch)(u,s);return {fetch:async(u,s)=>{if(s?.credentials==="omit"||!n.wantsToken())return r(u,s);let a=Ee(u,s),l=n.declareOn(a),d=await r(u,{...s,headers:a});return l&&n.observe(d.headers),d},probe:r,tokens:n}}function xe(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=J(e.publishableKey),n=ee(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:n,decoded:t,projectBaseURL:`${n}/api/projects/${t.projectId}/auth`}}function ct(e){let t=xe(e),{fetch:n,...r}=se(t.decoded.projectId,e.fetch);return {...e,...t,fetch:n,session:r}}var Oe=1e4,Ae=1024*1024,N=class extends Error{kind;requestId;constructor(t,n){super(Ke(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},ue=new WeakSet;function f(e,t){let n=new N(e,t);return ue.add(n),n}async function ft({fetchImpl:e,url:t,init:n={},timeoutMs:r=Oe,maxResponseBytes:o=Ae,allowHttpLoopback:c=false,decode:u}){ae(r,"timeoutMs"),ae(o,"maxResponseBytes");let s=Z(t,{allowHttpLoopback:c}),a=n.signal,l=new AbortController,d=null,w,b=new Promise(p=>{w=p;}),E=p=>{d===null&&(d=p,w({type:"abort",kind:p}),l.abort());},R=()=>E("aborted");a?.addEventListener("abort",R,{once:true});let L=setTimeout(()=>E("timeout"),r);a?.aborted&&R();try{if(d!==null)throw f(d);let p;try{p=await Promise.race([e(s.toString(),{...n,redirect:"error",signal:l.signal}).then(v=>({type:"response",response:v})),b]);}catch{throw f(d??"network")}if(p.type==="abort")throw f(p.kind);if(!_e(p.response))throw f("invalid_response");let T=p.response,k=ve(T.headers),P=await Le(T,o,b,()=>d,k),C=Pe(T,P,k),U;try{U=T.ok&&u?u(C,Object.freeze({status:T.status})):C;}catch{throw f("invalid_response",k)}return {response:T,data:U,...k===void 0?{}:{requestId:k}}}catch(p){throw p instanceof N&&ue.has(p)?p:f(d??"network")}finally{clearTimeout(L),a?.removeEventListener("abort",R);}}function _e(e){if(!e||typeof e!="object")return false;let t=e;return Number.isInteger(t.status)&&t.status>=0&&t.status<=599&&typeof t.statusText=="string"&&typeof t.ok=="boolean"&&typeof t.headers?.get=="function"&&(t.body===null||typeof t.body=="object"&&typeof t.body?.getReader=="function"&&typeof t.body.cancel=="function")}async function Le(e,t,n,r,o){let c=e.headers.get("content-length");if(c!==null){if(!/^\d+$/.test(c))throw ie(e.body),f("invalid_response",o);if(Number(c)>t)throw ie(e.body),f("response_too_large",o)}if(!e.body)return "";let u;try{u=e.body.getReader();}catch{throw f("network",o)}let s=[],a=0,l=null;try{for(;;){let b;try{b=await Promise.race([u.read(),n]);}catch{l=f(r()??"network",o);break}if(Ue(b)){l=f(b.kind,o);break}let{done:E,value:R}=b;if(E)break;if(R.byteLength!==0){if(a+=R.byteLength,a>t){l=f("response_too_large",o);break}s.push(R);}}}finally{l&&He(u);try{u.releaseLock();}catch{}}if(l)throw l;let d=new Uint8Array(a),w=0;for(let b of s)d.set(b,w),w+=b.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(d)}catch{throw f("invalid_response",o)}}function Ue(e){return "type"in e&&e.type==="abort"}function ie(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function He(e){try{e.cancel().catch(()=>{});}catch{}}function Pe(e,t,n){if(e.status===204||e.status===205)return null;let r=Ce(e.headers.get("content-type"));if(!e.ok&&(!r||t.length===0))return null;if(!r||t.length===0)throw f("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw f("invalid_response",n)}}function Ce(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function ve(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function ae(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Ke(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."}}function Ne(e,t){return !e||!t?false:e.permissions.includes(t)}function Ie(e,t){return !e||!t?false:e.teams?.includes(t)??false}function De(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function je(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&&!De(e,n)||r!==void 0&&!e.permissions.includes(r)||o!==void 0&&!Ie(e,o))}function bt(e){return {has:t=>je(e,t),hasPermission:t=>Ne(e,t.permission)}}var Be=new Set(["__proto__","constructor","prototype"]);function q(e){(!e||typeof e!="object"||Array.isArray(e))&&h();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&h(),e}function I(e){return typeof e!="string"&&h(),e}function Ve(e){return typeof e!="boolean"&&h(),e}function V(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&h(),e}function B(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&h(),[...e]}function S(e,t){let n=e[t];return n==null||typeof n=="string"?n:h()}function le(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:h()}function mt(e){let t=q(e),n=t.email;return n!==null&&typeof n!="string"&&h(),{id:I(t.id),email:n,emailVerified:Ve(t.emailVerified),createdAt:V(t.createdAt),updatedAt:V(t.updatedAt),...y("phoneNumber",S(t,"phoneNumber")),...y("username",S(t,"username")),...y("displayUsername",S(t,"displayUsername")),...y("firstName",S(t,"firstName")),...y("lastName",S(t,"lastName")),...y("name",S(t,"name")),...y("image",S(t,"image")),...y("twoFactorEnabled",le(t,"twoFactorEnabled"))}}function yt(e){let t=q(e),n=t.membership;return {id:I(t.id),userId:I(t.userId),expiresAt:V(t.expiresAt),...y("activeOrganizationId",S(t,"activeOrganizationId")),...y("activeTeamId",S(t,"activeTeamId")),...y("membership",n==null?n:qe(n)),...y("pendingMfaEnrollment",le(t,"pendingMfaEnrollment"))}}function h(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function wt(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&h(),Fe(e,t,n)}function Fe(e,t=20,n=1e4){return F(e,0,{nodes:0},t,n)}function qe(e){let t=q(e);return {role:I(t.role),...t.roles===void 0?{}:{roles:B(t.roles)},permissions:B(t.permissions),...t.teams===void 0?{}:{teams:B(t.teams)}}}function F(e,t,n,r,o){if(n.nodes+=1,(t>r||n.nodes>o)&&h(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||h(),e;if(Array.isArray(e))return e.map(s=>F(s,t+1,n,r,o));(!e||typeof e!="object")&&h();let c=Object.getPrototypeOf(e);c!==Object.prototype&&c!==null&&h();let u={};for(let[s,a]of Object.entries(e))Be.has(s)&&h(),u[s]=F(a,t+1,n,r,o);return u}function y(e,t){return t===void 0?{}:{[e]:t}}
|
|
2
|
-
export{Fe as A,Ne as B,Ie as C,De as D,je as E,bt as F,J as a,$e as b,Z as c,Ze as d,O as e,A as f,_ as g,Ge as h,Ye as i,W as j,G as k,Y as l,xe as m,ct as n,N as o,ft as p,q,I as r,Ve as s,V as t,B as u,S as v,mt as w,yt as x,h as y,wt as z};
|