@authowl/core 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import {d,c,E as E$1,B as B$1,p,o,n,z}from'./chunk-5REZDJ26.js';export{l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,m as resolveAuthTarget,n as resolveConfig,b as sessionCookieName}from'./chunk-5REZDJ26.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 p({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:ne,maxResponseBytes:se,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>z(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=pe(n.data);return D.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof o)switch(n.kind){case "timeout":throw new i("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new i("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new i("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new i("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function 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$1=async(p$1,c)=>{let m=c??{},f=A[p$1],y=new URL(Le(f.path,m).replace(/^\/+/,""),r);Ne(y,m);let d=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Re(d,m);let h="body"in m?JSON.stringify(m.body):void 0;h!==void 0&&d.set("content-type","application/json");let S;try{S=await p({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$1,Y.status,u)});}catch(u){throw u instanceof O?u:u instanceof o?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$1});for(let p of Object.keys(A))a[p]=c=>o$1(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$1=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n$1)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n$1){if(typeof e?.issuer!="string"||typeof e.jwksUri!="string"||typeof e.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return k({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let s,o;if(r){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e.publishableKey,o=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o=process.env.AUTHOWL_API_URL;if(!s||!o)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let a=n({publishableKey:s,apiUrl:o});return k({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},a.decoded.env==="test")}async function 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 E$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 B$1(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};
1
+ import {d,c,E as E$1,B as B$1,p,o,n,z}from'./chunk-V3MSLXXB.js';export{l as SESSION_TRANSPORT_BEARER,k as SESSION_TRANSPORT_HEADER,m as resolveAuthTarget,n as resolveConfig,b as sessionCookieName}from'./chunk-V3MSLXXB.js';var i=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},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 p({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:ne,maxResponseBytes:se,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>z(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=pe(n.data);return D.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof o)switch(n.kind){case "timeout":throw new i("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new i("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new i("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new i("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function 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(p=>typeof p=="string"):[],o=Array.isArray(r.roles)?r.roles.filter(p=>typeof p=="string"):void 0,a=Array.isArray(r.teams)?r.teams.filter(p=>typeof p=="string"):void 0;return n===""&&s.length===0&&!o?.length&&!a?.length?null:{role:n,...o===void 0?{}:{roles:o},permissions:s,...a===void 0?{}:{teams:a}}}async function 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$1=async(p$1,c)=>{let m=c??{},f=A[p$1],y=new URL(Le(f.path,m).replace(/^\/+/,""),r);Ne(y,m);let d=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Re(d,m);let h="body"in m?JSON.stringify(m.body):void 0;h!==void 0&&d.set("content-type","application/json");let S;try{S=await p({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$1,Y.status,u)});}catch(u){throw u instanceof O?u:u instanceof o?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$1});for(let p of Object.keys(A))a[p]=c=>o$1(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$1=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n$1)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n$1){if(typeof e?.issuer!="string"||typeof e.jwksUri!="string"||typeof e.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return k({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let s,o;if(r){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e.publishableKey,o=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o=process.env.AUTHOWL_API_URL;if(!s||!o)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let a=n({publishableKey:s,apiUrl:o});return k({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},a.decoded.env==="test")}async function 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 E$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 B$1(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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authowl/core",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
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 le=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,de=/^sk_/i;function q(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(de.test(e))throw new Error("A secret key was passed where a publishable key was expected. Never embed secret keys in client code.");let t=le.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1].toLowerCase(),env:t[2].toLowerCase(),projectId:t[3].toLowerCase()}}function $e(e,t){let n=`p_${e.toLowerCase().replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}function O(e,t){try{return e?.getItem(t)??null}catch{return null}}function A(e,t,n){try{n===null?e?.removeItem(t):e?.setItem(t,n);}catch{}}function _(){try{return globalThis.localStorage}catch{return}}function x(){try{return globalThis.sessionStorage}catch{return}}var pe="authowl.session-challenge",fe=e=>`${pe}.${e}`,he="set-auth-challenge",D="x-authowl-challenge";function Ge(e){let t=e.get(D);return H(t)?$(t).some(([n,r])=>n.endsWith(".dont_remember")&&r.length>0):false}var Ye="INVALID_TWO_FACTOR_COOKIE",be=2048,H=e=>e!==null&&e.length<=be,J=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;function $(e){let t=[];for(let n of e.split(";")){let r=n.trimStart(),o=r.indexOf("=");o<=0||t.push([r.slice(0,o).trimEnd(),r.slice(o+1)]);}return t}function z(e){let t=fe(e),n=new Map;function r(){return n.size===0?null:[...n].map(([s,a])=>`${s}=${a}`).join("; ")}function o(){let s=r();A(x(),t,H(s)?s:null);}function l(s){for(let[a,c]of $(s))J.test(a)&&(c===""?n.delete(a):J.test(c)&&n.set(a,c));}let u=O(x(),t);return H(u)&&l(u),{presentOn(s){let a=r();s.delete(D),H(a)&&s.set(D,a);},observe(s){let a=s.get(he);H(a)&&(l(a),o());},clear(){n.clear(),o();}}}var M="set-auth-token",W="x-authowl-session-transport",G="bearer";var j=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function m(e,t){throw new Error(`${e}: ${t}`)}function ge(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function Y(e,{label:t,allowHttpLoopback:n}){(typeof e!="string"||e.length===0)&&m(t,"required"),e!==e.trim()&&m(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&m(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&m(t,"path must be unencoded");let r;try{r=new URL(e);}catch{m(t,"absolute URL required");}return (r.username||r.password)&&m(t,"credentials forbidden"),r.protocol!=="https:"&&r.protocol!=="http:"&&m(t,"HTTPS required"),r.protocol==="http:"&&(!n||!j.test(e))&&m(t,"HTTPS required except exact loopback"),r}function X(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 Q(e,t,n){let r=ge(e);(r.includes("//")||r.split("/").some(o=>o==="."||o==="..")||r!==""&&r!==t.pathname)&&m(n,"path traversal or duplicate separator");}function Z(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&m("apiUrl","origin required");let n;try{n=new URL(e);}catch{m("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!j.test(e))&&m("apiUrl","HTTPS required except exact loopback"),n.origin}function Ze(e,t,n={allowHttpLoopback:false}){let r=Y(e,{label:"issuer",allowHttpLoopback:n.allowHttpLoopback}),o=Y(t,{label:"jwksUri",allowHttpLoopback:n.allowHttpLoopback});return Q(e,r,"issuer"),Q(t,o,"jwksUri"),r.pathname!=="/"&&r.pathname.endsWith("/")&&m("issuer","trailing slash forbidden"),{issuer:r.toString().replace(/\/$/,""),jwksUri:o.toString()}}var me="authowl.session-token",ye="authowl.cookie-transport",te="ok",ne="bearer",we=e=>`${me}.${e}`,Re=e=>`${ye}.${e}`;function Te(e){return e===te?"cookies":e===ne?"bearer":"unknown"}function ke(e){return e==="cookies"?te:e==="bearer"?ne:null}function Se(e){let t=we(e),n=Re(e),r=z(e),o=null,l=false,u=null,s=Te(O(_(),n)),a=()=>s==="unknown",c=0,d=null,w=false;function b(){let i=O(x(),t);if(i!==null)return l=true,i;let g=O(_(),t);return g!==null?(l=false,g):null}o=b(),o!==null&&a()&&(w=true);function E(){if(!(!w||!d)){w=false;try{d();}catch{}}}function R(){let i=s==="bearer"?o:null,[g,K]=l?[x(),_()]:[_(),x()];A(K,t,null),A(g,t,i);}function L(i){i!==null&&u!==null&&(l=u,u=null),o=i,R(),i!==null&&a()&&(w=true,E());}function p(i){s=i,A(_(),n,ke(i));}function T(){p("unknown"),w=false;}function k(){return o===null&&(o=b()),o}function P(){let i=b();return i!==null&&(o=i),o}function C(i){P()===i&&R();}function U(){c+=1,u=null,l=false,L(null),r.clear(),T();}let v=()=>s!=="cookies";return {hasToken:()=>k()!==null,declareOn(i){if(i.has("authorization"))return false;let g=k();return !g&&!v()?false:(g&&i.set("authorization",`Bearer ${g}`),i.set(W,G),r.presentOn(i),true)},wantsToken:v,needsProbe:a,observe(i){let g=i.get(M);g&&L(g),r.observe(i);},dropChallenge:r.clear,measureWith(i){d=i,E();},beginRead(){let i=k(),g=c;return {carriedToken:i!==null,endIfDead(){i!==null&&P()===i&&c===g&&U();},recordCookieVerdict(K){if(c===g&&a()){if(p(K?"cookies":"bearer"),K){L(null);return}C(i);}}}},beginSession({remember:i}){c+=1,u=!i,r.clear(),T();},endSession:U}}var ee=new Map;function re(e){let t=ee.get(e);if(t)return t;let n=Se(e);return ee.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 oe(e,t){let n=re(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 xe(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=q(e.publishableKey),n=Z(e.apiUrl,{allowHttpLoopback:t.env==="test"});return {publishableKey:e.publishableKey,apiUrl:n,decoded:t,projectBaseURL:`${n}/api/projects/${t.projectId}/auth`}}function lt(e){let t=xe(e),{fetch:n,...r}=oe(t.decoded.projectId,e.fetch);return {...e,...t,fetch:n,session:r}}var Oe=1e4,Ae=1024*1024,N=class extends Error{kind;requestId;constructor(t,n){super(Ke(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},ae=new WeakSet;function f(e,t){let n=new N(e,t);return ae.add(n),n}async function ft({fetchImpl:e,url:t,init:n={},timeoutMs:r=Oe,maxResponseBytes:o=Ae,allowHttpLoopback:l=false,decode:u}){ie(r,"timeoutMs"),ie(o,"maxResponseBytes");let s=X(t,{allowHttpLoopback:l}),a=n.signal,c=new AbortController,d=null,w,b=new Promise(p=>{w=p;}),E=p=>{d===null&&(d=p,w({type:"abort",kind:p}),c.abort());},R=()=>E("aborted");a?.addEventListener("abort",R,{once:true});let L=setTimeout(()=>E("timeout"),r);a?.aborted&&R();try{if(d!==null)throw f(d);let p;try{p=await Promise.race([e(s.toString(),{...n,redirect:"error",signal:c.signal}).then(v=>({type:"response",response:v})),b]);}catch{throw f(d??"network")}if(p.type==="abort")throw f(p.kind);if(!_e(p.response))throw f("invalid_response");let T=p.response,k=ve(T.headers),P=await Le(T,o,b,()=>d,k),C=Pe(T,P,k),U;try{U=T.ok&&u?u(C,Object.freeze({status:T.status})):C;}catch{throw f("invalid_response",k)}return {response:T,data:U,...k===void 0?{}:{requestId:k}}}catch(p){throw p instanceof N&&ae.has(p)?p:f(d??"network")}finally{clearTimeout(L),a?.removeEventListener("abort",R);}}function _e(e){if(!e||typeof e!="object")return false;let t=e;return Number.isInteger(t.status)&&t.status>=0&&t.status<=599&&typeof t.statusText=="string"&&typeof t.ok=="boolean"&&typeof t.headers?.get=="function"&&(t.body===null||typeof t.body=="object"&&typeof t.body?.getReader=="function"&&typeof t.body.cancel=="function")}async function Le(e,t,n,r,o){let l=e.headers.get("content-length");if(l!==null){if(!/^\d+$/.test(l))throw se(e.body),f("invalid_response",o);if(Number(l)>t)throw se(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 b;try{b=await Promise.race([u.read(),n]);}catch{c=f(r()??"network",o);break}if(Ue(b)){c=f(b.kind,o);break}let{done:E,value:R}=b;if(E)break;if(R.byteLength!==0){if(a+=R.byteLength,a>t){c=f("response_too_large",o);break}s.push(R);}}}finally{c&&He(u);try{u.releaseLock();}catch{}}if(c)throw c;let d=new Uint8Array(a),w=0;for(let b of s)d.set(b,w),w+=b.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(d)}catch{throw f("invalid_response",o)}}function Ue(e){return "type"in e&&e.type==="abort"}function se(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function He(e){try{e.cancel().catch(()=>{});}catch{}}function Pe(e,t,n){if(e.status===204||e.status===205)return null;let r=Ce(e.headers.get("content-type"));if(!e.ok&&(!r||t.length===0))return null;if(!r||t.length===0)throw f("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw f("invalid_response",n)}}function Ce(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function ve(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function ie(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function Ke(e){switch(e){case "aborted":return "The request was cancelled.";case "timeout":return "The request timed out.";case "response_too_large":return "The response exceeded the allowed size.";case "invalid_response":return "The service returned an invalid response.";case "network":return "The network request could not be completed."}}function Ne(e,t){return !e||!t?false:e.permissions.includes(t)}function Ie(e,t){return !e||!t?false:e.teams?.includes(t)??false}function De(e,t){return e?e.roles===void 0?e.role===t:e.roles.includes(t):false}function je(e,t){if(!e)return false;let{role:n,permission:r,teamId:o}=t;return !(n===void 0&&r===void 0&&o===void 0||n!==void 0&&!De(e,n)||r!==void 0&&!e.permissions.includes(r)||o!==void 0&&!Ie(e,o))}function bt(e){return {has:t=>je(e,t),hasPermission:t=>Ne(e,t.permission)}}var Be=new Set(["__proto__","constructor","prototype"]);function 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 Ve(e){return typeof e!="boolean"&&h(),e}function B(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&h(),e}function ue(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 ce(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:h()}function mt(e){let t=F(e),n=t.email;return n!==null&&typeof n!="string"&&h(),{id:I(t.id),email:n,emailVerified:Ve(t.emailVerified),createdAt:B(t.createdAt),updatedAt:B(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",ce(t,"twoFactorEnabled"))}}function yt(e){let t=F(e),n=t.membership;return {id:I(t.id),userId:I(t.userId),expiresAt:B(t.expiresAt),...y("activeOrganizationId",S(t,"activeOrganizationId")),...y("activeTeamId",S(t,"activeTeamId")),...y("membership",n==null?n:qe(n)),...y("pendingMfaEnrollment",ce(t,"pendingMfaEnrollment"))}}function h(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function wt(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&h(),Fe(e,t,n)}function Fe(e,t=20,n=1e4){return V(e,0,{nodes:0},t,n)}function qe(e){let t=F(e);return {role:I(t.role),permissions:ue(t.permissions),...t.teams===void 0?{}:{teams:ue(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))Be.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{Fe as A,Ne as B,Ie as C,De as D,je as E,bt as F,q as a,$e as b,X as c,Ze as d,O as e,A as f,_ as g,Ge as h,Ye as i,M as j,W as k,G as l,xe as m,lt as n,N as o,ft as p,F as q,I as r,Ve as s,B as t,ue as u,S as v,mt as w,yt as x,h as y,wt as z};
@@ -1 +0,0 @@
1
- import {p,o,i,z,s,q as q$1,y,r,w,B,E,x as x$1,t,A,v,u}from'./chunk-5REZDJ26.js';import {a}from'./chunk-T5SH3ZZP.js';function Di(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(c=>c==="password"||c==="magic_link"||c==="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 se=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),p({fetchImpl:e.fetch,url:t,init:{...n.init,headers:i},allowHttpLoopback:e.decoded.env==="test",...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.maxResponseBytes===void 0?{}:{maxResponseBytes:n.maxResponseBytes},...n.decode===void 0?{}:{decode:n.decode}})}function Ee(e,t){if(!e.response.ok)throw new se(t,e.response,e.requestId);return e.data}var dn="x-authowl-turnstile-token",ln=1e4,pn=32,gn=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 le(e,t=e.projectBaseURL){return {async request(n,i$1={}){let o$1=hn(t,n,i$1.query),a=i$1.method??(i$1.body===void 0?"GET":"POST"),c=new Headers(i$1.fetchOptions?.headers);i$1.fetchOptions?.authChallengeToken&&c.set(dn,i$1.fetchOptions.authChallengeToken),i$1.body!==void 0&&c.set("content-type","application/json");let p={method:a,headers:c,credentials:i$1.credentials??"include",...i$1.body===void 0?{}:{body:JSON.stringify(i$1.body)}},r=Object.freeze({method:a,path:n});await i$1.fetchOptions?.onRequest?.(r);let l=mn(a,i$1.fetchOptions),u;try{u=await fn(e,o$1,{...p,signal:i$1.fetchOptions?.signal},l);}catch(m){let I=ze(m);return await i$1.fetchOptions?.onError?.(ue(r,I,On(m))),{data:null,error:I}}let{response:h,requestId:O}=u,A=kn(n,u.data),s=A;if(h.ok)try{s=de(A),i$1.decode&&(s=i$1.decode(s));}catch{let m=ze(new o("invalid_response",O));return await i$1.fetchOptions?.onError?.(ue(r,m,"invalid_response")),{data:null,error:m}}let g=Object.freeze({...r,status:h.status,...O===void 0?{}:{requestId:O}});if(await i$1.fetchOptions?.onResponse?.(g),!h.ok){let m=An(h,A,O);return m.code===i&&e.session.tokens.dropChallenge(),await i$1.fetchOptions?.onError?.(ue(r,m,"api")),{data:null,error:m}}return await i$1.fetchOptions?.onSuccess?.(g),{data:s,error:null}}}}async function fn(e,t,n,i){let o$1=Date.now()+ln;for(let a=0;a<i;a+=1){let c=o$1-Date.now();if(c<=0)throw new o("timeout");try{let p=await X(e,t,{init:n,timeoutMs:Math.max(1,Math.ceil(c))});if(p.response.status<500||a===i-1)return p}catch(p){if(a===i-1||!(p instanceof o)||p.kind!=="network")throw p}await bn(50*2**a,n.signal,o$1);}throw new o("network")}function mn(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 hn(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 An(e,t,n){let i=K(t)?t:{},o=yn(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 yn(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??xe(t.get("retry-after"))??xe(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function xe(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 ze(e){let t=e instanceof o?e.kind:"network";return {status:0,...{aborted:{statusText:"ABORTED",code:"REQUEST_ABORTED",message:"The request was cancelled."},timeout:{statusText:"TIMEOUT",code:"REQUEST_TIMEOUT",message:"The request timed out."},response_too_large:{statusText:"INVALID_RESPONSE",code:"RESPONSE_TOO_LARGE",message:"The service response was too large."},invalid_response:{statusText:"INVALID_RESPONSE",code:"INVALID_RESPONSE",message:"The service returned an invalid response."},network:{statusText:"FETCH_ERROR",code:"FETCH_ERROR",message:"Network request failed."}}[t],...e instanceof o&&e.requestId?{requestId:e.requestId}:{}}}function ue(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function On(e){return e instanceof o?e.kind:"network"}function bn(e,t,n){return new Promise((i,o$1)=>{if(t?.aborted){o$1(new o("aborted"));return}let a=n-Date.now();if(a<=0){o$1(new o("timeout"));return}let c=Math.min(e,a),p=()=>{clearTimeout(r),o$1(new o("aborted"));},r=setTimeout(()=>{t?.removeEventListener("abort",p),Date.now()>=n?o$1(new o("timeout")):i();},c);t?.addEventListener("abort",p,{once:true}),t?.aborted&&p();})}function de(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>pn||i.nodes>gn)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=>de(o,"",n+1,i)):K(e)?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,wn(o)?a:de(a,o,n+1,i)])):e}function wn(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function kn(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>K(o)?ce(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-")?ce(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:ce(i.session)}),i}function ce(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 Ne(){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 Ue({http:e,probe:t,tokens:n,channelName:i}){let o=new Set,a=null,c=null,p=null,r=null,l=null,u,h=y=>{s(y);};u={data:null,isPending:true,isRefetching:false,error:null,refetch:h};function O(y){u=y;for(let S of o)S();}async function A(y){return e.request("/get-session",{query:y?.query,decode:pe})}function s(y){if(y?.query?.disableCookieCache===true)return g(y);if(r)return r;let S=g(y).finally(()=>{r===S&&(r=null);});return r=S,S}async function g(y){p?.abort();let S=new AbortController;p=S,O({...u,isPending:u.data===null&&u.error===null,isRefetching:u.data!==null});let B=n.beginRead(),G=await e.request("/get-session",{query:y?.query,fetchOptions:{signal:S.signal},decode:pe});if(p===S&&(p=null,O({data:G.data,error:G.error,isPending:false,isRefetching:false,refetch:h}),G.error===null)){if(G.data===null){B.endIfDead();return}await m(B);}}async function m(y){if(n.needsProbe()){if(!y.carriedToken){y.recordCookieVerdict(true);return}return l||I(y)}}function I(y){let S=t.request("/get-session",{query:{disableCookieCache:true},decode:pe}).then(B=>{l===S&&B.error===null&&y.recordCookieVerdict(B.data!==null);}).finally(()=>{l===S&&(l=null);});return l=S,S}function v(){a?.postMessage({type:"session-changed"});}function un(){if(typeof window>"u"||c)return;let y=()=>{s();},S=()=>{document.visibilityState==="visible"&&s();};window.addEventListener("focus",y),document.addEventListener("visibilitychange",S),typeof BroadcastChannel<"u"&&(a=new BroadcastChannel(i),a.addEventListener("message",y)),c=()=>{window.removeEventListener("focus",y),document.removeEventListener("visibilitychange",S),a?.close(),a=null,c=null;};}function cn(y){return o.add(y),o.size===1&&(un(),s()),()=>{if(o.delete(y),o.size===0){let S=p;p=null,r=null,S?.abort(),c?.();}}}return n.measureWith(()=>{n.needsProbe()&&I(n.beginRead());}),{store:{subscribe:cn,getSnapshot:()=>u},getSession:A,notifyMutation(){v(),l&&l.catch(()=>{}).then(()=>{!n.needsProbe()&&n.hasToken()&&v();}),o.size>0&&s({query:{disableCookieCache:true}});}}}function pe(e){if(e===null)return null;let t=q$1(e);return (t.session===void 0||t.user===void 0)&&y(),{session:x$1(t.session),user:w(t.user)}}async function _e(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:Le})}async function Me(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:Le})}function Le(e){let t=q$1(e),n=z(t.public_metadata),i=z(t.unsafe_metadata);if(!Number.isSafeInteger(t.metadata_version)||t.metadata_version<0)throw new TypeError("Invalid AuthOwl metadata response");return {publicMetadata:n,unsafeMetadata:i,metadataVersion:t.metadata_version}}function qe(e,t){let{post:n,mutation:i}=L(e,t);return {getMetadata:o=>_e(e,o),updateUnsafeMetadata:(o,a)=>Me(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,Sn)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:Rn}),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:In});if(!a.data)return {data:null,error:a.error};let c=a.data.length>1;return {...a,data:a.data.filter(p=>p.providerId!=="credential").map(p=>({...p,canUnlink:c}))}},linkSocial:(o,a)=>n("/link-social",o,a,Tn),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,j)),delete:(o={},a)=>i(n("/delete-user",o,a,Pn))}}function j(e){let t=q$1(e);return {status:s(t.status)}}function Sn(e){let t=q$1(e);return {user:w(t.user)}}function Rn(e){return Array.isArray(e)||y(),e.map(t$1=>{let n=q$1(t$1);return {id:r(n.id),userId:r(n.userId),createdAt:t(n.createdAt),updatedAt:t(n.updatedAt),expiresAt:t(n.expiresAt),...Fe("ipAddress",v(n,"ipAddress")),...Fe("userAgent",v(n,"userAgent"))}})}function In(e){return Array.isArray(e)||y(),e.map(t$1=>{let n=q$1(t$1);return {id:r(n.id),userId:r(n.userId),providerId:r(n.providerId),accountId:r(n.accountId),scopes:u(n.scopes),createdAt:t(n.createdAt),updatedAt:t(n.updatedAt)}})}function Tn(e){let t=q$1(e);return {url:r(t.url),redirect:s(t.redirect)}}function Pn(e){let t=q$1(e);return {success:s(t.success),message:r(t.message)}}function Fe(e,t){return t===void 0?{}:{[e]:t}}var vn=new Set(["pending","accepted","rejected","canceled"]),ge=1e4;function F(e,t$1,n){let i=q$1(e),o={id:k(i.id),name:k(i.name),slug:k(i.slug),createdAt:t(i.createdAt),...$("logo",v(i,"logo")),...$("metadata",i.metadata===void 0?void 0:A(i.metadata))};return _(o.id,t$1),_(o.slug,n),o}function Ve(e){return M(e,F)}function fe(e,t,n){return e===null?null:(t===null&&y(),F(e,t,n))}function He(e,t,n){if(e===null)return null;let i=q$1(e),o=F(i,t,n);return {...o,members:M(i.members,a=>tt(a,o.id)),invitations:M(i.invitations,a=>N(a,void 0,o.id))}}function Be(e,t){let n=M(e,i=>et(i));return Q(n.map(i=>i.organizationId),t),n}function Ke(e,t,n){return e===null?null:(t===null&&y(),et(e,t,n))}function je(e,t){let n=q$1(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&y(),{members:Cn(n.members,t),total:n.total}}function N(e,t$1,n){let i=q$1(e),o=k(i.status);vn.has(o)||y();let a={id:k(i.id),organizationId:k(i.organizationId),email:Y(i.email),role:k(i.role),status:o,inviterId:k(i.inviterId),expiresAt:t(i.expiresAt),createdAt:t(i.createdAt)};return _(a.id,t$1),_(a.organizationId,n),a}function Je(e,t){let n=M(e,i=>N(i));return Q(n.map(i=>i.organizationId),t),n}function Ge(e){return M(e,t=>{let n=q$1(t);return {...N(n),organizationName:Y(n.organizationName)}})}function We(e,t){let n=q$1(e);return {...N(n,t),organizationName:k(n.organizationName),organizationSlug:k(n.organizationSlug),inviterEmail:nt(n.inviterEmail)}}function Xe(e,t){let n=q$1(e),i=N(n.invitation,t);return {invitation:i,member:q(n.member,void 0,i.organizationId)}}function $e(e,t){let n=q$1(e);return n.member!==null&&y(),{invitation:n.invitation===null?null:N(n.invitation,t),member:null}}function Ye(e,t){return e===null?null:N(e,t)}function Qe(e,t,n){let i=q$1(e);return {member:q(i.member,n,t)}}function q(e,t$1,n){let i=q$1(e),o={id:k(i.id),organizationId:k(i.organizationId),userId:k(i.userId),role:k(i.role),createdAt:t(i.createdAt),...i.user===void 0?{}:{user:it(i.user)}};return _(o.id,t$1),_(o.organizationId,n),o}function Ze(e,t){let n=M(e,i=>{let o=q$1(i);return {organizationId:k(o.organizationId),data:{role:k(o.role),...$("permission",o.permission===void 0?void 0:Dn(o.permission))}}});return Q(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function et(e,t$1,n){let i=q$1(e),o=i.updatedAt,a={id:k(i.id),name:Y(i.name),organizationId:k(i.organizationId),createdAt:t(i.createdAt),...o===void 0?{}:{updatedAt:t(o)}};return _(a.id,t$1),_(a.organizationId,n),a}function tt(e,t){let n=q$1(e);return {...q(n,void 0,t),user:it(n.user)}}function Cn(e,t){let n=M(e,i=>tt(i));return Q(n.map(i=>i.organizationId),t),n}function Dn(e){let t=q$1(e),n={};for(let[i,o]of Object.entries(t))(i==="__proto__"||i==="constructor"||i==="prototype"||i.length===0||i.length>ge||!Array.isArray(o))&&y(),n[i]=o.map(a=>k(a));return n}function k(e){let t=r(e);return (t.length===0||t.length>ge)&&y(),t}function Y(e){if(e==null)return "";let t=r(e);return t.length>ge&&y(),t}function nt(e){return e===null?null:k(e)}function _(e,t){t!==void 0&&e!==t&&y();}function Q(e,t){let n=t??e[0];n!==void 0&&e.some(i=>i!==n)&&y();}function it(e){let t=q$1(e);return {id:k(t.id),name:Y(t.name),email:nt(t.email),...$("image",v(t,"image"))}}function M(e,t){return Array.isArray(e)||y(),e.map(n=>t(n))}function $(e,t){return t===void 0?{}:{[e]:t}}function ot(e,t,n=()=>null){let{post:i,mutation:o}=L(e,t),a=new Map,c=(r,l,u,h)=>{if(u)return e.request(r,{query:l,fetchOptions:u,decode:h});let O=`${r}\0${JSON.stringify(l??null)}`,A=a.get(O);if(A)return A;let s=e.request(r,{query:l,decode:h}).finally(()=>{a.delete(O);});return a.set(O,s),s},p=r=>o(r).finally(()=>a.clear());return {create:(r,l)=>p(i("/organization/create",r,l,F)),list:r=>c("/organization/list",void 0,r,Ve),get:(r={},l)=>c("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},l,u=>He(u,r.organizationId,r.organizationSlug)),setActive:(r,l)=>p(i("/organization/set-active",r,l,u=>fe(u,r.organizationId,r.organizationSlug))),listTeams:(r={},l)=>c("/organization/list-teams",{organizationId:r.organizationId},l,u=>Be(u,r.organizationId)),setActiveTeam:(r,l)=>p(i("/organization/set-active-team",r,l,u=>Ke(u,r.teamId))),update:(r,l)=>p(i("/organization/update",r,l,u=>fe(u,r.organizationId))),delete:(r,l)=>p(i("/organization/delete",r,l,u=>F(u,r.organizationId))),listMembers:(r={},l)=>c("/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},l,u=>je(u,r.organizationId)),inviteMember:(r,l)=>p(i("/organization/invite-member",r,l,u=>N(u,void 0,r.organizationId))),listInvitations:(r={},l)=>c("/organization/list-invitations",{organizationId:r.organizationId},l,u=>Je(u,r.organizationId)),listUserInvitations:r=>c("/organization/list-user-invitations",void 0,r,Ge),getInvitation:(r,l)=>c("/organization/get-invitation",{id:r.id},l,u=>We(u,r.id)),acceptInvitation:(r,l)=>p(i("/organization/accept-invitation",r,l,u=>Xe(u,r.invitationId))),rejectInvitation:(r,l)=>p(i("/organization/reject-invitation",r,l,u=>$e(u,r.invitationId))),cancelInvitation:(r,l)=>p(i("/organization/cancel-invitation",r,l,u=>Ye(u,r.invitationId))),removeMember:(r,l)=>p(i("/organization/remove-member",r,l,u=>Qe(u,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,l)=>p(i("/organization/update-member-role",r,l,u=>q(u,r.memberId,r.organizationId))),leave:(r,l)=>p(i("/organization/leave",r,l,u=>q(u,void 0,r.organizationId))),listRoles:(r={},l)=>c("/organization/list-roles",{organizationId:r.organizationId},l,u=>Ze(u,r.organizationId)),has:r=>E(n(),r),hasPermission:r=>B(n(),r.permission)}}var rt=4096,En=4096,xn=100,zn=256,Nn=16,Un=64,_n=12;function he(e){let t=q$1(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&y(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:St(t.twoFactorMethods,Nn,Un)}}):(t.twoFactorRedirect!==void 0&&y(),{redirect:s(t.redirect),...Vn(t,"url"),user:w(t.user)})}function at(e){let t=q$1(e);return {user:w(t.user)}}function st(e){let t=q$1(e);return {sessionCreated:s(t.sessionCreated),user:w(t.user)}}function ut(e,t){let n=q$1(e),i=s(n.redirect);n.user===null&&y();let o=n.user!==void 0&&n.user!==null,a=n.url!==void 0&&n.url!==null;return i?((o||!a)&&y(),{redirect:true,url:me(n.url,t)}):(o===a&&y(),o?{redirect:false,user:w(n.user)}:{redirect:false,url:me(n.url,t)})}function ct(e,t){let n=q$1(e);return (n.redirect!==true||n.user!==void 0)&&y(),{redirect:true,url:me(n.url,t)}}function dt(e){return {status:s(q$1(e).status)}}function lt(e){return {success:s(q$1(e).success)}}function pt(e){return q$1(e).status!=="pending"&&y(),{status:"pending"}}function gt(e){let t=q$1(e);if(t.kind==="authowl_turnstile")return {kind:"authowl_turnstile"};t.kind!=="akedly_shield_v1_2"&&y();let n=q$1(t.turnstile),i=n.siteKey===null?null:r(n.siteKey);return {kind:"akedly_shield_v1_2",connectionId:r(t.connectionId),challenge:r(t.challenge),difficulty:Mn(t.difficulty),challengeToken:r(t.challengeToken),challengeRequired:s(t.challengeRequired),turnstile:{required:s(n.required),siteKey:i}}}function Mn(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>_n)&&y(),Number(e)}function ft(e){let t=q$1(e);return (t.status!==true||t.sessionCreated!==true)&&y(),{status:true,sessionCreated:true,user:Ln(t.user)}}function Ae(e){return {status:s(q$1(e).status)}}function mt(e){return {status:s(q$1(e).status)}}function ht(e){let t=q$1(e);return {status:s(t.status),user:w(t.user)}}function At(e){return {success:s(q$1(e).success)}}function yt(e){let t=q$1(e);return {totpURI:qn(t.totpURI),backupCodes:kt(t.backupCodes)}}function Ot(e){return {status:s(q$1(e).status)}}function Z(e){return q$1(e).status!==true&&y(),{status:true}}function bt(e){return {status:s(q$1(e).status)}}function wt(e){let t=q$1(e);return t.status!==void 0&&t.status!==true&&y(),{backupCodes:kt(t.backupCodes)}}function Ln(e){let t$1=q$1(e);return {id:V(t$1.id,512),...Hn(t$1,"name",1024),phoneNumber:V(t$1.phoneNumber,64),phoneNumberVerified:s(t$1.phoneNumberVerified),...t$1.createdAt===void 0?{}:{createdAt:t(t$1.createdAt)},...t$1.updatedAt===void 0?{}:{updatedAt:t(t$1.updatedAt)}}}function me(e,t){let n=V(e,rt);/[\u0000-\u0020\u007f]/u.test(n)&&y();let i;try{i=new URL(n);}catch{return y()}return (i.username||i.password)&&y(),i.protocol==="https:"||t&&i.protocol==="http:"&&Fn(i.hostname)?i.href:y()}function Fn(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function qn(e){let t=V(e,En),n;try{n=new URL(t);}catch{return y()}let i=n.searchParams.get("secret");return (n.protocol!=="otpauth:"||n.hostname.toLowerCase()!=="totp"||n.username||n.password||n.hash||i===null||i.length===0||i.length>512||/\s/u.test(i))&&y(),t}function kt(e){return St(e,xn,zn)}function St(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&y();let i=e.map(o=>V(o,n));return i.some(o=>o.trim().length===0)&&y(),new Set(i).size!==i.length&&y(),i}function V(e,t){let n=r(e);return (n.length===0||n.length>t)&&y(),n}function Vn(e,t){let n=e[t];return n==null?{}:{[t]:V(n,rt)}}function Hn(e,t,n){let i=v(e,t);return i===void 0?{}:(i!==null&&i.length>n&&y(),{[t]:i})}var Rt=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),ee=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 te(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||Tt(n,i)||It(i)||Rt.has(i))return {valid:false}}let t=Bn(e);return ye(t)?{valid:true,value:t}:{valid:false}}function ye(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||Tt(o,a)||It(a)||Rt.has(a))return false;n??=a,i=a;}return t>0&&n!==void 0&&i!==void 0&&!ee.has(n)&&!ee.has(i)}function ne(){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 Bn(e){let t=0,n=e.length;for(;t<n;){let i=e.codePointAt(t);if(i===void 0||!ee.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,c=e.codePointAt(a);if(c===void 0||!ee.has(c))break;n=a;}return e.slice(t,n)}function It(e){return e>=0&&e<=31||e>=127&&e<=159}function Tt(e,t){return e.length===1&&t>=55296&&t<=57343}var Ct=12,Dt=5e3,Kn=8,jn=1e3,Jn=16,Pt=512,Et=100,xt=8192,Gn=32768,Oe=1024,vt=256,we=64,Wn=6e5,Xn=/^[A-Za-z0-9_-]+$/u,$n=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,Yn=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,Qn=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,Zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,zt=new Set(["discouraged","preferred","required"]),ei=new Set(["singleDevice","multiDevice"]),Nt=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),Ut=new Set(["hybrid","security-key","client-device"]),ti=new Set(["none","indirect","direct","enterprise"]),ni=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),ii=new Set(["platform","cross-platform"]),oi=new Set(["discouraged","preferred","required"]),ri=new Set([-8,-7,-257]);function _t(e){let t=z(e,Ct,Dt);return {challenge:Jt(t.challenge),...R("timeout",Kt(t.timeout)),...R("rpId",Gt(t.rpId)),...R("allowCredentials",Bt(t.allowCredentials)),...R("userVerification",J(t.userVerification,zt)),...R("hints",ie(t.hints,Ut)),...R("extensions",jt(t.extensions))}}function Mt(e){let t=z(e,Ct,Dt);return {challenge:Jt(t.challenge),rp:ai(t.rp),user:si(t.user),pubKeyCredParams:ui(t.pubKeyCredParams),...R("timeout",Kt(t.timeout)),...R("excludeCredentials",Bt(t.excludeCredentials)),...R("authenticatorSelection",ci(t.authenticatorSelection)),...R("attestation",J(t.attestation,ti)),...R("attestationFormats",ie(t.attestationFormats,ni)),...R("hints",ie(t.hints,Ut)),...R("extensions",jt(t.extensions))}}function Lt(e){let t=q$1(e),n=x$1(t.session),i=w(t.user);return n.userId!==i.id&&y(),{session:n,user:i}}function ke(e){let t$1=q$1(e),n=t$1.counter;(!Number.isSafeInteger(n)||n<0)&&y();let i=Se(t$1.deviceType,ei),o=s(t$1.backedUp);return o&&i!=="multiDevice"&&y(),{id:H(t$1.id,vt),...pi(t$1),publicKey:di(t$1.publicKey,Gn),userId:H(t$1.userId,vt),credentialID:re(t$1.credentialID,xt),counter:n,deviceType:i,backedUp:o,...gi(t$1),createdAt:t(t$1.createdAt),...fi(t$1)}}function Ft(e,t,n){let i=ke(e);return (i.credentialID!==t||(n===void 0?i.name!==void 0&&i.name!==null:i.name!==n))&&y(),i}function qt(e){(!Array.isArray(e)||e.length>Et)&&y();let t=e.map(ke);return oe(t.map(n=>n.id)),oe(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&y(),t}function Vt(e,t,n){let i=q$1(e),o=ke(i.passkey);return (o.id!==t||o.name!==n)&&y(),{passkey:o}}function Ht(e){return q$1(e).status!==true&&y(),{status:true}}function ai(e){let t=q$1(e);return {name:be(t.name,Oe),...R("id",Gt(t.id))}}function si(e){let t=q$1(e);return {id:re(t.id,128,1,64),name:be(t.name,Oe),displayName:be(t.displayName,Oe)}}function ui(e){(!Array.isArray(e)||e.length===0||e.length>we)&&y();let t=e.map(n=>{let i=q$1(n);return (i.type!=="public-key"||!Number.isSafeInteger(i.alg)||!ri.has(i.alg))&&y(),{type:"public-key",alg:i.alg}});return mi(t.map(n=>n.alg)),t}function Bt(e){if(e===void 0)return;(!Array.isArray(e)||e.length>Et)&&y();let t=e.map(n=>{let i=q$1(n);return i.type!=="public-key"&&y(),{type:"public-key",id:re(i.id,xt),...R("transports",ie(i.transports,Nt))}});return oe(t.map(n=>n.id)),t}function ci(e){if(e===void 0)return;let t=q$1(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&y();let n=J(t.residentKey,oi);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&y(),{...R("authenticatorAttachment",J(t.authenticatorAttachment,ii)),...R("residentKey",n),...R("requireResidentKey",t.requireResidentKey),...R("userVerification",J(t.userVerification,zt))}}function Kt(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>Wn)&&y(),e}function jt(e){return e===void 0?void 0:z(e,Kn,jn)}function ie(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>we)&&y();let n=e.map(i=>Se(i,t));return oe(n),n}function J(e,t){if(e!==void 0)return Se(e,t)}function Jt(e){return re(e,Math.ceil(Pt*4/3),Jn,Pt)}function re(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=H(e,t),a=o.length%4,c=li(o.at(-1)??""),p=Math.floor(o.length*3/4);return (!Xn.test(o)||a===1||a===2&&(c&15)!==0||a===3&&(c&3)!==0||p<n||p>i)&&y(),o}function H(e,t){let n=r(e);return (n.length===0||n.length>t)&&y(),n}function be(e,t){let n=H(e,t);return Yn.test(n)&&y(),n}function Gt(e){if(e===void 0)return;let t=H(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!Qn.test(n)))&&y(),t}function di(e,t){let n=H(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",c=Wt(a);return (n.length%4!==0||!$n.test(n)||i&&(c&15)!==0||o&&(c&3)!==0)&&y(),n}function li(e){return Wt(e,true)}function Wt(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function pi(e){let t=v(e,"name");return t===void 0?{}:(t!==null&&!ye(t)&&y(),{name:t})}function gi(e){let t=v(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>we||n.some(i=>!Nt.has(i))||new Set(n).size!==n.length)&&y(),{transports:t}}function fi(e){let t=v(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(Zn.test(t)||y(),{aaguid:t})}function Se(e,t){let n=r(e);return t.has(n)||y(),n}function R(e,t){return t===void 0?{}:{[e]:t}}function oe(e){new Set(e).size!==e.length&&y();}function mi(e){new Set(e).size!==e.length&&y();}function hi(e,t){if(!t)return e;let n=t.catch(()=>{});return n.then(()=>{n=null;}),{async request(i,o){return n&&await n,e.request(i,o)}}}var Xt=new Map;function Ai(e,t,n){let i=Xt.get(n);if(!i){let o=new URLSearchParams(window.location.hash.slice(1)).get("authowl_code");if(!o)return;i=import('./session-handoff-6FBH3GFJ.js').then(a=>a.completeCrossSiteSignIn(e,t,o)),Xt.set(n,i);}return i}function $t(e){return !a()||e.idToken||e.disableRedirect?"legacy":"first-party"}function yi(e,t=()=>{},n=wi){let i=le(e),o=e.session.tokens,a$1=a()?Ai(i,o,e.decoded.projectId):void 0,c=hi(i,a$1),p=Ue({http:c,probe:le({...e,fetch:e.session.probe}),tokens:o,channelName:`authowl:${e.decoded.projectId}`}),r=n(c,p.notifyMutation),l=()=>{p.notifyMutation(),t();},{post:u,mutation:h}=L(c,l),O=e.decoded.env==="test",A=s=>{o.beginSession({remember:s?.rememberMe!==false});};return {sessionStore:p.store,getSession:p.getSession,account:qe(c,l),organization:ot(c,l,()=>p.store.getSnapshot().data?.session.membership??null),signIn:{email:(s,g)=>(A(s),h(u("/sign-in/email",s,g,he),m=>!("twoFactorRedirect"in m))),username:(s,g)=>(A(s),h(u("/sign-in/username",s,g,he),m=>!("twoFactorRedirect"in m))),social:async(s,g)=>{if(A(),$t(s)==="first-party"){let{beginCrossSiteSignIn:I}=await import('./session-handoff-6FBH3GFJ.js'),v=await I(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 m=await h(u("/sign-in/social",s,g,I=>ut(I,O)),I=>"user"in I);return m.error!==null||m.data===null||"url"in m.data&&m.data.redirect&&!s.disableRedirect&&typeof window<"u"&&window.location.assign(m.data.url),m},sso:async(s,g)=>{if($t(s)==="first-party"){let{beginCrossSiteSignIn:I}=await import('./session-handoff-6FBH3GFJ.js'),v=await I(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 m=await u("/sign-in/sso",s,g,I=>ct(I,O));return m.error!==null||m.data===null||typeof window<"u"&&window.location.assign(m.data.url),m},magicLink:(s,g)=>u("/sign-in/magic-link",s,g,dt),emailOtp:(s,g)=>(A(),h(u("/sign-in/email-otp",s,g,at))),passkey:(s,g)=>(A(),r.signIn(s,g))},signUp:{email:(s,g)=>(A(),h(u("/sign-up/email",s,g,st),m=>m.sessionCreated))},emailOtp:{sendVerificationOtp:(s,g)=>u("/email-otp/send-verification-otp",s,g,lt),verifyEmail:(s,g)=>(A(),h(u("/email-otp/verify-email",s,g,ht)))},phoneOtp:{prepare:s=>u("/phone-otp/challenge",{},s,gt),start:(s,g)=>u("/phone-otp/start",{...s,idempotencyKey:s.idempotencyKey??Ne()},g,pt),verify:(s,g)=>(A(),h(u("/phone-otp/verify",s,g,ft)))},requestPasswordReset:(s,g)=>u("/request-password-reset",s,g,Ae),resetPassword:(s,g)=>u("/reset-password",s,g,Ae),sendVerificationEmail:(s,g)=>u("/send-verification-email",s,g,mt),passkey:{addPasskey:(s,g)=>r.add(s,g),listUserPasskeys:()=>c.request("/passkey/list-user-passkeys",{decode:qt}),updatePasskey:async(s,g)=>{let m=te(s.name);if(!m.valid||m.value===void 0)return ne();let I=m.value;return u("/passkey/update-passkey",{...s,name:I},g,v=>Vt(v,s.id,I))},deletePasskey:(s,g)=>u("/passkey/delete-passkey",s,g,Ht)},twoFactor:{enable:(s,g)=>u("/two-factor/enable",s,g,yt),disable:(s,g)=>h(u("/two-factor/disable",s,g,Ot),m=>m.status),verifyTotp:(s,g)=>h(u("/two-factor/verify-totp",s,g,Z)),verifyBackupCode:(s,g)=>h(u("/two-factor/verify-backup-code",s,g,Z)),sendOtp:(s={},g)=>u("/two-factor/send-otp",s,g,bt),verifyOtp:(s,g)=>h(u("/two-factor/verify-otp",s,g,Z)),generateBackupCodes:(s,g)=>u("/two-factor/generate-backup-codes",s,g,wt)},signOut:s=>h(c.request("/sign-out",{method:"POST",body:{},fetchOptions:s,decode:At}).then(g=>(o.endSession(),g)),g=>g.success)}}function mo(e,t=()=>{},n){let i=yi(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:Yt(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:Yt(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function Yt(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return Oi();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?bi():i}}function Oi(){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 bi(){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 wi(){return {signIn:()=>Qt(),add:()=>Qt()}}function Qt(){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 Oo(e,t,n){let i=new Map;return {async signIn(o={},a){let c=await e.request("/passkey/generate-authenticate-options");if(!c.data)return tn(c.error);let p;try{p=_t(c.data);}catch{return Zt()}let r;try{r=await n.authenticate({optionsJSON:p,useBrowserAutofill:o.autoFill});}catch(A){return nn(n,A,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!ki(r))return en();let{clientExtensionResults:l,...u}=r,h=i.get(r.id);if(h)return h;let O=(async()=>{let A=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:u},fetchOptions:a,decode:Lt});return A.data&&t(),A})();i.set(r.id,O);try{return await O}finally{i.get(r.id)===O&&i.delete(r.id);}},async add(o={},a){let c=te(o.name);if(!c.valid)return ne();let p=await e.request("/passkey/generate-register-options",{query:{name:c.value,authenticatorAttachment:o.authenticatorAttachment}});if(!p.data)return tn(p.error);let r;try{r=Mt(p.data);}catch{return Zt()}let l;try{l=await n.register({optionsJSON:r});}catch(A){return nn(n,A,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!Si(l))return en();let{clientExtensionResults:u,...h}=l,O=await e.request("/passkey/verify-registration",{method:"POST",body:{response:h,name:c.value},fetchOptions:a,decode:A=>Ft(A,l.id,c.value)});return O.data&&t(),O}}}function Zt(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function en(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function rn(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 ki(e){if(!rn(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 Si(e){if(!rn(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function tn(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function nn(e,t,n,i){let o=Ii(t,"page does not have focus"),a=e.errorCode?.(t),c=a!==void 0?a==="ERROR_CEREMONY_ABORTED":on(t)==="AbortError",p=n!=="AUTH_CANCELLED",r=Ri(a,on(t),p);return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:o?"PASSKEY_PAGE_NOT_FOCUSED":c?n:a??"PASSKEY_BROWSER_ERROR",message:o?"Keep this page focused while completing the passkey prompt.":c?i:r}}}function Ri(e,t,n){switch(e){case "ERROR_INVALID_DOMAIN":case "ERROR_INVALID_RP_ID":return "Passkeys are not set up for this site\u2019s domain.";case "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED":return "This device already has a passkey for this account.";case "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEY_ALGS":case "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT":case "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT":return "This device cannot create a passkey for this site.";}return t==="NotAllowedError"?n?"No passkey was created. The prompt was dismissed or timed out.":"No passkey was used. This device may not have one saved for this site yet, or the prompt was dismissed.":t==="SecurityError"?"Passkeys are not set up for this site\u2019s domain.":n?"Passkey registration did not complete.":"Passkey sign-in did not complete."}function on(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function Ii(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 So(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return Ee(await X(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>Ti(i,e)}),"public-config")}function Ti(e,t){let n=z(e),i=n.environmentId,o=n.environmentType,a=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!Pi(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==a)throw x();let c=P(n.branding),p=P(n.legal);if(!Re(n.enabledMethods,64)||!Re(n.socialProviders,64)||!sn(c,["appName","logoUrl","primaryColor"])||c.showAppName!==void 0&&typeof c.showAppName!="boolean"||c.alignment!==void 0&&c.alignment!=="left"&&c.alignment!=="center"&&c.alignment!=="right"||c.theme!==void 0&&c.theme!=="light"&&c.theme!=="dark"&&c.theme!=="system"||!sn(p,["termsUrl","privacyUrl"])||!Number.isSafeInteger(p.version)||p.version<0||typeof p.required!="boolean")throw x();if(n.socialProviderClientIds!==void 0){let r=P(n.socialProviderClientIds);if(Object.keys(r).length>64||Object.values(r).some(l=>typeof l!="string"||l.length>2048))throw x()}if(!U(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!an(n.turnstileSiteKey)||!an(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw x();if(n.jwtIssuer!==null){let r=P(n.jwtIssuer);if(r.issuer!==a||r.jwksUrl!==`${a}/jwks`||r.aud!==t.decoded.projectId)throw x()}if(n.signUp!==void 0){let r=P(n.signUp).mode;if(typeof r!="string"||!["open","restricted","allowlist","waitlist"].includes(r))throw x()}if(n.authentication!==void 0&&vi(n.authentication),n.emailVerification!==void 0){let r=P(n.emailVerification);if(!U(r,["required"])||r.method!=="link"&&r.method!=="code")throw x()}if(n.userModel!==void 0&&!U(P(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw x();if(n.mfa!==void 0){let r=P(n.mfa);if(!U(r,["totp","required","backupCodes"])||(r.required===true||r.backupCodes===true)&&r.totp!==true)throw x()}return n}function Pi(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 x(){return new TypeError("public-config returned an invalid response")}function P(e){if(!e||typeof e!="object"||Array.isArray(e))throw x();return e}function an(e){return e===null||typeof e=="string"&&e.length<=4096}function vi(e){let t=P(e),n=P(t.email),i=P(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!U(n,["signUp"])||!Re(n.signIn,3)||n.signIn.some(a=>a!=="password"&&a!=="magic_link"&&a!=="email_otp")||!U(P(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(P(t.passkey),["signIn","add"])||!Ci(P(t.passkey).relyingPartyId)||!U(P(t.username),["collectOnSignUp","signIn"]))throw x()}function Ci(e){return e==null||typeof e=="string"}function U(e,t){return t.every(n=>typeof e[n]=="boolean")}function sn(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function Re(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{Di as a,se as b,X as c,Ee as d,dn as e,le as f,Ne as g,yi as h,mo as i,Oo as j,So as k};