@authowl/core 0.19.0 → 0.21.0

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