@authowl/core 0.15.1 → 0.15.3

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,v as v$1,t,h,g as g$1,f,r}from'./chunk-RRP2XNYV.js';export{f as resolveConfig,b as sessionCookieName}from'./chunk-RRP2XNYV.js';var i=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Q=300*1e3,ee=5e3,te=64*1024,re=64,ne=60*1e3,D=new Map,W=new Map;function L(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 q(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(L(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 B(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function J(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&L(e).byteLength===32}function se(e){if(!B(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)||!J(e.x)||!J(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 oe(e){if(!B(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>re)throw new i("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(se),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 V(e,t){let r$1=D.get(e);if(!t&&r$1&&Date.now()-r$1.fetchedAt<Q)return r$1.keys;try{let n=await h({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:ee,maxResponseBytes:te,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>r(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=oe(n.data);return D.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof g$1)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 ie(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await V(e,false));if(!n){let s=W.get(e)??0;Date.now()-s>=ne&&(W.set(e,Date.now()),n=r(await V(e,true)));}if(!n)throw new i("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function ae(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 pe(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function de(e){let t=e.membership;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,n=typeof r.role=="string"?r.role:"",s=Array.isArray(r.permissions)?r.permissions.filter(a=>typeof a=="string"):[],o=Array.isArray(r.teams)?r.teams.filter(a=>typeof a=="string"):void 0;return n===""&&s.length===0&&!o?.length?null:{role:n,permissions:s,...o===void 0?{}:{teams:o}}}async function ce(e,t){return w(e,k(t))}function k(e,t=false){if(!e||typeof e!="object")throw new i("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=d(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new i("Token verifier issuer or JWKS URL is invalid.","TOKEN_CONFIG_INVALID")}if(typeof e.audience!="string"||e.audience.length===0||e.audience.length>256)throw new i("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new i("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function w(e,t){if(typeof e!="string"||e.length===0)throw new i("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new i("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,a=q(n);if(a.alg!=="ES256")throw new i("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await ie(t.jwksUri,typeof a.kid=="string"?a.kid:void 0),c;try{c=await ae(p);}catch(b){throw b instanceof i?b:new i("JWKS key could not be imported.","JWKS_KEY_INVALID")}let m;try{if(!/^[A-Za-z0-9_-]{86}$/.test(o))throw new Error("invalid signature encoding");if(m=L(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new i("Malformed JWT signature.","TOKEN_MALFORMED")}let f=new TextEncoder().encode(`${n}.${s}`),y;try{y=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},c,m,f);}catch{throw new i("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!y)throw new i("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let d=q(s),h=t.clockToleranceSeconds??60,S=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+h<S)throw new i("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof d.nbf=="number"&&d.nbf-h>S)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(!pe(d.aud,t.audience))throw new i("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof d.sub=="string"?d.sub:null,membership:de(d),claims:d}}var me="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",A={getOpenApiDocument:{method:"GET",path:"/openapi.json",successStatuses:[200],responseSchemas:{200:{type:"object"}}},listUsers:{method:"GET",path:"/users",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserPage"}}},createUser:{method:"POST",path:"/users",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/User"}}},startUserExport:{method:"POST",path:"/users/export",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getUserExport:{method:"GET",path:"/users/export/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadUserExport:{method:"GET",path:"/users/export/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},startPasswordHashUserExport:{method:"POST",path:"/users/export/hashes",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},dryRunUserImport:{method:"POST",path:"/imports/dry-run",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportDryRun"}}},createUserImport:{method:"POST",path:"/imports",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportBatch"}}},getUserImport:{method:"GET",path:"/imports/{importId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ImportBatch"}}},downloadUserImportReport:{method:"GET",path:"/imports/{importId}/report",successStatuses:[200],responseSchemas:{200:null}},getUser:{method:"GET",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},updateUser:{method:"PATCH",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},deleteUser:{method:"DELETE",path:"/users/{userId}",successStatuses:[204],responseSchemas:{204:null}},listUserSessions:{method:"GET",path:"/users/{userId}/sessions",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionPage"}}},revokeUserSessions:{method:"DELETE",path:"/users/{userId}/sessions",successStatuses:[204],responseSchemas:{204:null}},updateUserMetadata:{method:"PATCH",path:"/users/{userId}/metadata",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserMetadata"}}},verifySession:{method:"POST",path:"/sessions/verify",successStatuses:[200],responseSchemas:{200:{type:"object",required:["user","session"],properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}},getSession:{method:"GET",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Session"}}},updateSessionMetadata:{method:"PATCH",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionMetadata"}}},revokeSession:{method:"DELETE",path:"/sessions/{sessionId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizations:{method:"GET",path:"/organizations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationPage"}}},createOrganization:{method:"POST",path:"/organizations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Organization"}}},getOrganization:{method:"GET",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},updateOrganization:{method:"PATCH",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},deleteOrganization:{method:"DELETE",path:"/organizations/{organizationId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationMembers:{method:"GET",path:"/organizations/{organizationId}/members",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MemberPage"}}},addOrganizationMember:{method:"POST",path:"/organizations/{organizationId}/members",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationMember"}}},updateOrganizationMember:{method:"PATCH",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationMember"}}},removeOrganizationMember:{method:"DELETE",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationRoles:{method:"GET",path:"/organizations/{organizationId}/roles",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/RolePage"}}},createOrganizationRole:{method:"POST",path:"/organizations/{organizationId}/roles",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationRole"}}},updateOrganizationRole:{method:"PATCH",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationRole"}}},deleteOrganizationRole:{method:"DELETE",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[204],responseSchemas:{204:null}},listInvitations:{method:"GET",path:"/invitations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/InvitationPage"}}},createInvitation:{method:"POST",path:"/invitations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Invitation"}}},getInvitation:{method:"GET",path:"/invitations/{invitationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Invitation"}}},revokeInvitation:{method:"DELETE",path:"/invitations/{invitationId}",successStatuses:[204],responseSchemas:{204:null}},listMessages:{method:"GET",path:"/messages",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MessagePage"}}},sendMessage:{method:"POST",path:"/messages",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/Message"}}},getMessage:{method:"GET",path:"/messages/{messageId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Message"}}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},v={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 ue=new Set(["__proto__","constructor","prototype"]),le=64,fe=5e4;function H(e,t,r){let s=A[e].responseSchemas;Object.hasOwn(s,String(t))||P();let o=s[String(t)];if(o===null){r!==null&&P();return}let a={nodes:0};return l(r,g(o),0,a)||P(),r}function l(e,t,r,n){if(n.nodes+=1,r>le||n.nodes>fe)return false;if(typeof t.$ref=="string"){let o=we(t.$ref);if(o===null||!l(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>l(e,g(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>l(e,g(o),r+1,n)).length!==1||Array.isArray(t.enum)&&!t.enum.some(o=>Object.is(o,e))||t.const!==void 0&&!Object.is(t.const,e))return false;let s=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!s.some(o=>ye(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?he(e,t):typeof e=="number"?be(e,t):Array.isArray(e)?_e(e,t,r,n):E(e)?Se(e,t,r,n):typeof e=="boolean"}function ye(e,t){switch(t){case "null":return e===null;case "object":return E(e);case "array":return Array.isArray(e);case "string":return typeof e=="string";case "integer":return Number.isSafeInteger(e);case "number":return typeof e=="number"&&Number.isFinite(e);case "boolean":return typeof e=="boolean";default:return false}}function he(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!ge(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 ge(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 be(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function _e(e,t,r,n){if(typeof t.minItems=="number"&&e.length<t.minItems||typeof t.maxItems=="number"&&e.length>t.maxItems||t.uniqueItems===true&&new Set(e.map(o=>JSON.stringify(o))).size!==e.length)return false;if(t.items===void 0)return true;let s=g(t.items);return e.every(o=>l(o,s,r+1,n))}function Se(e,t,r,n){let s=Object.keys(e);if(s.some(a=>ue.has(a))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=E(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(a=>!l(a,g(t.propertyNames),r+1,n))||Array.isArray(t.required)&&t.required.some(a=>typeof a!="string"||!Object.hasOwn(e,a)))return false;for(let[a,p]of Object.entries(e)){let c=o[a];if(c!==void 0){if(!l(p,g(c),r+1,n))return false;continue}if(t.additionalProperties===false||E(t.additionalProperties)&&!l(p,t.additionalProperties,r+1,n))return false}return true}function we(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(v,r)?g(v[r]):null}function g(e){return E(e)||P(),e}function E(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function P(){throw new TypeError("Admin API response does not match its generated contract.")}var Ae=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Ee=1024*1024,Oe=1e4,O=class extends Error{status;code;requestId;problem;retryAfter;constructor(t){super(t.problem.detail),this.name="AuthOwlAdminApiError",this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.problem=t.problem,this.retryAfter=t.retryAfter;}},_=class extends Error{kind;requestId;constructor(t,r){super(t==="aborted"?"The AuthOwl Admin API request was aborted.":t==="timeout"?"The AuthOwl Admin API request timed out.":t==="response_too_large"?"The AuthOwl Admin API response exceeded the allowed size.":t==="invalid_response"?"The AuthOwl Admin API returned an invalid response.":"The AuthOwl Admin API request could not be completed."),this.name="AuthOwlAdminNetworkError",this.kind=t,this.requestId=r;}};function Te(e){Ie();let t=ke(e?.secretKey),r=Pe(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,c)=>{let m=c??{},f=A[p],y=new URL(xe(f.path,m).replace(/^\/+/,""),r);je(y,m);let d=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Le(d,m);let h$1="body"in m?JSON.stringify(m.body):void 0;h$1!==void 0&&d.set("content-type","application/json");let S;try{S=await h({fetchImpl:s,url:y,init:{method:f.method,headers:d,body:h$1,signal:c?.signal},timeoutMs:Oe,maxResponseBytes:Ee,allowHttpLoopback:r.protocol==="http:",decode:(u,Y)=>H(p,Y.status,u)});}catch(u){throw u instanceof O?u:u instanceof g$1?new _(u.kind,u.requestId):new _("network")}let{response:b,requestId:R,data:z}=S;if(!b.ok)throw ve(b,z,R);if(!f.successStatuses.some(u=>u===b.status))throw new _("invalid_response",R);return z},a=Object.assign(Object.create(null),{request:o});for(let p of Object.keys(A))a[p]=c=>o(p,c);return Object.freeze(a)}function Ie(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function ke(e){if(typeof e!="string"||!Ae.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function Pe(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 xe(e,t){let r="path"in t&&x(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(n,s)=>{let o=r[s];if(typeof o!="string"&&typeof o!="number")throw new TypeError(`Missing Admin API path parameter: ${s}.`);return encodeURIComponent(String(o))})}function je(e,t){if(!(!("query"in t)||!x(t.query)))for(let[r,n]of Object.entries(t.query)){if(n==null)continue;let s=Array.isArray(n)?n:[n];for(let o of s)e.searchParams.append(r,String(o));}}function Le(e,t){if(!(!("header"in t)||!x(t.header)))for(let[r,n]of Object.entries(t.header)){if(n==null)continue;if(r.toLowerCase()!=="idempotency-key")throw new TypeError(`Unsupported Admin API header parameter: ${r}.`);if(typeof n!="string"||n.length<1||n.length>255)throw new TypeError("Idempotency-Key must contain between 1 and 255 characters.");if(!/^[\x21-\x7e ]+$/.test(n))throw new TypeError("Idempotency-Key contains unsupported characters.");e.set("Idempotency-Key",n);}}function ve(e,t,r){let n=r??F(e.headers.get("x-request-id"),256),s=F(e.headers.get("retry-after"),128),o=Ne(e.status,n),a=Re(t)?t:o;return new O({status:e.status,code:a.code,requestId:n,problem:a,retryAfter:s})}function Ne(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 Re(e){return x(e)?typeof e.type=="string"&&typeof e.title=="string"&&typeof e.status=="number"&&typeof e.detail=="string"&&typeof e.instance=="string"&&typeof e.code=="string":false}function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function F(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var ze=/^v1=([a-f0-9]{64})$/i,Ke=/^whsec_[A-Za-z0-9_-]{1,256}$/,Ue=/^(0|[1-9]\d{0,10})$/;async function $e(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=Me(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=De(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!Ue.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let a=Ce(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 f of t){let y=await crypto.subtle.importKey("raw",new TextEncoder().encode(f),{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=new Uint8Array(await crypto.subtle.sign("HMAC",y,c));for(let h of a)m=qe(d,h)||m;}return m}function Me(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!Ke.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function Ce(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=ze.exec(n.trim());s&&r.push(We(s[1]));}return r}function De(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 We(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 qe(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 G=["publishableKey","apiUrl","issuer","jwksUri","audience"],Je=new Set([...G,"clockToleranceSeconds"]);function N(e){if(e!==void 0&&(!e||typeof e!="object"))throw new Error("AuthOwl token verification config must be an object.");if(e&&Object.keys(e).some(p=>!Je.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(G.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 k({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let s,o;if(r){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e.publishableKey,o=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o=process.env.AUTHOWL_API_URL;if(!s||!o)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let a=f({publishableKey:s,apiUrl:o});return k({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},a.decoded.env==="test")}async function at(e,t){return w(e,N(t))}async function pt(e,t,r){let n=N(r);try{let s=await w(e,n);return v$1(s.membership,t)}catch{return false}}async function dt(e,t$1,r){let n=N(r);try{let s=await w(e,n);return t(s.membership,t$1.permission)}catch{return false}}export{me as ADMIN_API_SPEC_SHA256,O as AuthOwlAdminApiError,_ as AuthOwlAdminNetworkError,i as TokenVerificationError,Te as createAdminClient,pt as has,dt as hasPermission,ce as verifyProjectToken,at as verifyToken,$e as verifyWebhook};
1
+ import {d,c,A as A$1,y,m,l as l$1,k as k$1,w as w$1}from'./chunk-6D4A36HU.js';export{i as SESSION_TRANSPORT_BEARER,h as SESSION_TRANSPORT_HEADER,j as resolveAuthTarget,k as resolveConfig,b as sessionCookieName}from'./chunk-6D4A36HU.js';var i=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},re=300*1e3,ne=5e3,se=64*1024,oe=64,ie=60*1e3,D=new Map,W=new Map;function v(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4===0?t:t+"=".repeat(4-t.length%4),n=typeof atob=="function"?atob(r):globalThis.Buffer.from(r,"base64").toString("binary"),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}function q(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(v(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof i?t:new i("Malformed JWT segment.","TOKEN_MALFORMED")}}function B(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function J(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&v(e).byteLength===32}function ae(e){if(!B(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)||!J(e.x)||!J(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 pe(e){if(!B(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>oe)throw new i("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(ae),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 V(e,t){let r=D.get(e);if(!t&&r&&Date.now()-r.fetchedAt<re)return r.keys;try{let n=await m({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:ne,maxResponseBytes:se,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>w$1(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=pe(n.data);return D.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof l$1)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 de(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await V(e,false));if(!n){let s=W.get(e)??0;Date.now()-s>=ie&&(W.set(e,Date.now()),n=r(await V(e,true)));}if(!n)throw new i("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function ce(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 me(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function ue(e){let t=e.membership;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,n=typeof r.role=="string"?r.role:"",s=Array.isArray(r.permissions)?r.permissions.filter(a=>typeof a=="string"):[],o=Array.isArray(r.teams)?r.teams.filter(a=>typeof a=="string"):void 0;return n===""&&s.length===0&&!o?.length?null:{role:n,permissions:s,...o===void 0?{}:{teams:o}}}async function le(e,t){return w(e,k(t))}function k(e,t=false){if(!e||typeof e!="object")throw new i("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=d(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new i("Token verifier issuer or JWKS URL is invalid.","TOKEN_CONFIG_INVALID")}if(typeof e.audience!="string"||e.audience.length===0||e.audience.length>256)throw new i("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new i("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function w(e,t){if(typeof e!="string"||e.length===0)throw new i("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new i("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,a=q(n);if(a.alg!=="ES256")throw new i("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await de(t.jwksUri,typeof a.kid=="string"?a.kid:void 0),c;try{c=await ce(p);}catch(b){throw b instanceof i?b:new i("JWKS key could not be imported.","JWKS_KEY_INVALID")}let m;try{if(!/^[A-Za-z0-9_-]{86}$/.test(o))throw new Error("invalid signature encoding");if(m=v(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new i("Malformed JWT signature.","TOKEN_MALFORMED")}let f=new TextEncoder().encode(`${n}.${s}`),y;try{y=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},c,m,f);}catch{throw new i("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!y)throw new i("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let d=q(s),h=t.clockToleranceSeconds??60,S=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+h<S)throw new i("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof d.nbf=="number"&&d.nbf-h>S)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(!me(d.aud,t.audience))throw new i("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof d.sub=="string"?d.sub:null,membership:ue(d),claims:d}}var fe="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",A={getOpenApiDocument:{method:"GET",path:"/openapi.json",successStatuses:[200],responseSchemas:{200:{type:"object"}}},listUsers:{method:"GET",path:"/users",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserPage"}}},createUser:{method:"POST",path:"/users",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/User"}}},startUserExport:{method:"POST",path:"/users/export",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getUserExport:{method:"GET",path:"/users/export/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadUserExport:{method:"GET",path:"/users/export/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},startPasswordHashUserExport:{method:"POST",path:"/users/export/hashes",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},dryRunUserImport:{method:"POST",path:"/imports/dry-run",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportDryRun"}}},createUserImport:{method:"POST",path:"/imports",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportBatch"}}},getUserImport:{method:"GET",path:"/imports/{importId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ImportBatch"}}},downloadUserImportReport:{method:"GET",path:"/imports/{importId}/report",successStatuses:[200],responseSchemas:{200:null}},getUser:{method:"GET",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},updateUser:{method:"PATCH",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},deleteUser:{method:"DELETE",path:"/users/{userId}",successStatuses:[204],responseSchemas:{204:null}},listUserSessions:{method:"GET",path:"/users/{userId}/sessions",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionPage"}}},revokeUserSessions:{method:"DELETE",path:"/users/{userId}/sessions",successStatuses:[204],responseSchemas:{204:null}},updateUserMetadata:{method:"PATCH",path:"/users/{userId}/metadata",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserMetadata"}}},verifySession:{method:"POST",path:"/sessions/verify",successStatuses:[200],responseSchemas:{200:{type:"object",required:["user","session"],properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}},getSession:{method:"GET",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Session"}}},updateSessionMetadata:{method:"PATCH",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionMetadata"}}},revokeSession:{method:"DELETE",path:"/sessions/{sessionId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizations:{method:"GET",path:"/organizations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationPage"}}},createOrganization:{method:"POST",path:"/organizations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Organization"}}},getOrganization:{method:"GET",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},updateOrganization:{method:"PATCH",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},deleteOrganization:{method:"DELETE",path:"/organizations/{organizationId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationMembers:{method:"GET",path:"/organizations/{organizationId}/members",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MemberPage"}}},addOrganizationMember:{method:"POST",path:"/organizations/{organizationId}/members",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationMember"}}},updateOrganizationMember:{method:"PATCH",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationMember"}}},removeOrganizationMember:{method:"DELETE",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationRoles:{method:"GET",path:"/organizations/{organizationId}/roles",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/RolePage"}}},createOrganizationRole:{method:"POST",path:"/organizations/{organizationId}/roles",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationRole"}}},updateOrganizationRole:{method:"PATCH",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationRole"}}},deleteOrganizationRole:{method:"DELETE",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[204],responseSchemas:{204:null}},listInvitations:{method:"GET",path:"/invitations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/InvitationPage"}}},createInvitation:{method:"POST",path:"/invitations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Invitation"}}},getInvitation:{method:"GET",path:"/invitations/{invitationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Invitation"}}},revokeInvitation:{method:"DELETE",path:"/invitations/{invitationId}",successStatuses:[204],responseSchemas:{204:null}},listMessages:{method:"GET",path:"/messages",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MessagePage"}}},sendMessage:{method:"POST",path:"/messages",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/Message"}}},getMessage:{method:"GET",path:"/messages/{messageId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Message"}}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},L={Problem:{type:"object",required:["type","title","status","detail","instance","code"],properties:{type:{type:"string",format:"uri"},title:{type:"string"},status:{type:"integer"},detail:{type:"string"},instance:{type:"string",format:"uri"},code:{type:"string"}},additionalProperties:true},User:{type:"object",required:["id","email","phone","name","image","email_verified","banned","public_metadata","private_metadata","unsafe_metadata","metadata_version","created_at","updated_at"],properties:{id:{type:"string"},email:{type:"string",format:"email"},phone:{type:["string","null"]},name:{type:["string","null"]},image:{type:["string","null"],format:"uri"},email_verified:{type:"boolean"},banned:{type:"boolean"},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateUser:{type:"object",required:["email"],properties:{email:{type:"string",format:"email",maxLength:320},password:{type:"string",minLength:8,maxLength:128},name:{type:"string",minLength:1,maxLength:200},phone:{type:"string",minLength:1,maxLength:32}},additionalProperties:false},UpdateUser:{type:"object",minProperties:1,properties:{email:{type:"string",format:"email",maxLength:320},name:{type:["string","null"],minLength:1,maxLength:200},phone:{type:["string","null"],minLength:1,maxLength:32},banned:{type:"boolean"}},additionalProperties:false},ImportDryRun:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","errors","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"dry_run"},status:{type:"string",const:"validated"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},errors:{type:"array",maxItems:100,items:{type:"object",required:["line","code","path","message"],properties:{line:{type:"integer",minimum:2},code:{type:"string",enum:["INVALID_JSON","UNEXPECTED_RECORD","INVALID_USER","DUPLICATE_EXTERNAL_ID"]},path:{type:["string","null"]},message:{type:"string"}},additionalProperties:false}},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},ImportBatch:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","report_expires_at","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"commit"},status:{type:"string",const:"completed"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid","created","updated","unchanged","failed"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4},created:{type:"integer",minimum:0,maximum:1e4},updated:{type:"integer",minimum:0,maximum:1e4},unchanged:{type:"integer",minimum:0,maximum:1e4},failed:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},report_expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},MetadataObject:{type:"object",maxProperties:100,description:"JSON metadata object. Reserved prototype keys and the authowl_ prefix are rejected at every depth. Encoded object size is limited to 8192 bytes.",additionalProperties:true},UserMetadata:{type:"object",required:["public_metadata","private_metadata","unsafe_metadata","metadata_version"],properties:{public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateUserMetadata:{type:"object",required:["expected_version"],minProperties:2,properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Session:{type:"object",required:["id","user_id","expires_at","created_at","metadata","metadata_version"],properties:{id:{type:"string"},user_id:{type:"string"},expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},ip_address:{type:["string","null"]},user_agent:{type:["string","null"]},metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},SessionMetadata:{type:"object",required:["metadata","metadata_version"],properties:{metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateSessionMetadata:{type:"object",required:["expected_version","metadata"],properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Organization:{type:"object",required:["id","name","slug","created_at"],properties:{id:{type:"string"},name:{type:"string"},slug:{type:"string"},logo:{type:["string","null"],format:"uri"},metadata:{type:["object","null"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateOrganization:{type:"object",required:["name","slug"],properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:"string",format:"uri",maxLength:2048},metadata:{type:"object"}},additionalProperties:false},UpdateOrganization:{type:"object",minProperties:1,properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:["string","null"],format:"uri",maxLength:2048},metadata:{type:["object","null"]}},additionalProperties:false},OrganizationMember:{type:"object",required:["organization_id","user_id","role","created_at"],properties:{organization_id:{type:"string"},user_id:{type:"string"},role:{type:"string"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},AddMember:{type:"object",required:["user_id","role"],properties:{user_id:{type:"string"},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},OrganizationRole:{type:"object",required:["id","organization_id","name","permissions"],properties:{id:{type:"string"},organization_id:{type:"string"},name:{type:"string"},permissions:{type:"array",items:{$ref:"#/components/schemas/OrganizationPermissionId"}}},additionalProperties:false},OrganizationPermissionId:{type:"string",enum:["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","team:create","team:update","team:delete","ac:create","ac:read","ac:update","ac:delete"]},RoleInput:{type:"object",required:["name","permissions"],properties:{name:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9_-]*$"},permissions:{type:"array",maxItems:100,items:{$ref:"#/components/schemas/OrganizationPermissionId"},uniqueItems:true}},additionalProperties:false},Invitation:{type:"object",required:["id","organization_id","email","role","status","expires_at"],properties:{id:{type:"string"},organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100},status:{type:"string"},expires_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateInvitation:{type:"object",required:["organization_id","email","role"],properties:{organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},Event:{type:"object",required:["id","type","status","created_at"],properties:{id:{type:"string"},type:{type:"string"},status:{type:"string"},user_id:{type:["string","null"]},metadata:{type:"object"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},StatsOverview:{type:"object",required:["users_total","monthly_active_users","recent_sign_ins"],properties:{users_total:{type:"integer",minimum:0},monthly_active_users:{type:"integer",minimum:0},recent_sign_ins:{type:"integer",minimum:0}},additionalProperties:false},WebhookInput:{type:"object",required:["url","events"],properties:{url:{type:"string",format:"uri",maxLength:2048},description:{type:"string",maxLength:500},events:{type:"array",minItems:1,maxItems:20,items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"},uniqueItems:true}},additionalProperties:false},SendMessage:{type:"object",required:["to","template","variables"],properties:{to:{type:"string",minLength:7,maxLength:32},channel:{type:"string",enum:["sms","whatsapp","auto"],description:"Defaults to auto."},purpose:{type:"string",enum:["transactional"],description:"Defaults to transactional."},template:{type:"string",pattern:"^[a-z][a-z0-9_]{0,63}$"},locale:{type:"string",enum:["en","ar"],description:"Defaults to en."},variables:{type:"object",maxProperties:50,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_]{0,63}$"},additionalProperties:{type:"string",maxLength:1024}},customerReference:{type:"string",minLength:1,maxLength:255}},additionalProperties:false},MessageState:{type:"string",enum:["preparing","queued","accepted","skipped","delivered","failed","unknown","canceled"]},Message:{type:"object",required:["id","state","purpose","requested_channel","actual_channel","customer_reference","masked_recipient","sms","billing","failure","created_at","updated_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},state:{$ref:"#/components/schemas/MessageState"},purpose:{type:"string",enum:["transactional","auth_otp"]},requested_channel:{type:"string",enum:["sms","whatsapp","auto"]},actual_channel:{type:["string","null"],enum:["sms","whatsapp",null]},customer_reference:{type:["string","null"]},masked_recipient:{type:"string"},sms:{oneOf:[{type:"null"},{type:"object",required:["encoding","segments"],properties:{encoding:{type:["string","null"],enum:["gsm7","ucs2",null]},segments:{type:["integer","null"],minimum:1}},additionalProperties:false}]},billing:{type:"object",required:["credential_mode","unit","units","charged_piasters","reserved_piasters"],properties:{credential_mode:{type:"string",enum:["managed","byok"]},unit:{type:["string","null"]},units:{type:["integer","null"]},charged_piasters:{type:"integer",minimum:0},reserved_piasters:{type:"integer",minimum:0}},additionalProperties:false},failure:{oneOf:[{type:"null"},{type:"object",required:["code","retryable"],properties:{code:{type:"string"},retryable:{type:"boolean"}},additionalProperties:false}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},WebhookSubscriptionEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed"]},WebhookEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed","webhook.test"]},WebhookEndpoint:{type:"object",required:["id","url","events","status","created_at","updated_at"],properties:{id:{type:"string",format:"uuid"},url:{type:"string",format:"uri"},description:{type:["string","null"]},events:{type:"array",items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"}},status:{type:"string",enum:["active","paused","auto_paused"]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookSecret:{type:"object",required:["secret","overlap_expires_at"],properties:{secret:{type:"string"},overlap_expires_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookWithSecret:{type:"object",required:["endpoint","secret"],properties:{endpoint:{$ref:"#/components/schemas/WebhookEndpoint"},secret:{type:"string"}},additionalProperties:false},WebhookDelivery:{type:"object",required:["id","event_id","attempt_id","attempt_number","webhook_id","event_type","status","response_status","response_body","error_code","created_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},event_id:{type:"string",format:"uuid"},attempt_id:{type:"string",format:"uuid"},attempt_number:{type:"integer",minimum:1},webhook_id:{type:"string",format:"uuid"},event_type:{$ref:"#/components/schemas/WebhookEventType"},status:{type:"string",enum:["queued","delivering","succeeded","failed"]},response_status:{type:["integer","null"]},response_body:{type:["string","null"]},error_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},ExportJob:{type:"object",required:["id","format","status","includes_password_hashes","total_rows","artifact_bytes","failure_code","created_at","completed_at","expires_at","download_url"],properties:{id:{type:"string",format:"uuid"},format:{type:"string",enum:["ndjson","csv"]},status:{type:"string",enum:["pending","processing","completed","failed"]},includes_password_hashes:{type:"boolean"},total_rows:{type:"integer",minimum:0},artifact_bytes:{type:"integer",minimum:0},failure_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},completed_at:{type:["string","null"],format:"date-time"},expires_at:{type:["string","null"],format:"date-time"},download_url:{type:["string","null"]}},additionalProperties:false},ExportRequest:{type:"object",properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"}},additionalProperties:false},HashExportRequest:{type:"object",required:["approval_token"],properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"},approval_token:{type:"string",minLength:1,maxLength:256}},additionalProperties:false},Page:{type:"object",required:["data","next_cursor"],properties:{data:{type:"array"},next_cursor:{type:["string","null"]}},additionalProperties:false},UserPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/User"}}}}]},SessionPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}]},OrganizationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}]},MemberPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationMember"}}}}]},RolePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationRole"}}}}]},InvitationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Invitation"}}}}]},EventPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Event"}}}}]},WebhookPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookEndpoint"}}}}]},DeliveryPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookDelivery"}}}}]},MessagePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Message"}}}}]}};var ye=new Set(["__proto__","constructor","prototype"]),he=64,ge=5e4;function H(e,t,r){let s=A[e].responseSchemas;Object.hasOwn(s,String(t))||P();let o=s[String(t)];if(o===null){r!==null&&P();return}let a={nodes:0};return l(r,g(o),0,a)||P(),r}function l(e,t,r,n){if(n.nodes+=1,r>he||n.nodes>ge)return false;if(typeof t.$ref=="string"){let o=Oe(t.$ref);if(o===null||!l(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>l(e,g(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>l(e,g(o),r+1,n)).length!==1||Array.isArray(t.enum)&&!t.enum.some(o=>Object.is(o,e))||t.const!==void 0&&!Object.is(t.const,e))return false;let s=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!s.some(o=>be(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?_e(e,t):typeof e=="number"?we(e,t):Array.isArray(e)?Ae(e,t,r,n):E(e)?Ee(e,t,r,n):typeof e=="boolean"}function be(e,t){switch(t){case "null":return e===null;case "object":return E(e);case "array":return Array.isArray(e);case "string":return typeof e=="string";case "integer":return Number.isSafeInteger(e);case "number":return typeof e=="number"&&Number.isFinite(e);case "boolean":return typeof e=="boolean";default:return false}}function _e(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!Se(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 Se(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 we(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function Ae(e,t,r,n){if(typeof t.minItems=="number"&&e.length<t.minItems||typeof t.maxItems=="number"&&e.length>t.maxItems||t.uniqueItems===true&&new Set(e.map(o=>JSON.stringify(o))).size!==e.length)return false;if(t.items===void 0)return true;let s=g(t.items);return e.every(o=>l(o,s,r+1,n))}function Ee(e,t,r,n){let s=Object.keys(e);if(s.some(a=>ye.has(a))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=E(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(a=>!l(a,g(t.propertyNames),r+1,n))||Array.isArray(t.required)&&t.required.some(a=>typeof a!="string"||!Object.hasOwn(e,a)))return false;for(let[a,p]of Object.entries(e)){let c=o[a];if(c!==void 0){if(!l(p,g(c),r+1,n))return false;continue}if(t.additionalProperties===false||E(t.additionalProperties)&&!l(p,t.additionalProperties,r+1,n))return false}return true}function Oe(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(L,r)?g(L[r]):null}function g(e){return E(e)||P(),e}function E(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function P(){throw new TypeError("Admin API response does not match its generated contract.")}var Te=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Ie=1024*1024,ke=1e4,O=class extends Error{status;code;requestId;problem;retryAfter;constructor(t){super(t.problem.detail),this.name="AuthOwlAdminApiError",this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.problem=t.problem,this.retryAfter=t.retryAfter;}},_=class extends Error{kind;requestId;constructor(t,r){super(t==="aborted"?"The AuthOwl Admin API request was aborted.":t==="timeout"?"The AuthOwl Admin API request timed out.":t==="response_too_large"?"The AuthOwl Admin API response exceeded the allowed size.":t==="invalid_response"?"The AuthOwl Admin API returned an invalid response.":"The AuthOwl Admin API request could not be completed."),this.name="AuthOwlAdminNetworkError",this.kind=t,this.requestId=r;}};function Pe(e){xe();let t=je(e?.secretKey),r=ve(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,c)=>{let m$1=c??{},f=A[p],y=new URL(Le(f.path,m$1).replace(/^\/+/,""),r);Ne(y,m$1);let d=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Re(d,m$1);let h="body"in m$1?JSON.stringify(m$1.body):void 0;h!==void 0&&d.set("content-type","application/json");let S;try{S=await m({fetchImpl:s,url:y,init:{method:f.method,headers:d,body:h,signal:c?.signal},timeoutMs:ke,maxResponseBytes:Ie,allowHttpLoopback:r.protocol==="http:",decode:(u,Y)=>H(p,Y.status,u)});}catch(u){throw u instanceof O?u:u instanceof l$1?new _(u.kind,u.requestId):new _("network")}let{response:b,requestId:R,data:z}=S;if(!b.ok)throw ze(b,z,R);if(!f.successStatuses.some(u=>u===b.status))throw new _("invalid_response",R);return z},a=Object.assign(Object.create(null),{request:o});for(let p of Object.keys(A))a[p]=c=>o(p,c);return Object.freeze(a)}function xe(){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"||!Te.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function ve(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 Le(e,t){let r="path"in t&&x(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(n,s)=>{let o=r[s];if(typeof o!="string"&&typeof o!="number")throw new TypeError(`Missing Admin API path parameter: ${s}.`);return encodeURIComponent(String(o))})}function Ne(e,t){if(!(!("query"in t)||!x(t.query)))for(let[r,n]of Object.entries(t.query)){if(n==null)continue;let s=Array.isArray(n)?n:[n];for(let o of s)e.searchParams.append(r,String(o));}}function Re(e,t){if(!(!("header"in t)||!x(t.header)))for(let[r,n]of Object.entries(t.header)){if(n==null)continue;if(r.toLowerCase()!=="idempotency-key")throw new TypeError(`Unsupported Admin API header parameter: ${r}.`);if(typeof n!="string"||n.length<1||n.length>255)throw new TypeError("Idempotency-Key must contain between 1 and 255 characters.");if(!/^[\x21-\x7e ]+$/.test(n))throw new TypeError("Idempotency-Key contains unsupported characters.");e.set("Idempotency-Key",n);}}function ze(e,t,r){let n=r??F(e.headers.get("x-request-id"),256),s=F(e.headers.get("retry-after"),128),o=Ke(e.status,n),a=Ue(t)?t:o;return new O({status:e.status,code:a.code,requestId:n,problem:a,retryAfter:s})}function Ke(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 Ue(e){return x(e)?typeof e.type=="string"&&typeof e.title=="string"&&typeof e.status=="number"&&typeof e.detail=="string"&&typeof e.instance=="string"&&typeof e.code=="string":false}function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function F(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var $e=/^v1=([a-f0-9]{64})$/i,Me=/^whsec_[A-Za-z0-9_-]{1,256}$/,Ce=/^(0|[1-9]\d{0,10})$/;async function De(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=We(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=Je(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!Ce.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let a=qe(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 f of t){let y=await crypto.subtle.importKey("raw",new TextEncoder().encode(f),{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=new Uint8Array(await crypto.subtle.sign("HMAC",y,c));for(let h of a)m=Be(d,h)||m;}return m}function We(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!Me.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function qe(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=$e.exec(n.trim());s&&r.push(Ve(s[1]));}return r}function Je(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 Ve(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 Be(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 G=["publishableKey","apiUrl","issuer","jwksUri","audience"],He=new Set([...G,"clockToleranceSeconds"]);function N(e){if(e!==void 0&&(!e||typeof e!="object"))throw new Error("AuthOwl token verification config must be an object.");if(e&&Object.keys(e).some(p=>!He.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(G.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 k({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let s,o;if(r){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e.publishableKey,o=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o=process.env.AUTHOWL_API_URL;if(!s||!o)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let a=k$1({publishableKey:s,apiUrl:o});return k({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},a.decoded.env==="test")}async function ct(e,t){return w(e,N(t))}async function mt(e,t,r){let n=N(r);try{let s=await w(e,n);return A$1(s.membership,t)}catch{return false}}async function ut(e,t,r){let n=N(r);try{let s=await w(e,n);return y(s.membership,t.permission)}catch{return false}}export{fe as ADMIN_API_SPEC_SHA256,O as AuthOwlAdminApiError,_ as AuthOwlAdminNetworkError,i as TokenVerificationError,Pe as createAdminClient,mt as has,ut as hasPermission,le as verifyProjectToken,ct as verifyToken,De as verifyWebhook};
@@ -0,0 +1,7 @@
1
+ /** Set by AuthOwl on a response that established a browser session. */
2
+ declare const SESSION_TOKEN_HEADER = "set-auth-token";
3
+ /** Paired declaration required before a bearer credential is treated as a session. */
4
+ declare const SESSION_TRANSPORT_HEADER = "x-authowl-session-transport";
5
+ declare const SESSION_TRANSPORT_BEARER = "bearer";
6
+
7
+ export { SESSION_TOKEN_HEADER as S, SESSION_TRANSPORT_BEARER as a, SESSION_TRANSPORT_HEADER as b };
@@ -0,0 +1,7 @@
1
+ /** Set by AuthOwl on a response that established a browser session. */
2
+ declare const SESSION_TOKEN_HEADER = "set-auth-token";
3
+ /** Paired declaration required before a bearer credential is treated as a session. */
4
+ declare const SESSION_TRANSPORT_HEADER = "x-authowl-session-transport";
5
+ declare const SESSION_TRANSPORT_BEARER = "bearer";
6
+
7
+ export { SESSION_TOKEN_HEADER as S, SESSION_TRANSPORT_BEARER as a, SESSION_TRANSPORT_HEADER as b };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authowl/core",
3
- "version": "0.15.1",
3
+ "version": "0.15.3",
4
4
  "description": "Framework-agnostic client for AuthOwl, the multi-tenant auth SaaS.",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -1,2 +0,0 @@
1
- var ie=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,ae=/^sk_/i;function B(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(ae.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=ie.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 qe(e,t){let n=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}var j=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function g(e,t){throw new Error(`${e}: ${t}`)}function ue(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function q(e,{label:t,allowHttpLoopback:n}){(typeof e!="string"||e.length===0)&&g(t,"required"),e!==e.trim()&&g(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&g(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&g(t,"path must be unencoded");let r;try{r=new URL(e);}catch{g(t,"absolute URL required");}return (r.username||r.password)&&g(t,"credentials forbidden"),r.protocol!=="https:"&&r.protocol!=="http:"&&g(t,"HTTPS required"),r.protocol==="http:"&&(!n||!j.test(e))&&g(t,"HTTPS required except exact loopback"),r}function $(e,t){let n;try{n=new URL(String(e));}catch{throw new TypeError("Transport URL must be absolute.")}if(n.username||n.password||n.hash)throw new TypeError("Transport URL must not contain credentials or a fragment.");let r=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&j.test(r)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function J(e,t,n){let r=ue(e);(r.includes("//")||r.split("/").some(o=>o==="."||o==="..")||r!==""&&r!==t.pathname)&&g(n,"path traversal or duplicate separator");}function z(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&g("apiUrl","origin required");let n;try{n=new URL(e);}catch{g("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!j.test(e))&&g("apiUrl","HTTPS required except exact loopback"),n.origin}function $e(e,t,n={allowHttpLoopback:false}){let r=q(e,{label:"issuer",allowHttpLoopback:n.allowHttpLoopback}),o=q(t,{label:"jwksUri",allowHttpLoopback:n.allowHttpLoopback});return J(e,r,"issuer"),J(t,o,"jwksUri"),r.pathname!=="/"&&r.pathname.endsWith("/")&&g("issuer","trailing slash forbidden"),{issuer:r.toString().replace(/\/$/,""),jwksUri:o.toString()}}function O(e,t){try{return e?.getItem(t)??null}catch{return null}}function A(e,t,n){try{n===null?e?.removeItem(t):e?.setItem(t,n);}catch{}}function _(){try{return globalThis.localStorage}catch{return}}function x(){try{return globalThis.sessionStorage}catch{return}}var ce="authowl.session-challenge",le=e=>`${ce}.${e}`,de="set-auth-challenge",M="x-authowl-challenge",Ge="INVALID_TWO_FACTOR_COOKIE",pe=2048,K=e=>e!==null&&e.length<=pe,W=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function fe(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 G(e){let t=le(e),n=new Map;function r(){return n.size===0?null:[...n].map(([s,a])=>`${s}=${a}`).join("; ")}function o(){let s=r();A(x(),t,K(s)?s:null);}function l(s){for(let[a,c]of fe(s))W.test(a)&&(c===""?n.delete(a):W.test(c)&&n.set(a,c));}let u=O(x(),t);return K(u)&&l(u),{presentOn(s){let a=r();s.delete(M),K(a)&&s.set(M,a);},observe(s){let a=s.get(de);K(a)&&(l(a),o());},clear(){n.clear(),o();}}}var he="authowl.session-token",me="authowl.cookie-transport",Q="ok",X="bearer",be=e=>`${he}.${e}`,ge=e=>`${me}.${e}`,ye="set-auth-token",we="x-authowl-session-transport",ke="bearer";function Te(e){return e===Q?"cookies":e===X?"bearer":"unknown"}function Re(e){return e==="cookies"?Q:e==="bearer"?X:null}function Se(e){let t=be(e),n=ge(e),r=G(e),o=null,l=false,u=null,s=Te(O(_(),n)),a=()=>s==="unknown",c=0,d=null,w=false;function m(){let i=O(x(),t);if(i!==null)return l=true,i;let b=O(_(),t);return b!==null?(l=false,b):null}o=m(),o!==null&&a()&&(w=true);function E(){if(!(!w||!d)){w=false;try{d();}catch{}}}function k(){let i=s==="bearer"?o:null,[b,v]=l?[x(),_()]:[_(),x()];A(v,t,null),A(b,t,i);}function L(i){i!==null&&u!==null&&(l=u,u=null),o=i,k(),i!==null&&a()&&(w=true,E());}function p(i){s=i,A(_(),n,Re(i));}function T(){p("unknown"),w=false;}function R(){return o===null&&(o=m()),o}function C(){let i=m();return i!==null&&(o=i),o}function H(i){C()===i&&k();}function U(){c+=1,u=null,l=false,L(null),r.clear(),T();}let P=()=>s!=="cookies";return {hasToken:()=>R()!==null,declareOn(i){if(i.has("authorization"))return false;let b=R();return !b&&!P()?false:(b&&i.set("authorization",`Bearer ${b}`),i.set(we,ke),r.presentOn(i),true)},wantsToken:P,needsProbe:a,observe(i){let b=i.get(ye);b&&L(b),r.observe(i);},dropChallenge:r.clear,measureWith(i){d=i,E();},beginRead(){let i=R(),b=c;return {carriedToken:i!==null,endIfDead(){i!==null&&C()===i&&c===b&&U();},recordCookieVerdict(v){if(c===b&&a()){if(p(v?"cookies":"bearer"),v){L(null);return}H(i);}}}},beginSession({remember:i}){c+=1,u=!i,r.clear(),T();},endSession:U}}var Y=new Map;function Z(e){let t=Y.get(e);if(t)return t;let n=Se(e);return Y.set(e,n),n}function Ee(e,t){return t?.headers?new Headers(t.headers):typeof e=="object"&&e!==null&&"headers"in e?new Headers(e.headers):new Headers}function ee(e,t){let n=Z(e),r=(u,s)=>(t??globalThis.fetch)(u,s);return {fetch:async(u,s)=>{if(s?.credentials==="omit"||!n.wantsToken())return r(u,s);let a=Ee(u,s),c=n.declareOn(a),d=await r(u,{...s,headers:a});return c&&n.observe(d.headers),d},probe:r,tokens:n}}function st(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=B(e.publishableKey),n=z(e.apiUrl,{allowHttpLoopback:t.env==="test"}),r=`${n}/api/projects/${t.projectId}/auth`,{fetch:o,...l}=ee(t.projectId,e.fetch);return {...e,apiUrl:n,decoded:t,projectBaseURL:r,fetch:o,session:l}}var xe=1e4,Oe=1024*1024,N=class extends Error{kind;requestId;constructor(t,n){super(ve(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},re=new WeakSet;function f(e,t){let n=new N(e,t);return re.add(n),n}async function ut({fetchImpl:e,url:t,init:n={},timeoutMs:r=xe,maxResponseBytes:o=Oe,allowHttpLoopback:l=false,decode:u}){ne(r,"timeoutMs"),ne(o,"maxResponseBytes");let s=$(t,{allowHttpLoopback:l}),a=n.signal,c=new AbortController,d=null,w,m=new Promise(p=>{w=p;}),E=p=>{d===null&&(d=p,w({type:"abort",kind:p}),c.abort());},k=()=>E("aborted");a?.addEventListener("abort",k,{once:true});let L=setTimeout(()=>E("timeout"),r);a?.aborted&&k();try{if(d!==null)throw f(d);let p;try{p=await Promise.race([e(s.toString(),{...n,redirect:"error",signal:c.signal}).then(P=>({type:"response",response:P})),m]);}catch{throw f(d??"network")}if(p.type==="abort")throw f(p.kind);if(!Ae(p.response))throw f("invalid_response");let T=p.response,R=Pe(T.headers),C=await _e(T,o,m,()=>d,R),H=Ce(T,C,R),U;try{U=T.ok&&u?u(H,Object.freeze({status:T.status})):H;}catch{throw f("invalid_response",R)}return {response:T,data:U,...R===void 0?{}:{requestId:R}}}catch(p){throw p instanceof N&&re.has(p)?p:f(d??"network")}finally{clearTimeout(L),a?.removeEventListener("abort",k);}}function Ae(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 _e(e,t,n,r,o){let l=e.headers.get("content-length");if(l!==null){if(!/^\d+$/.test(l))throw te(e.body),f("invalid_response",o);if(Number(l)>t)throw te(e.body),f("response_too_large",o)}if(!e.body)return "";let u;try{u=e.body.getReader();}catch{throw f("network",o)}let s=[],a=0,c=null;try{for(;;){let m;try{m=await Promise.race([u.read(),n]);}catch{c=f(r()??"network",o);break}if(Le(m)){c=f(m.kind,o);break}let{done:E,value:k}=m;if(E)break;if(k.byteLength!==0){if(a+=k.byteLength,a>t){c=f("response_too_large",o);break}s.push(k);}}}finally{c&&Ue(u);try{u.releaseLock();}catch{}}if(c)throw c;let d=new Uint8Array(a),w=0;for(let m of s)d.set(m,w),w+=m.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(d)}catch{throw f("invalid_response",o)}}function Le(e){return "type"in e&&e.type==="abort"}function te(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function Ue(e){try{e.cancel().catch(()=>{});}catch{}}function Ce(e,t,n){if(e.status===204||e.status===205)return null;let r=He(e.headers.get("content-type"));if(!e.ok&&(!r||t.length===0))return null;if(!r||t.length===0)throw f("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw f("invalid_response",n)}}function He(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function Pe(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function ne(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function ve(e){switch(e){case "aborted":return "The request was cancelled.";case "timeout":return "The request timed out.";case "response_too_large":return "The response exceeded the allowed size.";case "invalid_response":return "The service returned an invalid response.";case "network":return "The network request could not be completed."}}function Ke(e,t){return !e||!t?false:e.permissions.includes(t)}function Ne(e,t){return !e||!t?false:e.teams?.includes(t)??false}function Ie(e,t){if(!e)return false;let{role:n,permission:r,teamId:o}=t;return !(n===void 0&&r===void 0&&o===void 0||n!==void 0&&e.role!==n||r!==void 0&&!e.permissions.includes(r)||o!==void 0&&!Ne(e,o))}function lt(e){return {has:t=>Ie(e,t),hasPermission:t=>Ke(e,t.permission)}}var je=new Set(["__proto__","constructor","prototype"]);function F(e){(!e||typeof e!="object"||Array.isArray(e))&&h();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&h(),e}function I(e){return typeof e!="string"&&h(),e}function De(e){return typeof e!="boolean"&&h(),e}function D(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&h(),e}function oe(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&h(),[...e]}function S(e,t){let n=e[t];return n==null||typeof n=="string"?n:h()}function se(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:h()}function pt(e){let t=F(e),n=t.email;return n!==null&&typeof n!="string"&&h(),{id:I(t.id),email:n,emailVerified:De(t.emailVerified),createdAt:D(t.createdAt),updatedAt:D(t.updatedAt),...y("phoneNumber",S(t,"phoneNumber")),...y("username",S(t,"username")),...y("displayUsername",S(t,"displayUsername")),...y("firstName",S(t,"firstName")),...y("lastName",S(t,"lastName")),...y("name",S(t,"name")),...y("image",S(t,"image")),...y("twoFactorEnabled",se(t,"twoFactorEnabled"))}}function ft(e){let t=F(e),n=t.membership;return {id:I(t.id),userId:I(t.userId),expiresAt:D(t.expiresAt),...y("activeOrganizationId",S(t,"activeOrganizationId")),...y("activeTeamId",S(t,"activeTeamId")),...y("membership",n==null?n:Fe(n)),...y("pendingMfaEnrollment",se(t,"pendingMfaEnrollment"))}}function h(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function ht(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&h(),Ve(e,t,n)}function Ve(e,t=20,n=1e4){return V(e,0,{nodes:0},t,n)}function Fe(e){let t=F(e);return {role:I(t.role),permissions:oe(t.permissions),...t.teams===void 0?{}:{teams:oe(t.teams)}}}function V(e,t,n,r,o){if(n.nodes+=1,(t>r||n.nodes>o)&&h(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||h(),e;if(Array.isArray(e))return e.map(s=>V(s,t+1,n,r,o));(!e||typeof e!="object")&&h();let l=Object.getPrototypeOf(e);l!==Object.prototype&&l!==null&&h();let u={};for(let[s,a]of Object.entries(e))je.has(s)&&h(),u[s]=V(a,t+1,n,r,o);return u}function y(e,t){return t===void 0?{}:{[e]:t}}
2
- export{B as a,qe as b,$ as c,$e as d,Ge as e,st as f,N as g,ut as h,F as i,I as j,De as k,D as l,oe as m,S as n,pt as o,ft as p,h as q,ht as r,Ve as s,Ke as t,Ne as u,Ie as v,lt as w};
@@ -1 +0,0 @@
1
- import {h,g,e,r,k as k$1,i,q as q$1,j as j$1,o,t,v,p,l,s,n,m as m$1}from'./chunk-RRP2XNYV.js';import {a}from'./chunk-T5SH3ZZP.js';function Ti(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(r=>r==="password"||r==="magic_link"||r==="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 ae=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 X(e,t,n={}){let i=new Headers(n.init?.headers);return i.set("x-publishable-key",e.publishableKey),h({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 Ce(e,t){if(!e.response.ok)throw new ae(t,e.response,e.requestId);return e.data}var sn="x-authowl-turnstile-token",un=1e4,cn=32,dn=2e4;function L(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 de(e$1,t=e$1.projectBaseURL){return {async request(n,i={}){let o=gn(t,n,i.query),a=i.method??(i.body===void 0?"GET":"POST"),r=new Headers(i.fetchOptions?.headers);i.fetchOptions?.authChallengeToken&&r.set(sn,i.fetchOptions.authChallengeToken),i.body!==void 0&&r.set("content-type","application/json");let u={method:a,headers:r,credentials:i.credentials??"include",...i.body===void 0?{}:{body:JSON.stringify(i.body)}},c=Object.freeze({method:a,path:n});await i.fetchOptions?.onRequest?.(c);let h=pn(a,i.fetchOptions),g$1;try{g$1=await ln(e$1,o,{...u,signal:i.fetchOptions?.signal},h);}catch(f){let S=xe(f);return await i.fetchOptions?.onError?.(se(c,S,hn(f))),{data:null,error:S}}let{response:A,requestId:I}=g$1,O=On(n,g$1.data),s=O;if(A.ok)try{s=ce(O),i.decode&&(s=i.decode(s));}catch{let f=xe(new g("invalid_response",I));return await i.fetchOptions?.onError?.(se(c,f,"invalid_response")),{data:null,error:f}}let l=Object.freeze({...c,status:A.status,...I===void 0?{}:{requestId:I}});if(await i.fetchOptions?.onResponse?.(l),!A.ok){let f=fn(A,O,I);return f.code===e&&e$1.session.tokens.dropChallenge(),await i.fetchOptions?.onError?.(se(c,f,"api")),{data:null,error:f}}return await i.fetchOptions?.onSuccess?.(l),{data:s,error:null}}}}async function ln(e,t,n,i){let o=Date.now()+un;for(let a=0;a<i;a+=1){let r=o-Date.now();if(r<=0)throw new g("timeout");try{let u=await X(e,t,{init:n,timeoutMs:Math.max(1,Math.ceil(r))});if(u.response.status<500||a===i-1)return u}catch(u){if(a===i-1||!(u instanceof g)||u.kind!=="network")throw u}await An(50*2**a,n.signal,o);}throw new g("network")}function pn(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 gn(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 fn(e,t,n){let i=K(t)?t:{},o=mn(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 mn(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??De(t.get("retry-after"))??De(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function De(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 xe(e){let t=e instanceof g?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 g&&e.requestId?{requestId:e.requestId}:{}}}function se(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function hn(e){return e instanceof g?e.kind:"network"}function An(e,t,n){return new Promise((i,o)=>{if(t?.aborted){o(new g("aborted"));return}let a=n-Date.now();if(a<=0){o(new g("timeout"));return}let r=Math.min(e,a),u=()=>{clearTimeout(c),o(new g("aborted"));},c=setTimeout(()=>{t?.removeEventListener("abort",u),Date.now()>=n?o(new g("timeout")):i();},r);t?.addEventListener("abort",u,{once:true}),t?.aborted&&u();})}function ce(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>cn||i.nodes>dn)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=>ce(o,"",n+1,i)):K(e)?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,yn(o)?a:ce(a,o,n+1,i)])):e}function yn(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function On(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>K(o)?ue(o):o);if(!K(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-")?ue(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")&&K(i.session)&&(i={...i,session:ue(i.session)}),i}function ue(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function K(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function ze(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return `${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Ee({http:e,probe:t,tokens:n,channelName:i}){let o=new Set,a=null,r=null,u=null,c=null,h=null,g,A=y=>{s(y);};g={data:null,isPending:true,isRefetching:false,error:null,refetch:A};function I(y){g=y;for(let P of o)P();}async function O(y){return e.request("/get-session",{query:y?.query,decode:le})}function s(y){if(y?.query?.disableCookieCache===true)return l(y);if(c)return c;let P=l(y).finally(()=>{c===P&&(c=null);});return c=P,P}async function l(y){u?.abort();let P=new AbortController;u=P,I({...g,isPending:g.data===null&&g.error===null,isRefetching:g.data!==null});let B=n.beginRead(),G=await e.request("/get-session",{query:y?.query,fetchOptions:{signal:P.signal},decode:le});if(u===P&&(u=null,I({data:G.data,error:G.error,isPending:false,isRefetching:false,refetch:A}),G.error===null)){if(G.data===null){B.endIfDead();return}await f(B);}}async function f(y){if(n.needsProbe()){if(!y.carriedToken){y.recordCookieVerdict(true);return}return h||S(y)}}function S(y){let P=t.request("/get-session",{query:{disableCookieCache:true},decode:le}).then(B=>{h===P&&B.error===null&&y.recordCookieVerdict(B.data!==null);}).finally(()=>{h===P&&(h=null);});return h=P,P}function v(){a?.postMessage({type:"session-changed"});}function rn(){if(typeof window>"u"||r)return;let y=()=>{s();},P=()=>{document.visibilityState==="visible"&&s();};window.addEventListener("focus",y),document.addEventListener("visibilitychange",P),typeof BroadcastChannel<"u"&&(a=new BroadcastChannel(i),a.addEventListener("message",y)),r=()=>{window.removeEventListener("focus",y),document.removeEventListener("visibilitychange",P),a?.close(),a=null,r=null;};}function an(y){return o.add(y),o.size===1&&(rn(),s()),()=>{o.delete(y),o.size===0&&(u?.abort(),u=null,r?.());}}return n.measureWith(()=>{n.needsProbe()&&S(n.beginRead());}),{store:{subscribe:an,getSnapshot:()=>g},getSession:O,notifyMutation(){v(),h&&h.catch(()=>{}).then(()=>{!n.needsProbe()&&n.hasToken()&&v();}),o.size>0&&s({query:{disableCookieCache:true}});}}}function le(e){if(e===null)return null;let t=i(e);return (t.session===void 0||t.user===void 0)&&q$1(),{session:p(t.session),user:o(t.user)}}async function Ne(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:Me})}async function Ue(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:Me})}function Me(e){let t=i(e),n=r(t.public_metadata),i$1=r(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$1,metadataVersion:t.metadata_version}}function Le(e,t){let{post:n,mutation:i}=L(e,t);return {getMetadata:o=>Ne(e,o),updateUnsafeMetadata:(o,a)=>Ue(e,o,a),updateProfile:(o,a)=>i(n("/update-user",o,a,j)),changeEmail:(o,a)=>i(n("/change-email",o,a,j)),changePassword:(o,a)=>i(n("/change-password",o,a,bn)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:wn}),revokeSession:({sessionId:o},a)=>i(n("/revoke-session",{sessionId:o},a,j)),revokeOtherSessions:o=>i(n("/revoke-other-sessions",{},o,j)),listSocialAccounts:async o=>{let a=await e.request("/list-accounts",{fetchOptions:o,decode:kn});if(!a.data)return {data:null,error:a.error};let r=a.data.length>1;return {...a,data:a.data.filter(u=>u.providerId!=="credential").map(u=>({...u,canUnlink:r}))}},linkSocial:(o,a)=>n("/link-social",o,a,Sn),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,j)),delete:(o={},a)=>i(n("/delete-user",o,a,Rn))}}function j(e){let t=i(e);return {status:k$1(t.status)}}function bn(e){let t=i(e);return {user:o(t.user)}}function wn(e){return Array.isArray(e)||q$1(),e.map(t=>{let n$1=i(t);return {id:j$1(n$1.id),userId:j$1(n$1.userId),createdAt:l(n$1.createdAt),updatedAt:l(n$1.updatedAt),expiresAt:l(n$1.expiresAt),..._e("ipAddress",n(n$1,"ipAddress")),..._e("userAgent",n(n$1,"userAgent"))}})}function kn(e){return Array.isArray(e)||q$1(),e.map(t=>{let n=i(t);return {id:j$1(n.id),userId:j$1(n.userId),providerId:j$1(n.providerId),accountId:j$1(n.accountId),scopes:m$1(n.scopes),createdAt:l(n.createdAt),updatedAt:l(n.updatedAt)}})}function Sn(e){let t=i(e);return {url:j$1(t.url),redirect:k$1(t.redirect)}}function Rn(e){let t=i(e);return {success:k$1(t.success),message:j$1(t.message)}}function _e(e,t){return t===void 0?{}:{[e]:t}}var In=new Set(["pending","accepted","rejected","canceled"]),Fe=1e4;function F(e,t,n$1){let i$1=i(e),o={id:m(i$1.id),name:m(i$1.name),slug:m(i$1.slug),createdAt:l(i$1.createdAt),...$("logo",n(i$1,"logo")),...$("metadata",i$1.metadata===void 0?void 0:s(i$1.metadata))};return M(o.id,t),M(o.slug,n$1),o}function qe(e){return _(e,F)}function pe(e,t,n){return e===null?null:(t===null&&q$1(),F(e,t,n))}function Ve(e,t,n){if(e===null)return null;let i$1=i(e),o=F(i$1,t,n);return {...o,members:_(i$1.members,a=>et(a,o.id)),invitations:_(i$1.invitations,a=>N(a,void 0,o.id))}}function He(e,t){let n=_(e,i=>Ze(i));return Y(n.map(i=>i.organizationId),t),n}function Be(e,t,n){return e===null?null:(t===null&&q$1(),Ze(e,t,n))}function Ke(e,t){let n=i(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&q$1(),{members:Pn(n.members,t),total:n.total}}function N(e,t,n){let i$1=i(e),o=m(i$1.status);In.has(o)||q$1();let a={id:m(i$1.id),organizationId:m(i$1.organizationId),email:m(i$1.email),role:m(i$1.role),status:o,inviterId:m(i$1.inviterId),expiresAt:l(i$1.expiresAt),createdAt:l(i$1.createdAt)};return M(a.id,t),M(a.organizationId,n),a}function je(e,t){let n=_(e,i=>N(i));return Y(n.map(i=>i.organizationId),t),n}function Je(e){return _(e,t=>{let n=i(t);return {...N(n),organizationName:m(n.organizationName)}})}function Ge(e,t){let n=i(e);return {...N(n,t),organizationName:m(n.organizationName),organizationSlug:m(n.organizationSlug),inviterEmail:m(n.inviterEmail)}}function We(e,t){let n=i(e),i$1=N(n.invitation,t);return {invitation:i$1,member:q(n.member,void 0,i$1.organizationId)}}function Xe(e,t){let n=i(e);return n.member!==null&&q$1(),{invitation:n.invitation===null?null:N(n.invitation,t),member:null}}function $e(e,t){return e===null?null:N(e,t)}function Ye(e,t,n){let i$1=i(e);return {member:q(i$1.member,n,t)}}function q(e,t,n){let i$1=i(e),o={id:m(i$1.id),organizationId:m(i$1.organizationId),userId:m(i$1.userId),role:m(i$1.role),createdAt:l(i$1.createdAt),...i$1.user===void 0?{}:{user:tt(i$1.user)}};return M(o.id,t),M(o.organizationId,n),o}function Qe(e,t){let n=_(e,i$1=>{let o=i(i$1);return {organizationId:m(o.organizationId),data:{role:m(o.role),...$("permission",o.permission===void 0?void 0:Tn(o.permission))}}});return Y(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function Ze(e,t,n){let i$1=i(e),o=i$1.updatedAt,a={id:m(i$1.id),name:m(i$1.name),organizationId:m(i$1.organizationId),createdAt:l(i$1.createdAt),...o===void 0?{}:{updatedAt:l(o)}};return M(a.id,t),M(a.organizationId,n),a}function et(e,t){let n=i(e);return {...q(n,void 0,t),user:tt(n.user)}}function Pn(e,t){let n=_(e,i=>et(i));return Y(n.map(i=>i.organizationId),t),n}function Tn(e){let t=i(e),n={};for(let[i,o]of Object.entries(t))(i==="__proto__"||i==="constructor"||i==="prototype"||i.length===0||i.length>Fe||!Array.isArray(o))&&q$1(),n[i]=o.map(a=>m(a));return n}function m(e){let t=j$1(e);return (t.length===0||t.length>Fe)&&q$1(),t}function M(e,t){t!==void 0&&e!==t&&q$1();}function Y(e,t){let n=t??e[0];n!==void 0&&e.some(i=>i!==n)&&q$1();}function tt(e){let t=i(e);return {id:m(t.id),name:m(t.name),email:m(t.email),...$("image",n(t,"image"))}}function _(e,t){return Array.isArray(e)||q$1(),e.map(n=>t(n))}function $(e,t){return t===void 0?{}:{[e]:t}}function nt(e,t$1,n=()=>null){let{post:i,mutation:o}=L(e,t$1),a=(r,u,c,h)=>e.request(r,{query:u,fetchOptions:c,decode:h});return {create:(r,u)=>o(i("/organization/create",r,u,F)),list:r=>a("/organization/list",void 0,r,qe),get:(r={},u)=>a("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},u,c=>Ve(c,r.organizationId,r.organizationSlug)),setActive:(r,u)=>o(i("/organization/set-active",r,u,c=>pe(c,r.organizationId,r.organizationSlug))),listTeams:(r={},u)=>a("/organization/list-teams",{organizationId:r.organizationId},u,c=>He(c,r.organizationId)),setActiveTeam:(r,u)=>o(i("/organization/set-active-team",r,u,c=>Be(c,r.teamId))),update:(r,u)=>o(i("/organization/update",r,u,c=>pe(c,r.organizationId))),delete:(r,u)=>o(i("/organization/delete",r,u,c=>F(c,r.organizationId))),listMembers:(r={},u)=>a("/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},u,c=>Ke(c,r.organizationId)),inviteMember:(r,u)=>o(i("/organization/invite-member",r,u,c=>N(c,void 0,r.organizationId))),listInvitations:(r={},u)=>a("/organization/list-invitations",{organizationId:r.organizationId},u,c=>je(c,r.organizationId)),listUserInvitations:r=>a("/organization/list-user-invitations",void 0,r,Je),getInvitation:(r,u)=>a("/organization/get-invitation",{id:r.id},u,c=>Ge(c,r.id)),acceptInvitation:(r,u)=>o(i("/organization/accept-invitation",r,u,c=>We(c,r.invitationId))),rejectInvitation:(r,u)=>o(i("/organization/reject-invitation",r,u,c=>Xe(c,r.invitationId))),cancelInvitation:(r,u)=>o(i("/organization/cancel-invitation",r,u,c=>$e(c,r.invitationId))),removeMember:(r,u)=>o(i("/organization/remove-member",r,u,c=>Ye(c,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,u)=>o(i("/organization/update-member-role",r,u,c=>q(c,r.memberId,r.organizationId))),leave:(r,u)=>o(i("/organization/leave",r,u,c=>q(c,void 0,r.organizationId))),listRoles:(r={},u)=>a("/organization/list-roles",{organizationId:r.organizationId},u,c=>Qe(c,r.organizationId)),has:r=>v(n(),r),hasPermission:r=>t(n(),r.permission)}}var it=4096,vn=4096,Cn=100,Dn=256,xn=16,zn=64,En=12;function fe(e){let t=i(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&q$1(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:wt(t.twoFactorMethods,xn,zn)}}):(t.twoFactorRedirect!==void 0&&q$1(),{redirect:k$1(t.redirect),...Ln(t,"url"),user:o(t.user)})}function ot(e){let t=i(e);return {user:o(t.user)}}function rt(e){let t=i(e);return {sessionCreated:k$1(t.sessionCreated),user:o(t.user)}}function at(e,t){let n=i(e),i$1=k$1(n.redirect);n.user===null&&q$1();let o$1=n.user!==void 0&&n.user!==null,a=n.url!==void 0&&n.url!==null;return i$1?((o$1||!a)&&q$1(),{redirect:true,url:ge(n.url,t)}):(o$1===a&&q$1(),o$1?{redirect:false,user:o(n.user)}:{redirect:false,url:ge(n.url,t)})}function st(e,t){let n=i(e);return (n.redirect!==true||n.user!==void 0)&&q$1(),{redirect:true,url:ge(n.url,t)}}function ut(e){return {status:k$1(i(e).status)}}function ct(e){return {success:k$1(i(e).success)}}function dt(e){return i(e).status!=="pending"&&q$1(),{status:"pending"}}function lt(e){let t=i(e);if(t.kind==="authowl_turnstile")return {kind:"authowl_turnstile"};t.kind!=="akedly_shield_v1_2"&&q$1();let n=i(t.turnstile),i$1=n.siteKey===null?null:j$1(n.siteKey);return {kind:"akedly_shield_v1_2",connectionId:j$1(t.connectionId),challenge:j$1(t.challenge),difficulty:Nn(t.difficulty),challengeToken:j$1(t.challengeToken),challengeRequired:k$1(t.challengeRequired),turnstile:{required:k$1(n.required),siteKey:i$1}}}function Nn(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>En)&&q$1(),Number(e)}function pt(e){let t=i(e);return (t.status!==true||t.sessionCreated!==true)&&q$1(),{status:true,sessionCreated:true,user:Un(t.user)}}function me(e){return {status:k$1(i(e).status)}}function gt(e){return {status:k$1(i(e).status)}}function ft(e){let t=i(e);return {status:k$1(t.status),user:o(t.user)}}function mt(e){return {success:k$1(i(e).success)}}function ht(e){let t=i(e);return {totpURI:_n(t.totpURI),backupCodes:bt(t.backupCodes)}}function At(e){return {status:k$1(i(e).status)}}function Q(e){return i(e).status!==true&&q$1(),{status:true}}function yt(e){return {status:k$1(i(e).status)}}function Ot(e){let t=i(e);return t.status!==void 0&&t.status!==true&&q$1(),{backupCodes:bt(t.backupCodes)}}function Un(e){let t=i(e);return {id:V(t.id,512),...Fn(t,"name",1024),phoneNumber:V(t.phoneNumber,64),phoneNumberVerified:k$1(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:l(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:l(t.updatedAt)}}}function ge(e,t){let n=V(e,it);/[\u0000-\u0020\u007f]/u.test(n)&&q$1();let i;try{i=new URL(n);}catch{return q$1()}return (i.username||i.password)&&q$1(),i.protocol==="https:"||t&&i.protocol==="http:"&&Mn(i.hostname)?i.href:q$1()}function Mn(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function _n(e){let t=V(e,vn),n;try{n=new URL(t);}catch{return q$1()}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))&&q$1(),t}function bt(e){return wt(e,Cn,Dn)}function wt(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&q$1();let i=e.map(o=>V(o,n));return i.some(o=>o.trim().length===0)&&q$1(),new Set(i).size!==i.length&&q$1(),i}function V(e,t){let n=j$1(e);return (n.length===0||n.length>t)&&q$1(),n}function Ln(e,t){let n=e[t];return n==null?{}:{[t]:V(n,it)}}function Fn(e,t,n$1){let i=n(e,t);return i===void 0?{}:(i!==null&&i.length>n$1&&q$1(),{[t]:i})}var kt=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),Z=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 ee(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||Rt(n,i)||St(i)||kt.has(i))return {valid:false}}let t=qn(e);return he(t)?{valid:true,value:t}:{valid:false}}function he(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||Rt(o,a)||St(a)||kt.has(a))return false;n??=a,i=a;}return t>0&&n!==void 0&&i!==void 0&&!Z.has(n)&&!Z.has(i)}function te(){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 qn(e){let t=0,n=e.length;for(;t<n;){let i=e.codePointAt(t);if(i===void 0||!Z.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,r=e.codePointAt(a);if(r===void 0||!Z.has(r))break;n=a;}return e.slice(t,n)}function St(e){return e>=0&&e<=31||e>=127&&e<=159}function Rt(e,t){return e.length===1&&t>=55296&&t<=57343}var Tt=12,vt=5e3,Vn=8,Hn=1e3,Bn=16,It=512,Ct=100,Dt=8192,Kn=32768,Ae=1024,Pt=256,Oe=64,jn=6e5,Jn=/^[A-Za-z0-9_-]+$/u,Gn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,Wn=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,Xn=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,$n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,xt=new Set(["discouraged","preferred","required"]),Yn=new Set(["singleDevice","multiDevice"]),zt=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),Et=new Set(["hybrid","security-key","client-device"]),Qn=new Set(["none","indirect","direct","enterprise"]),Zn=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),ei=new Set(["platform","cross-platform"]),ti=new Set(["discouraged","preferred","required"]),ni=new Set([-8,-7,-257]);function Nt(e){let t=r(e,Tt,vt);return {challenge:Kt(t.challenge),...k("timeout",Ht(t.timeout)),...k("rpId",jt(t.rpId)),...k("allowCredentials",Vt(t.allowCredentials)),...k("userVerification",J(t.userVerification,xt)),...k("hints",ne(t.hints,Et)),...k("extensions",Bt(t.extensions))}}function Ut(e){let t=r(e,Tt,vt);return {challenge:Kt(t.challenge),rp:ii(t.rp),user:oi(t.user),pubKeyCredParams:ri(t.pubKeyCredParams),...k("timeout",Ht(t.timeout)),...k("excludeCredentials",Vt(t.excludeCredentials)),...k("authenticatorSelection",ai(t.authenticatorSelection)),...k("attestation",J(t.attestation,Qn)),...k("attestationFormats",ne(t.attestationFormats,Zn)),...k("hints",ne(t.hints,Et)),...k("extensions",Bt(t.extensions))}}function Mt(e){let t=i(e),n=p(t.session),i$1=o(t.user);return n.userId!==i$1.id&&q$1(),{session:n,user:i$1}}function be(e){let t=i(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&q$1();let i$1=we(t.deviceType,Yn),o=k$1(t.backedUp);return o&&i$1!=="multiDevice"&&q$1(),{id:H(t.id,Pt),...ci(t),publicKey:si(t.publicKey,Kn),userId:H(t.userId,Pt),credentialID:oe(t.credentialID,Dt),counter:n,deviceType:i$1,backedUp:o,...di(t),createdAt:l(t.createdAt),...li(t)}}function _t(e,t,n){let i=be(e);return (i.credentialID!==t||(n===void 0?i.name!==void 0&&i.name!==null:i.name!==n))&&q$1(),i}function Lt(e){(!Array.isArray(e)||e.length>Ct)&&q$1();let t=e.map(be);return ie(t.map(n=>n.id)),ie(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&q$1(),t}function Ft(e,t,n){let i$1=i(e),o=be(i$1.passkey);return (o.id!==t||o.name!==n)&&q$1(),{passkey:o}}function qt(e){return i(e).status!==true&&q$1(),{status:true}}function ii(e){let t=i(e);return {name:ye(t.name,Ae),...k("id",jt(t.id))}}function oi(e){let t=i(e);return {id:oe(t.id,128,1,64),name:ye(t.name,Ae),displayName:ye(t.displayName,Ae)}}function ri(e){(!Array.isArray(e)||e.length===0||e.length>Oe)&&q$1();let t=e.map(n=>{let i$1=i(n);return (i$1.type!=="public-key"||!Number.isSafeInteger(i$1.alg)||!ni.has(i$1.alg))&&q$1(),{type:"public-key",alg:i$1.alg}});return pi(t.map(n=>n.alg)),t}function Vt(e){if(e===void 0)return;(!Array.isArray(e)||e.length>Ct)&&q$1();let t=e.map(n=>{let i$1=i(n);return i$1.type!=="public-key"&&q$1(),{type:"public-key",id:oe(i$1.id,Dt),...k("transports",ne(i$1.transports,zt))}});return ie(t.map(n=>n.id)),t}function ai(e){if(e===void 0)return;let t=i(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&q$1();let n=J(t.residentKey,ti);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&q$1(),{...k("authenticatorAttachment",J(t.authenticatorAttachment,ei)),...k("residentKey",n),...k("requireResidentKey",t.requireResidentKey),...k("userVerification",J(t.userVerification,xt))}}function Ht(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>jn)&&q$1(),e}function Bt(e){return e===void 0?void 0:r(e,Vn,Hn)}function ne(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>Oe)&&q$1();let n=e.map(i=>we(i,t));return ie(n),n}function J(e,t){if(e!==void 0)return we(e,t)}function Kt(e){return oe(e,Math.ceil(It*4/3),Bn,It)}function oe(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=H(e,t),a=o.length%4,r=ui(o.at(-1)??""),u=Math.floor(o.length*3/4);return (!Jn.test(o)||a===1||a===2&&(r&15)!==0||a===3&&(r&3)!==0||u<n||u>i)&&q$1(),o}function H(e,t){let n=j$1(e);return (n.length===0||n.length>t)&&q$1(),n}function ye(e,t){let n=H(e,t);return Wn.test(n)&&q$1(),n}function jt(e){if(e===void 0)return;let t=H(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!Xn.test(n)))&&q$1(),t}function si(e,t){let n=H(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",r=Jt(a);return (n.length%4!==0||!Gn.test(n)||i&&(r&15)!==0||o&&(r&3)!==0)&&q$1(),n}function ui(e){return Jt(e,true)}function Jt(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function ci(e){let t=n(e,"name");return t===void 0?{}:(t!==null&&!he(t)&&q$1(),{name:t})}function di(e){let t=n(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n$1=t.split(",");return (n$1.length>Oe||n$1.some(i=>!zt.has(i))||new Set(n$1).size!==n$1.length)&&q$1(),{transports:t}}function li(e){let t=n(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:($n.test(t)||q$1(),{aaguid:t})}function we(e,t){let n=j$1(e);return t.has(n)||q$1(),n}function k(e,t){return t===void 0?{}:{[e]:t}}function ie(e){new Set(e).size!==e.length&&q$1();}function pi(e){new Set(e).size!==e.length&&q$1();}function gi(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 Gt=new Map;function fi(e,t,n){let i=Gt.get(n);return i||(i=import('./session-handoff-VJI4IXLT.js').then(o=>o.completeCrossSiteSignIn(e,t)),Gt.set(n,i)),i}function Wt(e){return !a()||e.idToken||e.disableRedirect?"legacy":"first-party"}function mi(e,t=()=>{},n=yi){let i=de(e),o=e.session.tokens,a$1=a()?fi(i,o,e.decoded.projectId):void 0,r=gi(i,a$1),u=Ee({http:r,probe:de({...e,fetch:e.session.probe}),tokens:o,channelName:`authowl:${e.decoded.projectId}`}),c=n(r,u.notifyMutation),h=()=>{u.notifyMutation(),t();},{post:g,mutation:A}=L(r,h),I=e.decoded.env==="test",O=s=>{o.beginSession({remember:s?.rememberMe!==false});};return {sessionStore:u.store,getSession:u.getSession,account:Le(r,h),organization:nt(r,h,()=>u.store.getSnapshot().data?.session.membership??null),signIn:{email:(s,l)=>(O(s),A(g("/sign-in/email",s,l,fe),f=>!("twoFactorRedirect"in f))),username:(s,l)=>(O(s),A(g("/sign-in/username",s,l,fe),f=>!("twoFactorRedirect"in f))),social:async(s,l)=>{if(O(),Wt(s)==="first-party"){let{beginCrossSiteSignIn:S}=await import('./session-handoff-VJI4IXLT.js'),v=await S(e,{kind:"social",provider:s.provider,callbackURL:s.callbackURL,errorCallbackURL:s.errorCallbackURL,newUserCallbackURL:s.newUserCallbackURL,scopes:s.scopes,loginHint:s.loginHint,requestSignUp:s.requestSignUp});if(v)return window.location.assign(v),{data:{redirect:true,url:v},error:null}}let f=await A(g("/sign-in/social",s,l,S=>at(S,I)),S=>"user"in S);return f.error!==null||f.data===null||"url"in f.data&&f.data.redirect&&!s.disableRedirect&&typeof window<"u"&&window.location.assign(f.data.url),f},sso:async(s,l)=>{if(Wt(s)==="first-party"){let{beginCrossSiteSignIn:S}=await import('./session-handoff-VJI4IXLT.js'),v=await S(e,{kind:"sso",email:s.email,providerId:s.providerId,domain:s.domain,organizationSlug:s.organizationSlug,callbackURL:s.callbackURL,errorCallbackURL:s.errorCallbackURL,newUserCallbackURL:s.newUserCallbackURL});if(v)return window.location.assign(v),{data:{url:v,redirect:true},error:null}}let f=await g("/sign-in/sso",s,l,S=>st(S,I));return f.error!==null||f.data===null||typeof window<"u"&&window.location.assign(f.data.url),f},magicLink:(s,l)=>g("/sign-in/magic-link",s,l,ut),emailOtp:(s,l)=>(O(),A(g("/sign-in/email-otp",s,l,ot))),passkey:(s,l)=>(O(),c.signIn(s,l))},signUp:{email:(s,l)=>(O(),A(g("/sign-up/email",s,l,rt),f=>f.sessionCreated))},emailOtp:{sendVerificationOtp:(s,l)=>g("/email-otp/send-verification-otp",s,l,ct),verifyEmail:(s,l)=>(O(),A(g("/email-otp/verify-email",s,l,ft)))},phoneOtp:{prepare:s=>g("/phone-otp/challenge",{},s,lt),start:(s,l)=>g("/phone-otp/start",{...s,idempotencyKey:s.idempotencyKey??ze()},l,dt),verify:(s,l)=>(O(),A(g("/phone-otp/verify",s,l,pt)))},requestPasswordReset:(s,l)=>g("/request-password-reset",s,l,me),resetPassword:(s,l)=>g("/reset-password",s,l,me),sendVerificationEmail:(s,l)=>g("/send-verification-email",s,l,gt),passkey:{addPasskey:(s,l)=>c.add(s,l),listUserPasskeys:()=>r.request("/passkey/list-user-passkeys",{decode:Lt}),updatePasskey:async(s,l)=>{let f=ee(s.name);if(!f.valid||f.value===void 0)return te();let S=f.value;return g("/passkey/update-passkey",{...s,name:S},l,v=>Ft(v,s.id,S))},deletePasskey:(s,l)=>g("/passkey/delete-passkey",s,l,qt)},twoFactor:{enable:(s,l)=>g("/two-factor/enable",s,l,ht),disable:(s,l)=>A(g("/two-factor/disable",s,l,At),f=>f.status),verifyTotp:(s,l)=>A(g("/two-factor/verify-totp",s,l,Q)),verifyBackupCode:(s,l)=>A(g("/two-factor/verify-backup-code",s,l,Q)),sendOtp:(s={},l)=>g("/two-factor/send-otp",s,l,yt),verifyOtp:(s,l)=>A(g("/two-factor/verify-otp",s,l,Q)),generateBackupCodes:(s,l)=>g("/two-factor/generate-backup-codes",s,l,Ot)},signOut:s=>A(r.request("/sign-out",{method:"POST",body:{},fetchOptions:s,decode:mt}).then(l=>(o.endSession(),l)),l=>l.success)}}function po(e,t=()=>{},n){let i=mi(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:Xt(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:Xt(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function Xt(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return hi();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?Ai():i}}function hi(){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 Ai(){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 yi(){return {signIn:()=>$t(),add:()=>$t()}}function $t(){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 ho(e,t,n){let i=new Map;return {async signIn(o={},a){let r=await e.request("/passkey/generate-authenticate-options");if(!r.data)return Zt(r.error);let u;try{u=Nt(r.data);}catch{return Yt()}let c;try{c=await n.authenticate({optionsJSON:u,useBrowserAutofill:o.autoFill});}catch(O){return en(n,O,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!Oi(c))return Qt();let{clientExtensionResults:h,...g}=c,A=i.get(c.id);if(A)return A;let I=(async()=>{let O=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:g},fetchOptions:a,decode:Mt});return O.data&&t(),O})();i.set(c.id,I);try{return await I}finally{i.get(c.id)===I&&i.delete(c.id);}},async add(o={},a){let r=ee(o.name);if(!r.valid)return te();let u=await e.request("/passkey/generate-register-options",{query:{name:r.value,authenticatorAttachment:o.authenticatorAttachment}});if(!u.data)return Zt(u.error);let c;try{c=Ut(u.data);}catch{return Yt()}let h;try{h=await n.register({optionsJSON:c});}catch(O){return en(n,O,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!bi(h))return Qt();let{clientExtensionResults:g,...A}=h,I=await e.request("/passkey/verify-registration",{method:"POST",body:{response:A,name:r.value},fetchOptions:a,decode:O=>_t(O,h.id,r.value)});return I.data&&t(),I}}}function Yt(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function Qt(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function tn(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 Oi(e){if(!tn(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 bi(e){if(!tn(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function Zt(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function en(e,t,n,i){let o=ki(t,"page does not have focus"),a=e.errorCode?.(t),r=a!==void 0?a==="ERROR_CEREMONY_ABORTED":wi(t)==="AbortError";return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:o?"PASSKEY_PAGE_NOT_FOCUSED":r?n:a??"PASSKEY_BROWSER_ERROR",message:o?"Keep this page focused while completing the passkey prompt.":r?i:n==="AUTH_CANCELLED"?"Passkey authentication could not be completed by this browser.":"Passkey registration could not be completed by this browser."}}}function wi(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function ki(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 bo(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return Ce(await X(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>Si(i,e)}),"public-config")}function Si(e,t){let n=r(e),i=n.environmentId,o=n.environmentType,a=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Ri(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==a)throw z();let r$1=T(n.branding),u=T(n.legal);if(!ke(n.enabledMethods,64)||!ke(n.socialProviders,64)||!on(r$1,["appName","logoUrl","primaryColor"])||r$1.showAppName!==void 0&&typeof r$1.showAppName!="boolean"||r$1.alignment!==void 0&&r$1.alignment!=="left"&&r$1.alignment!=="center"&&r$1.alignment!=="right"||r$1.theme!==void 0&&r$1.theme!=="light"&&r$1.theme!=="dark"&&r$1.theme!=="system"||!on(u,["termsUrl","privacyUrl"])||!Number.isSafeInteger(u.version)||u.version<0||typeof u.required!="boolean")throw z();if(n.socialProviderClientIds!==void 0){let c=T(n.socialProviderClientIds);if(Object.keys(c).length>64||Object.values(c).some(h=>typeof h!="string"||h.length>2048))throw z()}if(!U(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!nn(n.turnstileSiteKey)||!nn(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw z();if(n.jwtIssuer!==null){let c=T(n.jwtIssuer);if(c.issuer!==a||c.jwksUrl!==`${a}/jwks`||c.aud!==t.decoded.projectId)throw z()}if(n.signUp!==void 0){let c=T(n.signUp).mode;if(typeof c!="string"||!["open","restricted","allowlist","waitlist"].includes(c))throw z()}if(n.authentication!==void 0&&Ii(n.authentication),n.emailVerification!==void 0){let c=T(n.emailVerification);if(!U(c,["required"])||c.method!=="link"&&c.method!=="code")throw z()}if(n.userModel!==void 0&&!U(T(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw z();if(n.mfa!==void 0){let c=T(n.mfa);if(!U(c,["totp","required","backupCodes"])||(c.required===true||c.backupCodes===true)&&c.totp!==true)throw z()}return n}function Ri(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 z(){return new TypeError("public-config returned an invalid response")}function T(e){if(!e||typeof e!="object"||Array.isArray(e))throw z();return e}function nn(e){return e===null||typeof e=="string"&&e.length<=4096}function Ii(e){let t=T(e),n=T(t.email),i=T(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!U(n,["signUp"])||!ke(n.signIn,3)||n.signIn.some(a=>a!=="password"&&a!=="magic_link"&&a!=="email_otp")||!U(T(t.phone),["signUp","signIn"])||!U(i,["signUp","add"])||o&&(!Number.isSafeInteger(i.minLength)||!Number.isSafeInteger(i.maxLength)||i.minLength<1||i.maxLength>4096||i.minLength>i.maxLength)||!U(T(t.passkey),["signIn","add"])||!Pi(T(t.passkey).relyingPartyId)||!U(T(t.username),["collectOnSignUp","signIn"]))throw z()}function Pi(e){return e==null||typeof e=="string"}function U(e,t){return t.every(n=>typeof e[n]=="boolean")}function on(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function ke(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{Ti as a,ae as b,X as c,Ce as d,sn as e,de as f,ze as g,mi as h,po as i,ho as j,bo as k};