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