@authowl/core 0.22.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1 +1 @@
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
+ import {d,c,F as F$1,C,q as q$1,p,o,A}from'./chunk-YL2FF2VS.js';export{l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,n as resolveAuthTarget,o as resolveConfig,b as sessionCookieName}from'./chunk-YL2FF2VS.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 q$1({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:he,maxResponseBytes:ye,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>A(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 p)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(!F$1(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(!C(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=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 q$1({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 p?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});for(let p of Object.keys(I))a[p]=c=>o(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=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n){if(typeof e?.issuer!="string"||typeof e.jwksUri!="string"||typeof e.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return L({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds,tokenUse:e.tokenUse,requireTokenUse:e.requireTokenUse})}let s,o$1;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$1=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o$1=process.env.AUTHOWL_API_URL;if(!s||!o$1)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=o({publishableKey:s,apiUrl:o$1});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 F$1(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 C(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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authowl/core",
3
- "version": "0.22.1",
3
+ "version": "0.23.0",
4
4
  "description": "Framework-agnostic client for AuthOwl, the multi-tenant auth SaaS.",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -1 +0,0 @@
1
- import {a}from'./chunk-5NL5GJW6.js';import {p,o,i,q as q$1,y,r,t,z,s,w,B as B$1,E as E$1,x,A,v,u}from'./chunk-IB6TFQFD.js';import {a as a$1}from'./chunk-T5SH3ZZP.js';function to(e){let t=e?.enabledMethods??["password"],n=t.includes("password"),i=t.includes("passkey"),o=e?.authentication,a=e?.mfa;return {emailSignUp:o?.email.signUp??t.some(p=>p==="password"||p==="magic_link"||p==="email_otp"),passwordSignUp:o?.password.signUp??n,phoneSignUp:o?.phone.signUp??t.includes("phone_otp"),passwordSignIn:o?.email.signIn.includes("password")??n,passwordMinLength:o?.password.minLength??8,passwordMaxLength:o?.password.maxLength??128,magicLinkSignIn:o?.email.signIn.includes("magic_link")??t.includes("magic_link"),emailOtpSignIn:o?.email.signIn.includes("email_otp")??t.includes("email_otp"),phoneSignIn:o?.phone.signIn??t.includes("phone_otp"),usernameSignIn:o?.username.signIn??false,collectUsername:o?.username.collectOnSignUp??false,passkeySignIn:o?.passkey.signIn??i,passkeyAdd:o?.passkey.add??i,firstLastName:e?.userModel?.firstLastName??false,emailChange:e===null?false:e.userModel?.emailChange??true,accountDeletion:e?.userModel?.accountDeletion??e?.accountDeletion??false,emailVerificationRequired:e?.emailVerification?.required??e?.requireEmailVerification??false,emailVerificationMethod:e?.emailVerification?.method??"link",totp:a?.totp??e?.twoFactor??false,mfaRequired:a?.required??e?.mfaRequired??false,backupCodes:a?.backupCodes??e?.twoFactor??false,legacyNameField:e?.authentication===void 0}}var he=class extends Error{status;requestId;constructor(t,n,i){super(`${t} request failed with status ${n.status}.`),this.name="AuthOwlHttpError",this.status=n.status,this.requestId=i;}};function oe(e,t,n={}){let i=new Headers(n.init?.headers);return i.set("x-publishable-key",e.publishableKey),p({fetchImpl:e.fetch,url:t,init:{...n.init,headers:i},allowHttpLoopback:e.decoded.env==="test",...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.maxResponseBytes===void 0?{}:{maxResponseBytes:n.maxResponseBytes},...n.decode===void 0?{}:{decode:n.decode}})}function Be(e,t){if(!e.response.ok)throw new he(t,e.response,e.requestId);return e.data}var L=new Map,Pn=/^[a-z]{2}$/;function ro(e,t){if(typeof window>"u")return ()=>{};if(t===null)return L.delete(e),()=>{};let n=t.trim().toLowerCase();if(!Pn.test(n))return ()=>{};let i=Symbol(e),o=L.get(e)??[];return o.push({token:i,locale:n}),L.set(e,o),()=>{let a=L.get(e);if(!a)return;let p=a.filter(m=>m.token!==i);p.length===0?L.delete(e):L.set(e,p);}}function je(e){return typeof window>"u"?null:L.get(e)?.at(-1)?.locale??null}var Tn="x-authowl-turnstile-token",Cn="x-authowl-locale",Dn=1e4,zn=32,xn=2e4;function q(e,t){return {post:(n,i,o,a)=>e.request(n,{method:"POST",body:i,fetchOptions:o,decode:a}),mutation:async(n,i)=>{let o=await n;return o.error===null&&(i===void 0||o.data!==null&&i(o.data))&&t(),o}}}function be(e,t=e.projectBaseURL){return {async request(n,i$1={}){let o$1=Un(t,n,i$1.query),a=i$1.method??(i$1.body===void 0?"GET":"POST"),p=new Headers(i$1.fetchOptions?.headers);i$1.fetchOptions?.authChallengeToken&&p.set(Tn,i$1.fetchOptions.authChallengeToken);let m=je(e.decoded.projectId);m&&p.set(Cn,m),i$1.body!==void 0&&p.set("content-type","application/json");let d={method:a,headers:p,credentials:i$1.credentials??"include",...i$1.body===void 0?{}:{body:JSON.stringify(i$1.body)}},h=Object.freeze({method:a,path:n});await i$1.fetchOptions?.onRequest?.(h);let r=Nn(a,i$1.fetchOptions),s;try{s=await En(e,o$1,{...d,signal:i$1.fetchOptions?.signal},r);}catch(b){let C=Je(b);return await i$1.fetchOptions?.onError?.(Ae(h,C,Ln(b))),{data:null,error:C}}let{response:f,requestId:y}=s,u=Hn(n,s.data),g=u;if(f.ok)try{g=Oe(u),i$1.decode&&(g=i$1.decode(g));}catch{let b=Je(new o("invalid_response",y));return await i$1.fetchOptions?.onError?.(Ae(h,b,"invalid_response")),{data:null,error:b}}let A=Object.freeze({...h,status:f.status,...y===void 0?{}:{requestId:y}});if(await i$1.fetchOptions?.onResponse?.(A),!f.ok){let b=Mn(f,u,y);return b.code===i&&e.session.tokens.dropChallenge(),await i$1.fetchOptions?.onError?.(Ae(h,b,"api")),{data:null,error:b}}return await i$1.fetchOptions?.onSuccess?.(A),{data:g,error:null}}}}async function En(e,t,n,i){let o$1=Date.now()+Dn;for(let a=0;a<i;a+=1){let p=o$1-Date.now();if(p<=0)throw new o("timeout");try{let m=await oe(e,t,{init:n,timeoutMs:Math.max(1,Math.ceil(p))});if(m.response.status<500||a===i-1)return m}catch(m){if(a===i-1||!(m instanceof o)||m.kind!=="network")throw m}await Fn(50*2**a,n.signal,o$1);}throw new o("network")}function Nn(e,t){if(e!=="GET"||t?.authChallengeToken)return 1;let n=t?.retry;return typeof n!="number"||!Number.isFinite(n)?1:Math.min(Math.max(Math.trunc(n),0),3)+1}function Un(e,t,n){let i=new URL(`${e}${t.startsWith("/")?t:`/${t}`}`);for(let[o,a]of Object.entries(n??{}))a!==void 0&&i.searchParams.set(o,String(a));return i.toString()}function Mn(e,t,n){let i=G(t)?t:{},o=_n(i,e.headers);return {status:e.status,statusText:e.statusText,code:typeof i.code=="string"?i.code:void 0,...n===void 0?{}:{requestId:n},...typeof i.current_version=="number"?{currentVersion:i.current_version}:{},...o!==void 0?{retryAfterSeconds:o}:{},message:typeof i.message=="string"?i.message:typeof i.error=="string"?i.error:typeof i.detail=="string"?i.detail:e.statusText||"Request failed"}}function _n(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??Ge(t.get("retry-after"))??Ge(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function Ge(e){if(!e)return;let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)?n:void 0}function Je(e){let t=e instanceof o?e.kind:"network";return {status:0,...{aborted:{statusText:"ABORTED",code:"REQUEST_ABORTED",message:"The request was cancelled."},timeout:{statusText:"TIMEOUT",code:"REQUEST_TIMEOUT",message:"The request timed out."},response_too_large:{statusText:"INVALID_RESPONSE",code:"RESPONSE_TOO_LARGE",message:"The service response was too large."},invalid_response:{statusText:"INVALID_RESPONSE",code:"INVALID_RESPONSE",message:"The service returned an invalid response."},network:{statusText:"FETCH_ERROR",code:"FETCH_ERROR",message:"Network request failed."}}[t],...e instanceof o&&e.requestId?{requestId:e.requestId}:{}}}function Ae(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function Ln(e){return e instanceof o?e.kind:"network"}function Fn(e,t,n){return new Promise((i,o$1)=>{if(t?.aborted){o$1(new o("aborted"));return}let a=n-Date.now();if(a<=0){o$1(new o("timeout"));return}let p=Math.min(e,a),m=()=>{clearTimeout(d),o$1(new o("aborted"));},d=setTimeout(()=>{t?.removeEventListener("abort",m),Date.now()>=n?o$1(new o("timeout")):i();},p);t?.addEventListener("abort",m,{once:true}),t?.aborted&&m();})}function Oe(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>zn||i.nodes>xn)throw new Error("response traversal limit exceeded");if(typeof e=="string"&&/^(?:createdAt|updatedAt|expiresAt)$/.test(t)){let o=new Date(e);return Number.isNaN(o.getTime())?e:o}return Array.isArray(e)?e.map(o=>Oe(o,"",n+1,i)):G(e)?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,qn(o)?a:Oe(a,o,n+1,i)])):e}function qn(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function Hn(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>G(o)?ye(o):o);if(!G(t))return t;let i=e==="/change-password"||e==="/passkey/verify-authentication"||e==="/phone-otp/verify"||e==="/sign-up/email"||e.startsWith("/sign-in/")||e.startsWith("/two-factor/verify-")?ye(t):t;return e==="/sign-up/email"&&!("sessionCreated"in i)&&(i={...i,sessionCreated:typeof t.token=="string"&&t.token.length>0}),(e==="/get-session"||e==="/passkey/verify-authentication")&&G(i.session)&&(i={...i,session:ye(i.session)}),i}function ye(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function G(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function We(e){return {listConsentPreferences:t=>e.request("/privacy/consent-decisions",{fetchOptions:t,decode:Vn}),recordConsent:(t,n)=>e.request("/privacy/consent-decisions",{method:"POST",body:{...t,correlationId:t.correlationId??a()},fetchOptions:n,decode:Bn}),listRightsRequests:t=>e.request("/privacy/rights",{fetchOptions:t,decode:jn}),createRightsRequest:(t,n)=>e.request("/privacy/rights",{method:"POST",body:t,fetchOptions:n,decode:Gn})}}function Vn(e){let t=q$1(e);return Array.isArray(t.preferences)||y(),{preferences:t.preferences.map(Kn)}}function Kn(e){let t=q$1(e);return {purposeId:r(t.purposeId),purposeVersionId:r(t.purposeVersionId),code:r(t.code),state:Jn(t.state,["granted","refused","withdrawn"]),updatedAt:re(t.updatedAt),decidedAt:re(t.decidedAt)}}function Bn(e){let t=q$1(e);return t.recorded!==true&&y(),{recorded:true,decision:J(t.decision,["granted","refused","withdrawn"]),decidedAt:ae(t.decidedAt)}}function jn(e){let t=q$1(e);return Array.isArray(t.requests)||y(),{requests:t.requests.map(Xe)}}function Gn(e){return {request:Xe(q$1(e).request)}}function Xe(e){let t=q$1(e);return {id:r(t.id),rightType:J(t.rightType,["access","correction","portability","erasure","restriction","objection","consent_withdrawal"]),state:J(t.state,["received","identity_pending","in_progress","restricted","completed","denied","withdrawn"]),locale:J(t.locale,["en","ar"]),receivedAt:ae(t.receivedAt),acknowledgedAt:re(t.acknowledgedAt),fulfilmentDeadline:ae(t.fulfilmentDeadline),completedAt:re(t.completedAt)}}function re(e){return e===null?null:ae(e)}function ae(e){if(e instanceof Date)return t(e);typeof e!="string"&&y();let t$1=new Date(e);return Number.isNaN(t$1.getTime())&&y(),t$1}function J(e,t){return (typeof e!="string"||!t.includes(e))&&y(),e}function Jn(e,t){return e===null?null:J(e,t)}function $e({http:e,probe:t,tokens:n,channelName:i}){let o=new Set,a=null,p=null,m=null,d=null,h=null,r=null,s,f=O=>{g(O);};s={data:null,isPending:true,isRefetching:false,error:null,refetch:f};function y(O){s=O;for(let v of o)v();}async function u(O){return e.request("/get-session",{query:O?.query,decode:we})}function g(O){if(O?.query?.disableCookieCache===true)return b(O);if(d)return d;if(h)return h;let v=b(O).finally(()=>{h===v&&(h=null);});return h=v,v}function A(){if(d)return d;let O=b({query:{disableCookieCache:true}}).finally(()=>{d===O&&(d=null);});return d=O,O}async function b(O){m?.abort();let v=new AbortController;m=v,y({...s,isPending:s.data===null&&s.error===null,isRefetching:s.data!==null});let j=n.beginRead(),ee=await e.request("/get-session",{query:O?.query,fetchOptions:{signal:v.signal},decode:we});if(m===v&&(m=null,y({data:ee.data,error:ee.error,isPending:false,isRefetching:false,refetch:f}),ee.error===null)){if(ee.data===null){j.endIfDead();return}await C(j);}}async function C(O){if(n.needsProbe()){if(!O.carriedToken){O.recordCookieVerdict(true);return}return r||_e(O)}}function _e(O){let v=t.request("/get-session",{query:{disableCookieCache:true},decode:we}).then(j=>{r===v&&j.error===null&&O.recordCookieVerdict(j.data!==null);}).finally(()=>{r===v&&(r=null);});return r=v,v}function Le(){a?.postMessage({type:"session-changed"});}function Sn(){if(typeof window>"u"||p)return;let O=()=>{g();},v=()=>{document.visibilityState==="visible"&&g();};window.addEventListener("focus",O),document.addEventListener("visibilitychange",v),typeof BroadcastChannel<"u"&&(a=new BroadcastChannel(i),a.addEventListener("message",O)),p=()=>{window.removeEventListener("focus",O),document.removeEventListener("visibilitychange",v),a?.close(),a=null,p=null;};}function vn(O){return o.add(O),o.size===1&&(Sn(),g()),()=>{if(o.delete(O),o.size===0){let v=m;m=null,h=null,d=null,v?.abort(),p?.();}}}return n.measureWith(()=>{n.needsProbe()&&_e(n.beginRead());}),{store:{subscribe:vn,getSnapshot:()=>s,refresh:A},getSession:u,notifyMutation(){Le(),r&&r.catch(()=>{}).then(()=>{!n.needsProbe()&&n.hasToken()&&Le();}),o.size>0&&g({query:{disableCookieCache:true}});}}}function we(e){if(e===null)return null;let t=q$1(e);return (t.session===void 0||t.user===void 0)&&y(),{session:x(t.session),user:w(t.user)}}async function Ye(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:Ze})}async function Qe(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:Ze})}function Ze(e){let t=q$1(e),n=z(t.public_metadata),i=z(t.unsafe_metadata);if(!Number.isSafeInteger(t.metadata_version)||t.metadata_version<0)throw new TypeError("Invalid AuthOwl metadata response");return {publicMetadata:n,unsafeMetadata:i,metadataVersion:t.metadata_version}}function tt(e,t){let{post:n,mutation:i}=q(e,t);return {getMetadata:o=>Ye(e,o),updateUnsafeMetadata:(o,a)=>Qe(e,o,a),updateProfile:(o,a)=>i(n("/update-user",o,a,W)),changeEmail:(o,a)=>i(n("/change-email",o,a,W)),changePassword:(o,a)=>i(n("/change-password",o,a,Wn)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:Xn}),revokeSession:({sessionId:o},a)=>i(n("/revoke-session",{sessionId:o},a,W)),revokeOtherSessions:o=>i(n("/revoke-other-sessions",{},o,W)),listSocialAccounts:async o=>{let a=await e.request("/list-accounts",{fetchOptions:o,decode:$n});if(!a.data)return {data:null,error:a.error};let p=a.data.length>1;return {...a,data:a.data.filter(m=>m.providerId!=="credential").map(m=>({...m,canUnlink:p}))}},linkSocial:(o,a)=>n("/link-social",o,a,Yn),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,W)),delete:(o={},a)=>i(n("/delete-user",o,a,Qn))}}function W(e){let t=q$1(e);return {status:s(t.status)}}function Wn(e){let t=q$1(e);return {user:w(t.user)}}function Xn(e){return Array.isArray(e)||y(),e.map(t$1=>{let n=q$1(t$1);return {id:r(n.id),userId:r(n.userId),createdAt:t(n.createdAt),updatedAt:t(n.updatedAt),expiresAt:t(n.expiresAt),...et("ipAddress",v(n,"ipAddress")),...et("userAgent",v(n,"userAgent"))}})}function $n(e){return Array.isArray(e)||y(),e.map(t$1=>{let n=q$1(t$1);return {id:r(n.id),userId:r(n.userId),providerId:r(n.providerId),accountId:r(n.accountId),scopes:u(n.scopes),createdAt:t(n.createdAt),updatedAt:t(n.updatedAt)}})}function Yn(e){let t=q$1(e);return {url:r(t.url),redirect:s(t.redirect)}}function Qn(e){let t=q$1(e);return {success:s(t.success),message:r(t.message)}}function et(e,t){return t===void 0?{}:{[e]:t}}var Zn=new Set(["pending","accepted","rejected","canceled"]),ke=1e4;function nt(e){let t=q$1(e);return t.recipientHint!==null&&t.recipientHint!=="new_user"&&y(),{recipientHint:t.recipientHint}}function H(e,t$1,n){let i=q$1(e),o={id:k(i.id),name:k(i.name),slug:k(i.slug),createdAt:t(i.createdAt),...X("logo",v(i,"logo")),...X("metadata",i.metadata===void 0?void 0:A(i.metadata))};return E(o.id,t$1),E(o.slug,n),o}function it(e){return U(e,H)}function Re(e,t,n){return e===null?null:(t===null&&y(),H(e,t,n))}function ot(e,t,n){if(e===null)return null;let i=q$1(e),o=H(i,t,n);return {...o,members:U(i.members,a=>ht(a,o.id)),invitations:U(i.invitations,a=>M(a,void 0,o.id))}}function Ie(e,t,n=false){let i=U(e,o=>$(o));return n||Q(i.map(o=>o.organizationId),t),i}function rt(e,t){let n=U(e,i=>Se(i));return Q(n.map(i=>i.teamId),t),n}function Se(e,t$1,n){let i=q$1(e),o={id:k(i.id),teamId:k(i.teamId),userId:k(i.userId),createdAt:t(i.createdAt)};return E(o.teamId,t$1),E(o.userId,n),o}function at(e,t,n){return e===null?null:(t===null&&y(),$(e,t,n))}function st(e,t){let n=q$1(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&y(),{members:ei(n.members,t),total:n.total}}function M(e,t$1,n){let i=q$1(e),o=k(i.status);Zn.has(o)||y();let a={id:k(i.id),organizationId:k(i.organizationId),email:Y(i.email),role:k(i.role),status:o,inviterId:k(i.inviterId),expiresAt:t(i.expiresAt),createdAt:t(i.createdAt)};return E(a.id,t$1),E(a.organizationId,n),a}function ut(e,t){let n=U(e,i=>M(i));return Q(n.map(i=>i.organizationId),t),n}function ct(e){return U(e,t=>{let n=q$1(t);return {...M(n),organizationName:Y(n.organizationName)}})}function dt(e,t){let n=q$1(e);return {...M(n,t),organizationName:k(n.organizationName),organizationSlug:k(n.organizationSlug),inviterEmail:At(n.inviterEmail)}}function lt(e,t){let n=q$1(e),i=M(n.invitation,t);return {invitation:i,member:V(n.member,void 0,i.organizationId)}}function pt(e,t){let n=q$1(e);return n.member!==null&&y(),{invitation:n.invitation===null?null:M(n.invitation,t),member:null}}function gt(e,t){return e===null?null:M(e,t)}function ft(e,t,n){let i=q$1(e);return {member:V(i.member,n,t)}}function V(e,t$1,n){let i=q$1(e),o={id:k(i.id),organizationId:k(i.organizationId),userId:k(i.userId),role:k(i.role),createdAt:t(i.createdAt),...i.user===void 0?{}:{user:yt(i.user)}};return E(o.id,t$1),E(o.organizationId,n),o}function mt(e,t){let n=U(e,i=>{let o=q$1(i);return {organizationId:k(o.organizationId),data:{role:k(o.role),...X("permission",o.permission===void 0?void 0:ti(o.permission)),...X("customPermissionKeys",o.customPermissionKeys===void 0?void 0:u(o.customPermissionKeys))}}});return Q(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function $(e,t$1,n){let i=q$1(e),o=i.updatedAt,a={id:k(i.id),name:Y(i.name),organizationId:k(i.organizationId),createdAt:t(i.createdAt),...o===void 0?{}:{updatedAt:t(o)}};return E(a.id,t$1),E(a.organizationId,n),a}function ve(e){let t=q$1(e);return {message:Y(t.message)}}function ht(e,t){let n=q$1(e);return {...V(n,void 0,t),user:yt(n.user)}}function ei(e,t){let n=U(e,i=>ht(i));return Q(n.map(i=>i.organizationId),t),n}function ti(e){let t=q$1(e),n={};for(let[i,o]of Object.entries(t))(i==="__proto__"||i==="constructor"||i==="prototype"||i.length===0||i.length>ke||!Array.isArray(o))&&y(),n[i]=o.map(a=>k(a));return n}function k(e){let t=r(e);return (t.length===0||t.length>ke)&&y(),t}function Y(e){if(e==null)return "";let t=r(e);return t.length>ke&&y(),t}function At(e){return e===null?null:k(e)}function E(e,t){t!==void 0&&e!==t&&y();}function Q(e,t){let n=t??e[0];n!==void 0&&e.some(i=>i!==n)&&y();}function yt(e){let t=q$1(e);return {id:k(t.id),name:Y(t.name),email:At(t.email),...X("image",v(t,"image"))}}function U(e,t){return Array.isArray(e)||y(),e.map(n=>t(n))}function X(e,t){return t===void 0?{}:{[e]:t}}function Ot(e,t,n=()=>null){let{post:i,mutation:o}=q(e,t),a=new Set,p=()=>{for(let r of a)try{r();}catch{}},m=new Map,d=(r,s,f,y)=>{if(f)return e.request(r,{query:s,fetchOptions:f,decode:y});let u=`${r}\0${JSON.stringify(s??null)}`,g=m.get(u);if(g)return g;let A=e.request(r,{query:s,decode:y}).finally(()=>{m.delete(u);});return m.set(u,A),A},h=async r=>{let s=await o(r).finally(()=>m.clear());return s.error===null&&p(),s};return {subscribe(r){return a.add(r),()=>a.delete(r)},create:(r,s)=>h(i("/organization/create",r,s,H)),list:r=>d("/organization/list",void 0,r,it),get:(r={},s)=>d("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},s,f=>ot(f,r.organizationId,r.organizationSlug)),setActive:(r,s)=>h(i("/organization/set-active",r,s,f=>Re(f,r.organizationId,r.organizationSlug))),createTeam:(r,s)=>h(i("/organization/create-team",r,s,f=>$(f,void 0,r.organizationId))),listTeams:(r={},s)=>d("/organization/list-teams",{organizationId:r.organizationId},s,f=>Ie(f,r.organizationId)),updateTeam:(r,s)=>h(i("/organization/update-team",r,s,f=>$(f,r.teamId,r.data.organizationId))),removeTeam:(r,s)=>h(i("/organization/remove-team",r,s,ve)),listUserTeams:r=>d("/organization/list-user-teams",void 0,r,s=>Ie(s,void 0,true)),listTeamMembers:(r={},s)=>d("/organization/list-team-members",{teamId:r.teamId},s,f=>rt(f,r.teamId)),addTeamMember:(r,s)=>h(i("/organization/add-team-member",r,s,f=>Se(f,r.teamId,r.userId))),removeTeamMember:(r,s)=>h(i("/organization/remove-team-member",r,s,ve)),setActiveTeam:(r,s)=>h(i("/organization/set-active-team",r,s,f=>at(f,r.teamId))),update:(r,s)=>h(i("/organization/update",r,s,f=>Re(f,r.organizationId))),delete:(r,s)=>h(i("/organization/delete",r,s,f=>H(f,r.organizationId))),listMembers:(r={},s)=>d("/organization/list-members",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,limit:r.limit,offset:r.offset,sortBy:r.sortBy,sortDirection:r.sortDirection,filterField:r.filterField,filterValue:r.filterValue,filterOperator:r.filterOperator},s,f=>st(f,r.organizationId)),inviteMember:(r,s)=>h(i("/organization/invite-member",r,s,f=>M(f,void 0,r.organizationId))),listInvitations:(r={},s)=>d("/organization/list-invitations",{organizationId:r.organizationId},s,f=>ut(f,r.organizationId)),listUserInvitations:r=>d("/organization/list-user-invitations",void 0,r,ct),getInvitation:(r,s)=>d("/organization/get-invitation",{id:r.id},s,f=>dt(f,r.id)),getInvitationRecipientHint:(r,s)=>d("/organization/invitation-recipient-hint",{invitationId:r.invitationId},s,nt),acceptInvitation:(r,s)=>h(i("/organization/accept-invitation",r,s,f=>lt(f,r.invitationId))),rejectInvitation:(r,s)=>h(i("/organization/reject-invitation",r,s,f=>pt(f,r.invitationId))),cancelInvitation:(r,s)=>h(i("/organization/cancel-invitation",r,s,f=>gt(f,r.invitationId))),removeMember:(r,s)=>h(i("/organization/remove-member",r,s,f=>ft(f,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,s)=>h(i("/organization/update-member-role",r,s,f=>V(f,r.memberId,r.organizationId))),leave:(r,s)=>h(i("/organization/leave",r,s,f=>V(f,void 0,r.organizationId))),listRoles:(r={},s)=>d("/organization/list-roles",{organizationId:r.organizationId},s,f=>mt(f,r.organizationId)),has:r=>E$1(n(),r),hasPermission:r=>B$1(n(),r.permission)}}var bt=4096,ni=4096,ii=100,oi=256,ri=16,ai=64,si=12;function Te(e){let t=q$1(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&y(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:Lt(t.twoFactorMethods,ri,ai)}}):(t.twoFactorRedirect!==void 0&&y(),{redirect:s(t.redirect),...pi(t,"url"),user:w(t.user)})}function wt(e){let t=q$1(e);return {user:w(t.user)}}function kt(e){let t=q$1(e);return {sessionCreated:s(t.sessionCreated),user:w(t.user)}}function Rt(e,t){let n=q$1(e),i=s(n.redirect);n.user===null&&y();let o=n.user!==void 0&&n.user!==null,a=n.url!==void 0&&n.url!==null;return i?((o||!a)&&y(),{redirect:true,url:Pe(n.url,t)}):(o===a&&y(),o?{redirect:false,user:w(n.user)}:{redirect:false,url:Pe(n.url,t)})}function It(e,t){let n=q$1(e);return (n.redirect!==true||n.user!==void 0)&&y(),{redirect:true,url:Pe(n.url,t)}}function St(e){return {status:s(q$1(e).status)}}function vt(e){return {success:s(q$1(e).success)}}function Pt(e){return q$1(e).status!=="pending"&&y(),{status:"pending"}}function Tt(e){let t=q$1(e);if(t.kind==="authowl_turnstile")return {kind:"authowl_turnstile"};t.kind!=="akedly_shield_v1_2"&&y();let n=q$1(t.turnstile),i=n.siteKey===null?null:r(n.siteKey);return {kind:"akedly_shield_v1_2",connectionId:r(t.connectionId),challenge:r(t.challenge),difficulty:ui(t.difficulty),challengeToken:r(t.challengeToken),challengeRequired:s(t.challengeRequired),turnstile:{required:s(n.required),siteKey:i}}}function ui(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>si)&&y(),Number(e)}function Ct(e){let t=q$1(e);return (t.status!==true||t.sessionCreated!==true)&&y(),{status:true,sessionCreated:true,user:ci(t.user)}}function Ce(e){return {status:s(q$1(e).status)}}function Dt(e){return {status:s(q$1(e).status)}}function zt(e){let t=q$1(e);return {status:s(t.status),user:w(t.user)}}function xt(e){return {success:s(q$1(e).success)}}function Et(e){let t=q$1(e);return {totpURI:li(t.totpURI),backupCodes:_t(t.backupCodes)}}function Nt(e){return {status:s(q$1(e).status)}}function se(e){return q$1(e).status!==true&&y(),{status:true}}function Ut(e){return {status:s(q$1(e).status)}}function Mt(e){let t=q$1(e);return t.status!==void 0&&t.status!==true&&y(),{backupCodes:_t(t.backupCodes)}}function ci(e){let t$1=q$1(e);return {id:K(t$1.id,512),...gi(t$1,"name",1024),phoneNumber:K(t$1.phoneNumber,64),phoneNumberVerified:s(t$1.phoneNumberVerified),...t$1.createdAt===void 0?{}:{createdAt:t(t$1.createdAt)},...t$1.updatedAt===void 0?{}:{updatedAt:t(t$1.updatedAt)}}}function Pe(e,t){let n=K(e,bt);/[\u0000-\u0020\u007f]/u.test(n)&&y();let i;try{i=new URL(n);}catch{return y()}return (i.username||i.password)&&y(),i.protocol==="https:"||t&&i.protocol==="http:"&&di(i.hostname)?i.href:y()}function di(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function li(e){let t=K(e,ni),n;try{n=new URL(t);}catch{return y()}let i=n.searchParams.get("secret");return (n.protocol!=="otpauth:"||n.hostname.toLowerCase()!=="totp"||n.username||n.password||n.hash||i===null||i.length===0||i.length>512||/\s/u.test(i))&&y(),t}function _t(e){return Lt(e,ii,oi)}function Lt(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&y();let i=e.map(o=>K(o,n));return i.some(o=>o.trim().length===0)&&y(),new Set(i).size!==i.length&&y(),i}function K(e,t){let n=r(e);return (n.length===0||n.length>t)&&y(),n}function pi(e,t){let n=e[t];return n==null?{}:{[t]:K(n,bt)}}function gi(e,t,n){let i=v(e,t);return i===void 0?{}:(i!==null&&i.length>n&&y(),{[t]:i})}var Ft=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),ue=new Set([9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279]);function ce(e){if(e===void 0)return {valid:true,value:void 0};for(let n of e){let i=n.codePointAt(0);if(i===void 0||Ht(n,i)||qt(i)||Ft.has(i))return {valid:false}}let t=fi(e);return De(t)?{valid:true,value:t}:{valid:false}}function De(e){let t=0,n,i;for(let o of e){if(t+=1,t>256)return false;let a=o.codePointAt(0);if(a===void 0||Ht(o,a)||qt(a)||Ft.has(a))return false;n??=a,i=a;}return t>0&&n!==void 0&&i!==void 0&&!ue.has(n)&&!ue.has(i)}function de(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_PASSKEY_NAME",message:"Passkey names must contain 1 to 256 safe Unicode characters."}}}function fi(e){let t=0,n=e.length;for(;t<n;){let i=e.codePointAt(t);if(i===void 0||!ue.has(i))break;t+=i>65535?2:1;}for(;n>t;){let i=e.codePointAt(n-1);if(i===void 0)break;let a=i>=56320&&i<=57343?n-2:n-1,p=e.codePointAt(a);if(p===void 0||!ue.has(p))break;n=a;}return e.slice(t,n)}function qt(e){return e>=0&&e<=31||e>=127&&e<=159}function Ht(e,t){return e.length===1&&t>=55296&&t<=57343}var Bt=12,jt=5e3,mi=8,hi=1e3,Ai=16,Vt=512,Gt=100,Jt=8192,yi=32768,ze=1024,Kt=256,Ee=64,Oi=6e5,bi=/^[A-Za-z0-9_-]+$/u,wi=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,ki=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,Ri=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,Ii=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,Wt=new Set(["discouraged","preferred","required"]),Si=new Set(["singleDevice","multiDevice"]),Xt=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),$t=new Set(["hybrid","security-key","client-device"]),vi=new Set(["none","indirect","direct","enterprise"]),Pi=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),Ti=new Set(["platform","cross-platform"]),Ci=new Set(["discouraged","preferred","required"]),Di=new Set([-8,-7,-257]);function Yt(e){let t=z(e,Bt,jt);return {challenge:un(t.challenge),...P("timeout",an(t.timeout)),...P("rpId",cn(t.rpId)),...P("allowCredentials",rn(t.allowCredentials)),...P("userVerification",Z(t.userVerification,Wt)),...P("hints",le(t.hints,$t)),...P("extensions",sn(t.extensions))}}function Qt(e){let t=z(e,Bt,jt);return {challenge:un(t.challenge),rp:zi(t.rp),user:xi(t.user),pubKeyCredParams:Ei(t.pubKeyCredParams),...P("timeout",an(t.timeout)),...P("excludeCredentials",rn(t.excludeCredentials)),...P("authenticatorSelection",Ni(t.authenticatorSelection)),...P("attestation",Z(t.attestation,vi)),...P("attestationFormats",le(t.attestationFormats,Pi)),...P("hints",le(t.hints,$t)),...P("extensions",sn(t.extensions))}}function Zt(e){let t=q$1(e),n=x(t.session),i=w(t.user);return n.userId!==i.id&&y(),{session:n,user:i}}function Ne(e){let t$1=q$1(e),n=t$1.counter;(!Number.isSafeInteger(n)||n<0)&&y();let i=Ue(t$1.deviceType,Si),o=s(t$1.backedUp);return o&&i!=="multiDevice"&&y(),{id:B(t$1.id,Kt),..._i(t$1),publicKey:Ui(t$1.publicKey,yi),userId:B(t$1.userId,Kt),credentialID:ge(t$1.credentialID,Jt),counter:n,deviceType:i,backedUp:o,...Li(t$1),createdAt:t(t$1.createdAt),...Fi(t$1)}}function en(e,t,n){let i=Ne(e);return (i.credentialID!==t||(n===void 0?i.name!==void 0&&i.name!==null:i.name!==n))&&y(),i}function tn(e){(!Array.isArray(e)||e.length>Gt)&&y();let t=e.map(Ne);return pe(t.map(n=>n.id)),pe(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&y(),t}function nn(e,t,n){let i=q$1(e),o=Ne(i.passkey);return (o.id!==t||o.name!==n)&&y(),{passkey:o}}function on(e){return q$1(e).status!==true&&y(),{status:true}}function zi(e){let t=q$1(e);return {name:xe(t.name,ze),...P("id",cn(t.id))}}function xi(e){let t=q$1(e);return {id:ge(t.id,128,1,64),name:xe(t.name,ze),displayName:xe(t.displayName,ze)}}function Ei(e){(!Array.isArray(e)||e.length===0||e.length>Ee)&&y();let t=e.map(n=>{let i=q$1(n);return (i.type!=="public-key"||!Number.isSafeInteger(i.alg)||!Di.has(i.alg))&&y(),{type:"public-key",alg:i.alg}});return qi(t.map(n=>n.alg)),t}function rn(e){if(e===void 0)return;(!Array.isArray(e)||e.length>Gt)&&y();let t=e.map(n=>{let i=q$1(n);return i.type!=="public-key"&&y(),{type:"public-key",id:ge(i.id,Jt),...P("transports",le(i.transports,Xt))}});return pe(t.map(n=>n.id)),t}function Ni(e){if(e===void 0)return;let t=q$1(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&y();let n=Z(t.residentKey,Ci);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&y(),{...P("authenticatorAttachment",Z(t.authenticatorAttachment,Ti)),...P("residentKey",n),...P("requireResidentKey",t.requireResidentKey),...P("userVerification",Z(t.userVerification,Wt))}}function an(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>Oi)&&y(),e}function sn(e){return e===void 0?void 0:z(e,mi,hi)}function le(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>Ee)&&y();let n=e.map(i=>Ue(i,t));return pe(n),n}function Z(e,t){if(e!==void 0)return Ue(e,t)}function un(e){return ge(e,Math.ceil(Vt*4/3),Ai,Vt)}function ge(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=B(e,t),a=o.length%4,p=Mi(o.at(-1)??""),m=Math.floor(o.length*3/4);return (!bi.test(o)||a===1||a===2&&(p&15)!==0||a===3&&(p&3)!==0||m<n||m>i)&&y(),o}function B(e,t){let n=r(e);return (n.length===0||n.length>t)&&y(),n}function xe(e,t){let n=B(e,t);return ki.test(n)&&y(),n}function cn(e){if(e===void 0)return;let t=B(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!Ri.test(n)))&&y(),t}function Ui(e,t){let n=B(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",p=dn(a);return (n.length%4!==0||!wi.test(n)||i&&(p&15)!==0||o&&(p&3)!==0)&&y(),n}function Mi(e){return dn(e,true)}function dn(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function _i(e){let t=v(e,"name");return t===void 0?{}:(t!==null&&!De(t)&&y(),{name:t})}function Li(e){let t=v(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>Ee||n.some(i=>!Xt.has(i))||new Set(n).size!==n.length)&&y(),{transports:t}}function Fi(e){let t=v(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(Ii.test(t)||y(),{aaguid:t})}function Ue(e,t){let n=r(e);return t.has(n)||y(),n}function P(e,t){return t===void 0?{}:{[e]:t}}function pe(e){new Set(e).size!==e.length&&y();}function qi(e){new Set(e).size!==e.length&&y();}function Hi(e,t){if(!t)return e;let n=t.catch(()=>{});return n.then(()=>{n=null;}),{async request(i,o){return n&&await n,e.request(i,o)}}}var ln=new Map;function Vi(e,t,n){let i=ln.get(n);if(!i){let o=new URLSearchParams(window.location.hash.slice(1)).get("authowl_code");if(!o)return;i=import('./session-handoff-ICVIFI3C.js').then(a=>a.completeCrossSiteSignIn(e,t,o)),ln.set(n,i);}return i}function pn(e){return !a$1()||e.idToken||e.disableRedirect?"legacy":"first-party"}function Ki(e,t=()=>{},n=Gi){let i=be(e),o=e.session.tokens,a$2=a$1()?Vi(i,e.session,e.decoded.projectId):void 0,p=Hi(i,a$2),m=$e({http:p,probe:be({...e,fetch:e.session.probe}),tokens:o,channelName:`authowl:${e.decoded.projectId}`}),d=n(p,m.notifyMutation),h=()=>{m.notifyMutation(),t();},{post:r,mutation:s}=q(p,h),f=e.decoded.env==="test",y=u=>e.session.prepareSession({remember:u?.rememberMe!==false});return {sessionStore:m.store,getSession:m.getSession,account:tt(p,h),organization:Ot(p,h,()=>m.store.getSnapshot().data?.session.membership??null),privacy:We(p),signIn:{email:async(u,g)=>(await y(u),s(r("/sign-in/email",u,g,Te),A=>!("twoFactorRedirect"in A))),username:async(u,g)=>(await y(u),s(r("/sign-in/username",u,g,Te),A=>!("twoFactorRedirect"in A))),social:async(u,g)=>{if(await y(),pn(u)==="first-party"){let{beginCrossSiteSignIn:b}=await import('./session-handoff-ICVIFI3C.js'),C=await b(e,{kind:"social",provider:u.provider,callbackURL:u.callbackURL,errorCallbackURL:u.errorCallbackURL,newUserCallbackURL:u.newUserCallbackURL,scopes:u.scopes,loginHint:u.loginHint,requestSignUp:u.requestSignUp});if(C)return window.location.assign(C),{data:{redirect:true,url:C},error:null}}let A=await s(r("/sign-in/social",u,g,b=>Rt(b,f)),b=>"user"in b);return A.error!==null||A.data===null||"url"in A.data&&A.data.redirect&&!u.disableRedirect&&typeof window<"u"&&window.location.assign(A.data.url),A},sso:async(u,g)=>{if(pn(u)==="first-party"){let{beginCrossSiteSignIn:b}=await import('./session-handoff-ICVIFI3C.js'),C=await b(e,{kind:"sso",email:u.email,providerId:u.providerId,domain:u.domain,organizationSlug:u.organizationSlug,callbackURL:u.callbackURL,errorCallbackURL:u.errorCallbackURL,newUserCallbackURL:u.newUserCallbackURL});if(C)return window.location.assign(C),{data:{url:C,redirect:true},error:null}}let A=await r("/sign-in/sso",u,g,b=>It(b,f));return A.error!==null||A.data===null||typeof window<"u"&&window.location.assign(A.data.url),A},magicLink:(u,g)=>r("/sign-in/magic-link",u,g,St),emailOtp:async(u,g)=>(await y(),s(r("/sign-in/email-otp",u,g,wt))),passkey:async(u,g)=>(await y(),d.signIn(u,g))},signUp:{email:async(u,g)=>(await y(),s(r("/sign-up/email",u,g,kt),A=>A.sessionCreated))},emailOtp:{sendVerificationOtp:(u,g)=>r("/email-otp/send-verification-otp",u,g,vt),verifyEmail:async(u,g)=>(await y(),s(r("/email-otp/verify-email",u,g,zt)))},phoneOtp:{prepare:u=>r("/phone-otp/challenge",{},u,Tt),start:(u,g)=>r("/phone-otp/start",{...u,idempotencyKey:u.idempotencyKey??a()},g,Pt),verify:async(u,g)=>(await y(),s(r("/phone-otp/verify",u,g,Ct)))},requestPasswordReset:(u,g)=>r("/request-password-reset",u,g,Ce),resetPassword:(u,g)=>r("/reset-password",u,g,Ce),sendVerificationEmail:(u,g)=>r("/send-verification-email",u,g,Dt),passkey:{addPasskey:(u,g)=>d.add(u,g),listUserPasskeys:()=>p.request("/passkey/list-user-passkeys",{decode:tn}),updatePasskey:async(u,g)=>{let A=ce(u.name);if(!A.valid||A.value===void 0)return de();let b=A.value;return r("/passkey/update-passkey",{...u,name:b},g,C=>nn(C,u.id,b))},deletePasskey:(u,g)=>r("/passkey/delete-passkey",u,g,on)},twoFactor:{enable:(u,g)=>r("/two-factor/enable",u,g,Et),disable:(u,g)=>s(r("/two-factor/disable",u,g,Nt),A=>A.status),verifyTotp:(u,g)=>s(r("/two-factor/verify-totp",u,g,se)),verifyBackupCode:(u,g)=>s(r("/two-factor/verify-backup-code",u,g,se)),sendOtp:(u={},g)=>r("/two-factor/send-otp",u,g,Ut),verifyOtp:(u,g)=>s(r("/two-factor/verify-otp",u,g,se)),generateBackupCodes:(u,g)=>r("/two-factor/generate-backup-codes",u,g,Mt)},signOut:u=>s(p.request("/sign-out",{method:"POST",body:{},fetchOptions:u,decode:xt}).then(g=>(o.endSession(),g)),g=>g.success)}}function Go(e,t=()=>{},n){let i=Ki(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:gn(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp,passkey:i.signIn.passkey},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey,addPasskey:i.passkey.addPasskey}}:{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:gn(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function gn(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return Bi();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?ji():i}}function Bi(){return Promise.resolve({data:null,error:{status:400,statusText:"BAD_REQUEST",code:"NATIVE_SOCIAL_ID_TOKEN_REQUIRED",message:"Native social sign-in requires a provider ID token."}})}function ji(){return Promise.resolve({data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_NATIVE_SOCIAL_RESPONSE",message:"The server returned a redirect for native ID-token sign-in."}})}function Gi(){return {signIn:()=>fn(),add:()=>fn()}}function fn(){return Promise.resolve({data:null,error:{status:400,statusText:"BAD_REQUEST",code:"PASSKEY_BROWSER_REQUIRED",message:"This passkey ceremony requires a browser with WebAuthn."}})}function $o(e,t,n){let i=new Map;return {async signIn(o={},a){let p=await e.request("/passkey/generate-authenticate-options");if(!p.data)return An(p.error);let m;try{m=Yt(p.data);}catch{return mn()}let d;try{d=await n.authenticate({optionsJSON:m,useBrowserAutofill:o.autoFill});}catch(y){return yn(n,y,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!Ji(d))return hn();let{clientExtensionResults:h,...r}=d,s=i.get(d.id);if(s)return s;let f=(async()=>{let y=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:r},fetchOptions:a,decode:Zt});return y.data&&t(),y})();i.set(d.id,f);try{return await f}finally{i.get(d.id)===f&&i.delete(d.id);}},async add(o={},a){let p=ce(o.name);if(!p.valid)return de();let m=await e.request("/passkey/generate-register-options",{query:{name:p.value,authenticatorAttachment:o.authenticatorAttachment}});if(!m.data)return An(m.error);let d;try{d=Qt(m.data);}catch{return mn()}let h;try{h=await n.register({optionsJSON:d});}catch(y){return yn(n,y,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!Wi(h))return hn();let{clientExtensionResults:r,...s}=h,f=await e.request("/passkey/verify-registration",{method:"POST",body:{response:s,name:p.value},fetchOptions:a,decode:y=>en(y,h.id,p.value)});return f.data&&t(),f}}}function mn(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function hn(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function bn(e){if(!e||typeof e!="object")return false;let t=e;return typeof t.id=="string"&&t.id.length>0&&typeof t.rawId=="string"&&t.rawId.length>0&&t.type==="public-key"&&!!t.response&&typeof t.response=="object"}function Ji(e){if(!bn(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.authenticatorData=="string"&&typeof t.signature=="string"&&(t.userHandle===void 0||typeof t.userHandle=="string")}function Wi(e){if(!bn(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function An(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function yn(e,t,n,i){let o=$i(t,"page does not have focus"),a=e.errorCode?.(t),p=a!==void 0?a==="ERROR_CEREMONY_ABORTED":On(t)==="AbortError",m=n!=="AUTH_CANCELLED",d=Xi(a,On(t),m);return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:o?"PASSKEY_PAGE_NOT_FOCUSED":p?n:a??"PASSKEY_BROWSER_ERROR",message:o?"Keep this page focused while completing the passkey prompt.":p?i:d}}}function Xi(e,t,n){switch(e){case "ERROR_INVALID_DOMAIN":case "ERROR_INVALID_RP_ID":return "Passkeys are not set up for this site\u2019s domain.";case "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED":return "This device already has a passkey for this account.";case "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEY_ALGS":case "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT":case "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT":return "This device cannot create a passkey for this site.";}return t==="NotAllowedError"?n?"No passkey was created. The prompt was dismissed or timed out.":"No passkey was used. This device may not have one saved for this site yet, or the prompt was dismissed.":t==="SecurityError"?"Passkeys are not set up for this site\u2019s domain.":n?"Passkey registration did not complete.":"Passkey sign-in did not complete."}function On(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function $i(e,t){let n=t.toLowerCase(),i=new Set,o=e;for(;o&&typeof o=="object"&&!i.has(o);){if(i.add(o),"message"in o&&typeof o.message=="string"&&o.message.toLowerCase().includes(n))return true;o="cause"in o?o.cause:void 0;}return false}async function er(e){let t=`${e.apiUrl}/api/projects/${e.decoded.projectId}/public-config`;return Be(await oe(e,t,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:n=>Yi(n,e)}),"public-config")}function Yi(e,t){let n=z(e),i=n.environmentId,o=n.environmentType,a=`${t.apiUrl}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Me(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==a)throw T();let p=S(n.branding),m=S(n.legal);if(!F(n.enabledMethods,64)||!F(n.socialProviders,64)||!In(p,["appName","logoUrl","primaryColor"])||p.showAppName!==void 0&&typeof p.showAppName!="boolean"||p.alignment!==void 0&&p.alignment!=="left"&&p.alignment!=="center"&&p.alignment!=="right"||p.theme!==void 0&&p.theme!=="light"&&p.theme!=="dark"&&p.theme!=="system"||!In(m,["termsUrl","privacyUrl"])||!Number.isSafeInteger(m.version)||m.version<0||typeof m.required!="boolean")throw T();if(n.socialProviderClientIds!==void 0){let d=S(n.socialProviderClientIds);if(Object.keys(d).length>64||Object.values(d).some(h=>typeof h!="string"||h.length>2048))throw T()}if(!_(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!wn(n.turnstileSiteKey)||!wn(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw T();if(n.jwtIssuer!==null){let d=S(n.jwtIssuer),h=new URL(d.issuer),r=`${h.origin}/api/projects/${t.decoded.projectId}/auth`;if(d.issuer!==r||d.jwksUrl!==`${r}/jwks`||d.aud!==t.decoded.projectId||h.protocol!=="https:"&&h.origin!==t.apiUrl)throw T()}if(n.signUp!==void 0){let d=S(n.signUp).mode;if(typeof d!="string"||!["open","restricted","allowlist","waitlist"].includes(d))throw T()}if(n.authentication!==void 0&&Qi(n.authentication),n.privacy!==void 0&&Zi(n.privacy),n.emailVerification!==void 0){let d=S(n.emailVerification);if(!_(d,["required"])||d.method!=="link"&&d.method!=="code")throw T()}if(n.userModel!==void 0&&!_(S(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw T();if(n.mfa!==void 0){let d=S(n.mfa);if(!_(d,["totp","required","backupCodes"])||d.emailOtpFallback!==void 0&&typeof d.emailOtpFallback!="boolean"||d.trustDevice!==void 0&&typeof d.trustDevice!="boolean"||(d.required===true||d.backupCodes===true)&&d.totp!==true)throw T()}if(n.captcha===void 0||n.captcha===null)n.captcha=typeof n.authTurnstileSiteKey=="string"&&n.authTurnstileSiteKey.length>0?{provider:"turnstile",siteKey:n.authTurnstileSiteKey}:null;else {let d=S(n.captcha);if(typeof d.provider!="string"||d.provider.length===0||d.provider.length>64||typeof d.siteKey!="string"||d.siteKey.length===0||d.siteKey.length>512)throw T();n.captcha={provider:d.provider,siteKey:d.siteKey};}return n}function Me(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function T(){return new TypeError("public-config returned an invalid response")}function S(e){if(!e||typeof e!="object"||Array.isArray(e))throw T();return e}function wn(e){return e===null||typeof e=="string"&&e.length<=4096}function Qi(e){let t=S(e),n=S(t.email),i=S(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!_(n,["signUp"])||!F(n.signIn,3)||n.signIn.some(a=>a!=="password"&&a!=="magic_link"&&a!=="email_otp")||!_(S(t.phone),["signUp","signIn"])||!_(i,["signUp","add"])||o&&(!Number.isSafeInteger(i.minLength)||!Number.isSafeInteger(i.maxLength)||i.minLength<1||i.maxLength>4096||i.minLength>i.maxLength)||!_(S(t.passkey),["signIn","add"])||!eo(S(t.passkey).relyingPartyId)||!_(S(t.username),["collectOnSignUp","signIn"]))throw T()}function Zi(e){let t=S(e);if(!Array.isArray(t.notices)||!Array.isArray(t.consentPurposes)||t.notices.length>64||t.consentPurposes.length>64)throw T();for(let n of t.notices){let i=S(n);if(kn(i,"noticeId","noticeVersionId"),fe(i.title,512),fe(i.body,1e5),Rn(i.digest),!F(i.activityCodes,128)||!F(i.purposeCodes,128)||typeof i.effectiveFrom!="string"||!Number.isFinite(Date.parse(i.effectiveFrom)))throw T()}for(let n of t.consentPurposes){let i=S(n);if(kn(i,"purposeId","purposeVersionId"),fe(i.title,512),fe(i.description,1e4),Rn(i.digest),!F(i.activityCodes,128)||!F(i.dataCategories,128))throw T()}}function kn(e,t,n){if(typeof e[t]!="string"||!Me(e[t])||typeof e[n]!="string"||!Me(e[n])||typeof e.code!="string"||!/^[a-z][a-z0-9_]{0,63}$/.test(e.code)||!Number.isSafeInteger(e.version)||e.version<1)throw T()}function fe(e,t){let n=S(e);if(typeof n.en!="string"||n.en.length===0||n.en.length>t||typeof n.ar!="string"||n.ar.length===0||n.ar.length>t)throw T()}function Rn(e){let t=S(e);if(typeof t.en!="string"||!/^[a-f0-9]{64}$/.test(t.en)||typeof t.ar!="string"||!/^[a-f0-9]{64}$/.test(t.ar))throw T()}function eo(e){return e==null||typeof e=="string"}function _(e,t){return t.every(n=>typeof e[n]=="boolean")}function In(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function F(e,t){return Array.isArray(e)&&e.length<=t&&e.every(n=>typeof n=="string"&&n.length<=128)&&new Set(e).size===e.length}export{to as a,he as b,oe as c,Be as d,ro as e,je as f,Tn as g,Cn as h,be as i,We as j,Ki as k,Go as l,$o as m,er as n};
@@ -1,2 +0,0 @@
1
- var we=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,Te=/^sk_/i;function Y(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(Te.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=we.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 nt(e,t){let n=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}function U(e,t){try{return e?.getItem(t)??null}catch{return null}}function P(e,t,n){try{n===null?e?.removeItem(t):e?.setItem(t,n);}catch{}}function H(){try{return globalThis.localStorage}catch{return}}function C(){try{return globalThis.sessionStorage}catch{return}}var Re="authowl.session-challenge",Se=e=>`${Re}.${e}`,ke="set-auth-challenge",D="x-authowl-challenge";function it(e){let t=e.get(D);return v(t)?X(t).some(([n,r])=>n.endsWith(".dont_remember")&&r.length>0):false}var at="INVALID_TWO_FACTOR_COOKIE",Ee=2048,v=e=>e!==null&&e.length<=Ee,Q=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function X(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 Z(e){let t=Se(e),n=new Map;function r(){return n.size===0?null:[...n].map(([a,u])=>`${a}=${u}`).join("; ")}function o(){let a=r();P(C(),t,v(a)?a:null);}function l(a){for(let[u,h]of X(a))Q.test(u)&&(h===""?n.delete(u):Q.test(h)&&n.set(u,h));}let d=U(C(),t);return v(d)&&l(d),{presentOn(a){let u=r();a.delete(D),v(u)&&a.set(D,u);},observe(a){let u=a.get(ke);v(u)&&(l(u),o());},clear(){n.clear(),o();}}}var ee="set-auth-token",te="x-authowl-session-transport",ne="bearer";var F=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function T(e,t){throw new Error(`${e}: ${t}`)}function Oe(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function re(e,{label:t,allowHttpLoopback:n}){(typeof e!="string"||e.length===0)&&T(t,"required"),e!==e.trim()&&T(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&T(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&T(t,"path must be unencoded");let r;try{r=new URL(e);}catch{T(t,"absolute URL required");}return (r.username||r.password)&&T(t,"credentials forbidden"),r.protocol!=="https:"&&r.protocol!=="http:"&&T(t,"HTTPS required"),r.protocol==="http:"&&(!n||!F.test(e))&&T(t,"HTTPS required except exact loopback"),r}function se(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&&F.test(r)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function oe(e,t,n){let r=Oe(e);(r.includes("//")||r.split("/").some(o=>o==="."||o==="..")||r!==""&&r!==t.pathname)&&T(n,"path traversal or duplicate separator");}function ie(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&T("apiUrl","origin required");let n;try{n=new URL(e);}catch{T("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!F.test(e))&&T("apiUrl","HTTPS required except exact loopback"),n.origin}function ct(e,t,n={allowHttpLoopback:false}){let r=re(e,{label:"issuer",allowHttpLoopback:n.allowHttpLoopback}),o=re(t,{label:"jwksUri",allowHttpLoopback:n.allowHttpLoopback});return oe(e,r,"issuer"),oe(t,o,"jwksUri"),r.pathname!=="/"&&r.pathname.endsWith("/")&&T("issuer","trailing slash forbidden"),{issuer:r.toString().replace(/\/$/,""),jwksUri:o.toString()}}var xe="authowl.session-token",Ae="authowl.session-binding",_e="authowl.cookie-transport",le="ok",ue="bearer",Le=e=>`${xe}.${e}`,Ue=e=>`${Ae}.${e}`,Pe=e=>`${_e}.${e}`;function Ce(e){return e===le?"cookies":e===ue?"bearer":"unknown"}function He(e){return e==="cookies"?le:e==="bearer"?ue:null}function Ke(e){let t=Le(e),n=Ue(e),r=Pe(e),o=Z(e),l=null,d=null,a=null,u=false,h=null,b=Ce(U(H(),r)),O=()=>b==="unknown",i=0,p=null,c=false;function L(){let s=U(C(),t);if(s!==null)return u=true,s;let g=U(H(),t);return g!==null?(u=false,g):null}function f(){return U(C(),n)??U(H(),n)}l=L(),d=l===null?null:f(),l!==null&&O()&&(c=true);function R(){if(!(!c||!p)){c=false;try{p();}catch{}}}function w(){let s=b==="bearer"?l:null,g=s===null?null:d,[K,G]=u?[C(),H()]:[H(),C()];P(G,t,null),P(G,n,null),P(K,t,s),P(K,n,g);}function x(s){s!==null&&h!==null&&(u=h,h=null),s!==null&&a!==null?(d=a,a=null):s===null&&(d=null),l=s,w(),s!==null&&O()&&(c=true,R());}function S(s){b=s,P(H(),r,He(s));}function A(){S("unknown"),c=false;}function k(){return l===null&&(l=L(),d=l===null?null:f()),l}function N(){let s=L();return s!==null&&(l=s,d=f()),l}function ye(s){N()===s&&w();}function M(){i+=1,h=null,a=null,u=false,x(null),o.clear(),A();}let W=()=>b!=="cookies";return {hasToken:()=>k()!==null,bindingThumbprint:()=>(k(),d),declareOn(s){if(s.has("authorization"))return false;let g=k();return !g&&!W()?false:(g&&s.set("authorization",`Bearer ${g}`),s.set(te,ne),o.presentOn(s),true)},wantsToken:W,needsProbe:O,observe(s){let g=s.get(ee);g&&x(g),o.observe(s);},dropChallenge:o.clear,measureWith(s){p=s,R();},beginRead(){let s=k(),g=i;return {carriedToken:s!==null,endIfDead(){s!==null&&N()===s&&i===g&&M();},recordCookieVerdict(K){if(i===g&&O()){if(S(K?"cookies":"bearer"),K){x(null);return}ye(s);}}}},beginSession({remember:s}){i+=1,h=!s,o.clear(),A();},useCookieTransport(){k()===null&&(a=null,S("cookies"));},completeCookieTransport(){S("cookies"),x(null);},useBoundBearerTransport(s,g){if(!s)throw new Error("A session proof thumbprint is required.");a=s,g||(h=true),S("bearer");},endSession:M}}var ae=new Map;function ce(e){let t=ae.get(e);if(t)return t;let n=Ke(e);return ae.set(e,n),n}var V="x-authowl-session-proof",de="x-authowl-session-binding",pe="x-authowl-session-binding-proof",I=()=>import('./session-proof-client-JPZY63IN.js');function ve(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function fe(e,t){let n=ce(e.projectId),r=(i,p)=>(t??globalThis.fetch)(i,p),o=typeof globalThis.location=="object"&&typeof globalThis.location.origin=="string"&&globalThis.location.origin!=="null"?globalThis.location.origin:null,l=null,d=false,a=()=>new Headers({"x-publishable-key":e.publishableKey});async function u(i){let p=i.get("authorization");p&&await I().then(c=>c.abandonSession(r,`${e.projectBaseURL}/session/abandon`,a(),p));}async function h(i){l=null,d=false;let p=await I().then(c=>c.prepareSenderConstrainedSession({tokens:n,start:i,clientOrigin:o,fetcher:r,projectBaseURL:e.projectBaseURL,headers:a()}));l=p.binding,d=p.cookieOnly;}return {fetch:async(i,p)=>{if(p?.credentials==="omit"||!n.wantsToken())return r(i,p);let c=ve(i,p),L=n.declareOn(c),f=c.get("authorization"),R=(p?.method??(typeof i=="object"&&i!==null&&"method"in i?i.method:"GET")).toUpperCase(),w=typeof i=="string"?i:i instanceof URL?i.toString():i.url;if(L&&o){let S=!!f;if(f){let A=f.replace(/^Bearer\s+/i,""),k=n.bindingThumbprint();if(k)try{c.set(V,await I().then(N=>N.createStoredSessionProof({origin:o,expectedThumbprint:k,method:R,url:w,token:A})));}catch{await u(c),n.endSession(),c.delete("authorization"),c.delete(V),c.delete(de),c.delete(pe),S=false;}}if(l){let A=l;c.set(de,A.nonce),c.set(S?pe:V,await I().then(k=>k.createSessionProof({key:A.key,method:R,url:w,token:A.nonce})));}}let x=await r(i,{...p,headers:c});return L&&(x.status===401&&f&&(new URL(w).pathname.endsWith("/get-session")||new URL(w).pathname.endsWith("/sign-out"))?(await u(c),n.endSession(),l=null,d=false):(n.observe(x.headers),x.headers.has("set-auth-token")&&(d&&n.completeCookieTransport(),l=null,d=false))),x},probe:r,tokens:n,prepareSession:h}}function Ne(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=Y(e.publishableKey),n=ie(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:n,decoded:t,projectBaseURL:`${n}/api/projects/${t.projectId}/auth`}}function Rt(e){let t=Ne(e),{fetch:n,...r}=fe({projectId:t.decoded.projectId,projectBaseURL:t.projectBaseURL,publishableKey:t.publishableKey},e.fetch);return {...e,...t,fetch:n,session:r}}var Ie=1e4,Be=1024*1024,B=class extends Error{kind;requestId;constructor(t,n){super(Je(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},ge=new WeakSet;function m(e,t){let n=new B(e,t);return ge.add(n),n}async function Et({fetchImpl:e,url:t,init:n={},timeoutMs:r=Ie,maxResponseBytes:o=Be,allowHttpLoopback:l=false,decode:d}){be(r,"timeoutMs"),be(o,"maxResponseBytes");let a=se(t,{allowHttpLoopback:l}),u=n.signal,h=new AbortController,b=null,O,i=new Promise(f=>{O=f;}),p=f=>{b===null&&(b=f,O({type:"abort",kind:f}),h.abort());},c=()=>p("aborted");u?.addEventListener("abort",c,{once:true});let L=setTimeout(()=>p("timeout"),r);u?.aborted&&c();try{if(b!==null)throw m(b);let f;try{f=await Promise.race([e(a.toString(),{...n,redirect:"error",signal:h.signal}).then(k=>({type:"response",response:k})),i]);}catch{throw m(b??"network")}if(f.type==="abort")throw m(f.kind);if(!je(f.response))throw m("invalid_response");let R=f.response,w=qe(R.headers),x=await De(R,o,i,()=>b,w),S=ze(R,x,w),A;try{A=R.ok&&d?d(S,Object.freeze({status:R.status})):S;}catch{throw m("invalid_response",w)}return {response:R,data:A,...w===void 0?{}:{requestId:w}}}catch(f){throw f instanceof B&&ge.has(f)?f:m(b??"network")}finally{clearTimeout(L),u?.removeEventListener("abort",c);}}function je(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 De(e,t,n,r,o){let l=e.headers.get("content-length");if(l!==null){if(!/^\d+$/.test(l))throw he(e.body),m("invalid_response",o);if(Number(l)>t)throw he(e.body),m("response_too_large",o)}if(!e.body)return "";let d;try{d=e.body.getReader();}catch{throw m("network",o)}let a=[],u=0,h=null;try{for(;;){let i;try{i=await Promise.race([d.read(),n]);}catch{h=m(r()??"network",o);break}if(Fe(i)){h=m(i.kind,o);break}let{done:p,value:c}=i;if(p)break;if(c.byteLength!==0){if(u+=c.byteLength,u>t){h=m("response_too_large",o);break}a.push(c);}}}finally{h&&Ve(d);try{d.releaseLock();}catch{}}if(h)throw h;let b=new Uint8Array(u),O=0;for(let i of a)b.set(i,O),O+=i.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(b)}catch{throw m("invalid_response",o)}}function Fe(e){return "type"in e&&e.type==="abort"}function he(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function Ve(e){try{e.cancel().catch(()=>{});}catch{}}function ze(e,t,n){if(e.status===204||e.status===205)return null;let r=$e(e.headers.get("content-type"));if(!e.ok&&(!r||t.length===0))return null;if(!r||t.length===0)throw m("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw m("invalid_response",n)}}function $e(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function qe(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function be(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Je(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 Me(e,t){return !e||!t?false:e.permissions.includes(t)}function We(e,t){return !e||!t?false:e.teams?.includes(t)??false}function Ge(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function Ye(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&&!Ge(e,n)||r!==void 0&&!e.permissions.includes(r)||o!==void 0&&!We(e,o))}function xt(e){return {has:t=>Ye(e,t),hasPermission:t=>Me(e,t.permission)}}var Qe=new Set(["__proto__","constructor","prototype"]);function J(e){(!e||typeof e!="object"||Array.isArray(e))&&y();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&y(),e}function j(e){return typeof e!="string"&&y(),e}function Xe(e){return typeof e!="boolean"&&y(),e}function $(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&y(),e}function z(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&y(),[...e]}function _(e,t){let n=e[t];return n==null||typeof n=="string"?n:y()}function me(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:y()}function _t(e){let t=J(e),n=t.email;return n!==null&&typeof n!="string"&&y(),{id:j(t.id),email:n,emailVerified:Xe(t.emailVerified),createdAt:$(t.createdAt),updatedAt:$(t.updatedAt),...E("phoneNumber",_(t,"phoneNumber")),...E("username",_(t,"username")),...E("displayUsername",_(t,"displayUsername")),...E("firstName",_(t,"firstName")),...E("lastName",_(t,"lastName")),...E("name",_(t,"name")),...E("image",_(t,"image")),...E("twoFactorEnabled",me(t,"twoFactorEnabled"))}}function Lt(e){let t=J(e),n=t.membership;return {id:j(t.id),userId:j(t.userId),expiresAt:$(t.expiresAt),...E("activeOrganizationId",_(t,"activeOrganizationId")),...E("activeTeamId",_(t,"activeTeamId")),...E("membership",n==null?n:et(n)),...E("pendingMfaEnrollment",me(t,"pendingMfaEnrollment"))}}function y(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function Ut(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&y(),Ze(e,t,n)}function Ze(e,t=20,n=1e4){return q(e,0,{nodes:0},t,n)}function et(e){let t=J(e);return {role:j(t.role),...t.roles===void 0?{}:{roles:z(t.roles)},permissions:z(t.permissions),...t.teams===void 0?{}:{teams:z(t.teams)}}}function q(e,t,n,r,o){if(n.nodes+=1,(t>r||n.nodes>o)&&y(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||y(),e;if(Array.isArray(e))return e.map(a=>q(a,t+1,n,r,o));(!e||typeof e!="object")&&y();let l=Object.getPrototypeOf(e);l!==Object.prototype&&l!==null&&y();let d={};for(let[a,u]of Object.entries(e))Qe.has(a)&&y(),d[a]=q(u,t+1,n,r,o);return d}function E(e,t){return t===void 0?{}:{[e]:t}}
2
- export{Ze as A,Me as B,We as C,Ge as D,Ye as E,xt as F,Y as a,nt as b,se as c,ct as d,U as e,P as f,H as g,it as h,at as i,ee as j,te as k,ne as l,Ne as m,Rt as n,B as o,Et as p,J as q,j as r,Xe as s,$ as t,z as u,_ as v,_t as w,Lt as x,y,Ut as z};