@authowl/core 0.14.0 → 0.15.1

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,u,s,g,f as f$1,e,q as q$1}from'./chunk-KPXCQZUX.js';export{e as resolveConfig,b as sessionCookieName}from'./chunk-KPXCQZUX.js';var i=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Z=300*1e3,X=5e3,Q=64*1024,ee=64,te=60*1e3,C=new Map,D=new Map;function L(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4===0?t:t+"=".repeat(4-t.length%4),n=typeof atob=="function"?atob(r):globalThis.Buffer.from(r,"base64").toString("binary"),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}function W(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(L(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof i?t:new i("Malformed JWT segment.","TOKEN_MALFORMED")}}function V(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function q(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&L(e).byteLength===32}function re(e){if(!V(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)||!q(e.x)||!q(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 ne(e){if(!V(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>ee)throw new i("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(re),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 J(e,t){let r=C.get(e);if(!t&&r&&Date.now()-r.fetchedAt<Z)return r.keys;try{let n=await g({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:X,maxResponseBytes:Q,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>q$1(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=ne(n.data);return C.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof f$1)switch(n.kind){case "timeout":throw new i("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new i("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new i("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new i("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function se(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await J(e,false));if(!n){let s=D.get(e)??0;Date.now()-s>=te&&(D.set(e,Date.now()),n=r(await J(e,true)));}if(!n)throw new i("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function oe(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 ie(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function ae(e){let t=e.membership;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,n=typeof r.role=="string"?r.role:"",s=Array.isArray(r.permissions)?r.permissions.filter(a=>typeof a=="string"):[],o=Array.isArray(r.teams)?r.teams.filter(a=>typeof a=="string"):void 0;return n===""&&s.length===0&&!o?.length?null:{role:n,permissions:s,...o===void 0?{}:{teams:o}}}async function pe(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=W(n);if(a.alg!=="ES256")throw new i("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await se(t.jwksUri,typeof a.kid=="string"?a.kid:void 0),c;try{c=await oe(p);}catch(S){throw S instanceof i?S:new i("JWKS key could not be imported.","JWKS_KEY_INVALID")}let m;try{if(!/^[A-Za-z0-9_-]{86}$/.test(o))throw new Error("invalid signature encoding");if(m=L(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new i("Malformed JWT signature.","TOKEN_MALFORMED")}let g=new TextEncoder().encode(`${n}.${s}`),l;try{l=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},c,m,g);}catch{throw new i("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!l)throw new i("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let d=W(s),y=t.clockToleranceSeconds??60,b=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+y<b)throw new i("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof d.nbf=="number"&&d.nbf-y>b)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(!ie(d.aud,t.audience))throw new i("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof d.sub=="string"?d.sub:null,membership:ae(d),claims:d}}var de="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",A={getOpenApiDocument:{method:"GET",path:"/openapi.json",successStatuses:[200],responseSchemas:{200:{type:"object"}}},listUsers:{method:"GET",path:"/users",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserPage"}}},createUser:{method:"POST",path:"/users",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/User"}}},startUserExport:{method:"POST",path:"/users/export",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getUserExport:{method:"GET",path:"/users/export/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadUserExport:{method:"GET",path:"/users/export/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},startPasswordHashUserExport:{method:"POST",path:"/users/export/hashes",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},dryRunUserImport:{method:"POST",path:"/imports/dry-run",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportDryRun"}}},createUserImport:{method:"POST",path:"/imports",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportBatch"}}},getUserImport:{method:"GET",path:"/imports/{importId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ImportBatch"}}},downloadUserImportReport:{method:"GET",path:"/imports/{importId}/report",successStatuses:[200],responseSchemas:{200:null}},getUser:{method:"GET",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},updateUser:{method:"PATCH",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},deleteUser:{method:"DELETE",path:"/users/{userId}",successStatuses:[204],responseSchemas:{204:null}},listUserSessions:{method:"GET",path:"/users/{userId}/sessions",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionPage"}}},revokeUserSessions:{method:"DELETE",path:"/users/{userId}/sessions",successStatuses:[204],responseSchemas:{204:null}},updateUserMetadata:{method:"PATCH",path:"/users/{userId}/metadata",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserMetadata"}}},verifySession:{method:"POST",path:"/sessions/verify",successStatuses:[200],responseSchemas:{200:{type:"object",required:["user","session"],properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}},getSession:{method:"GET",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Session"}}},updateSessionMetadata:{method:"PATCH",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionMetadata"}}},revokeSession:{method:"DELETE",path:"/sessions/{sessionId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizations:{method:"GET",path:"/organizations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationPage"}}},createOrganization:{method:"POST",path:"/organizations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Organization"}}},getOrganization:{method:"GET",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},updateOrganization:{method:"PATCH",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},deleteOrganization:{method:"DELETE",path:"/organizations/{organizationId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationMembers:{method:"GET",path:"/organizations/{organizationId}/members",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MemberPage"}}},addOrganizationMember:{method:"POST",path:"/organizations/{organizationId}/members",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationMember"}}},updateOrganizationMember:{method:"PATCH",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationMember"}}},removeOrganizationMember:{method:"DELETE",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationRoles:{method:"GET",path:"/organizations/{organizationId}/roles",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/RolePage"}}},createOrganizationRole:{method:"POST",path:"/organizations/{organizationId}/roles",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationRole"}}},updateOrganizationRole:{method:"PATCH",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationRole"}}},deleteOrganizationRole:{method:"DELETE",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[204],responseSchemas:{204:null}},listInvitations:{method:"GET",path:"/invitations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/InvitationPage"}}},createInvitation:{method:"POST",path:"/invitations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Invitation"}}},getInvitation:{method:"GET",path:"/invitations/{invitationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Invitation"}}},revokeInvitation:{method:"DELETE",path:"/invitations/{invitationId}",successStatuses:[204],responseSchemas:{204:null}},listMessages:{method:"GET",path:"/messages",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MessagePage"}}},sendMessage:{method:"POST",path:"/messages",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/Message"}}},getMessage:{method:"GET",path:"/messages/{messageId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Message"}}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},v={Problem:{type:"object",required:["type","title","status","detail","instance","code"],properties:{type:{type:"string",format:"uri"},title:{type:"string"},status:{type:"integer"},detail:{type:"string"},instance:{type:"string",format:"uri"},code:{type:"string"}},additionalProperties:true},User:{type:"object",required:["id","email","phone","name","image","email_verified","banned","public_metadata","private_metadata","unsafe_metadata","metadata_version","created_at","updated_at"],properties:{id:{type:"string"},email:{type:"string",format:"email"},phone:{type:["string","null"]},name:{type:["string","null"]},image:{type:["string","null"],format:"uri"},email_verified:{type:"boolean"},banned:{type:"boolean"},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateUser:{type:"object",required:["email"],properties:{email:{type:"string",format:"email",maxLength:320},password:{type:"string",minLength:8,maxLength:128},name:{type:"string",minLength:1,maxLength:200},phone:{type:"string",minLength:1,maxLength:32}},additionalProperties:false},UpdateUser:{type:"object",minProperties:1,properties:{email:{type:"string",format:"email",maxLength:320},name:{type:["string","null"],minLength:1,maxLength:200},phone:{type:["string","null"],minLength:1,maxLength:32},banned:{type:"boolean"}},additionalProperties:false},ImportDryRun:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","errors","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"dry_run"},status:{type:"string",const:"validated"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},errors:{type:"array",maxItems:100,items:{type:"object",required:["line","code","path","message"],properties:{line:{type:"integer",minimum:2},code:{type:"string",enum:["INVALID_JSON","UNEXPECTED_RECORD","INVALID_USER","DUPLICATE_EXTERNAL_ID"]},path:{type:["string","null"]},message:{type:"string"}},additionalProperties:false}},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},ImportBatch:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","report_expires_at","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"commit"},status:{type:"string",const:"completed"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid","created","updated","unchanged","failed"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4},created:{type:"integer",minimum:0,maximum:1e4},updated:{type:"integer",minimum:0,maximum:1e4},unchanged:{type:"integer",minimum:0,maximum:1e4},failed:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},report_expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},MetadataObject:{type:"object",maxProperties:100,description:"JSON metadata object. Reserved prototype keys and the authowl_ prefix are rejected at every depth. Encoded object size is limited to 8192 bytes.",additionalProperties:true},UserMetadata:{type:"object",required:["public_metadata","private_metadata","unsafe_metadata","metadata_version"],properties:{public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateUserMetadata:{type:"object",required:["expected_version"],minProperties:2,properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Session:{type:"object",required:["id","user_id","expires_at","created_at","metadata","metadata_version"],properties:{id:{type:"string"},user_id:{type:"string"},expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},ip_address:{type:["string","null"]},user_agent:{type:["string","null"]},metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},SessionMetadata:{type:"object",required:["metadata","metadata_version"],properties:{metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateSessionMetadata:{type:"object",required:["expected_version","metadata"],properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Organization:{type:"object",required:["id","name","slug","created_at"],properties:{id:{type:"string"},name:{type:"string"},slug:{type:"string"},logo:{type:["string","null"],format:"uri"},metadata:{type:["object","null"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateOrganization:{type:"object",required:["name","slug"],properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:"string",format:"uri",maxLength:2048},metadata:{type:"object"}},additionalProperties:false},UpdateOrganization:{type:"object",minProperties:1,properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:["string","null"],format:"uri",maxLength:2048},metadata:{type:["object","null"]}},additionalProperties:false},OrganizationMember:{type:"object",required:["organization_id","user_id","role","created_at"],properties:{organization_id:{type:"string"},user_id:{type:"string"},role:{type:"string"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},AddMember:{type:"object",required:["user_id","role"],properties:{user_id:{type:"string"},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},OrganizationRole:{type:"object",required:["id","organization_id","name","permissions"],properties:{id:{type:"string"},organization_id:{type:"string"},name:{type:"string"},permissions:{type:"array",items:{$ref:"#/components/schemas/OrganizationPermissionId"}}},additionalProperties:false},OrganizationPermissionId:{type:"string",enum:["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","team:create","team:update","team:delete","ac:create","ac:read","ac:update","ac:delete"]},RoleInput:{type:"object",required:["name","permissions"],properties:{name:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9_-]*$"},permissions:{type:"array",maxItems:100,items:{$ref:"#/components/schemas/OrganizationPermissionId"},uniqueItems:true}},additionalProperties:false},Invitation:{type:"object",required:["id","organization_id","email","role","status","expires_at"],properties:{id:{type:"string"},organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100},status:{type:"string"},expires_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateInvitation:{type:"object",required:["organization_id","email","role"],properties:{organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},Event:{type:"object",required:["id","type","status","created_at"],properties:{id:{type:"string"},type:{type:"string"},status:{type:"string"},user_id:{type:["string","null"]},metadata:{type:"object"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},StatsOverview:{type:"object",required:["users_total","monthly_active_users","recent_sign_ins"],properties:{users_total:{type:"integer",minimum:0},monthly_active_users:{type:"integer",minimum:0},recent_sign_ins:{type:"integer",minimum:0}},additionalProperties:false},WebhookInput:{type:"object",required:["url","events"],properties:{url:{type:"string",format:"uri",maxLength:2048},description:{type:"string",maxLength:500},events:{type:"array",minItems:1,maxItems:20,items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"},uniqueItems:true}},additionalProperties:false},SendMessage:{type:"object",required:["to","template","variables"],properties:{to:{type:"string",minLength:7,maxLength:32},channel:{type:"string",enum:["sms","whatsapp","auto"],description:"Defaults to auto."},purpose:{type:"string",enum:["transactional"],description:"Defaults to transactional."},template:{type:"string",pattern:"^[a-z][a-z0-9_]{0,63}$"},locale:{type:"string",enum:["en","ar"],description:"Defaults to en."},variables:{type:"object",maxProperties:50,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_]{0,63}$"},additionalProperties:{type:"string",maxLength:1024}},customerReference:{type:"string",minLength:1,maxLength:255}},additionalProperties:false},MessageState:{type:"string",enum:["preparing","queued","accepted","skipped","delivered","failed","unknown","canceled"]},Message:{type:"object",required:["id","state","purpose","requested_channel","actual_channel","customer_reference","masked_recipient","sms","billing","failure","created_at","updated_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},state:{$ref:"#/components/schemas/MessageState"},purpose:{type:"string",enum:["transactional","auth_otp"]},requested_channel:{type:"string",enum:["sms","whatsapp","auto"]},actual_channel:{type:["string","null"],enum:["sms","whatsapp",null]},customer_reference:{type:["string","null"]},masked_recipient:{type:"string"},sms:{oneOf:[{type:"null"},{type:"object",required:["encoding","segments"],properties:{encoding:{type:["string","null"],enum:["gsm7","ucs2",null]},segments:{type:["integer","null"],minimum:1}},additionalProperties:false}]},billing:{type:"object",required:["credential_mode","unit","units","charged_piasters","reserved_piasters"],properties:{credential_mode:{type:"string",enum:["managed","byok"]},unit:{type:["string","null"]},units:{type:["integer","null"]},charged_piasters:{type:"integer",minimum:0},reserved_piasters:{type:"integer",minimum:0}},additionalProperties:false},failure:{oneOf:[{type:"null"},{type:"object",required:["code","retryable"],properties:{code:{type:"string"},retryable:{type:"boolean"}},additionalProperties:false}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},WebhookSubscriptionEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed"]},WebhookEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed","webhook.test"]},WebhookEndpoint:{type:"object",required:["id","url","events","status","created_at","updated_at"],properties:{id:{type:"string",format:"uuid"},url:{type:"string",format:"uri"},description:{type:["string","null"]},events:{type:"array",items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"}},status:{type:"string",enum:["active","paused","auto_paused"]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookSecret:{type:"object",required:["secret","overlap_expires_at"],properties:{secret:{type:"string"},overlap_expires_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookWithSecret:{type:"object",required:["endpoint","secret"],properties:{endpoint:{$ref:"#/components/schemas/WebhookEndpoint"},secret:{type:"string"}},additionalProperties:false},WebhookDelivery:{type:"object",required:["id","event_id","attempt_id","attempt_number","webhook_id","event_type","status","response_status","response_body","error_code","created_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},event_id:{type:"string",format:"uuid"},attempt_id:{type:"string",format:"uuid"},attempt_number:{type:"integer",minimum:1},webhook_id:{type:"string",format:"uuid"},event_type:{$ref:"#/components/schemas/WebhookEventType"},status:{type:"string",enum:["queued","delivering","succeeded","failed"]},response_status:{type:["integer","null"]},response_body:{type:["string","null"]},error_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},ExportJob:{type:"object",required:["id","format","status","includes_password_hashes","total_rows","artifact_bytes","failure_code","created_at","completed_at","expires_at","download_url"],properties:{id:{type:"string",format:"uuid"},format:{type:"string",enum:["ndjson","csv"]},status:{type:"string",enum:["pending","processing","completed","failed"]},includes_password_hashes:{type:"boolean"},total_rows:{type:"integer",minimum:0},artifact_bytes:{type:"integer",minimum:0},failure_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},completed_at:{type:["string","null"],format:"date-time"},expires_at:{type:["string","null"],format:"date-time"},download_url:{type:["string","null"]}},additionalProperties:false},ExportRequest:{type:"object",properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"}},additionalProperties:false},HashExportRequest:{type:"object",required:["approval_token"],properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"},approval_token:{type:"string",minLength:1,maxLength:256}},additionalProperties:false},Page:{type:"object",required:["data","next_cursor"],properties:{data:{type:"array"},next_cursor:{type:["string","null"]}},additionalProperties:false},UserPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/User"}}}}]},SessionPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}]},OrganizationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}]},MemberPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationMember"}}}}]},RolePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationRole"}}}}]},InvitationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Invitation"}}}}]},EventPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Event"}}}}]},WebhookPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookEndpoint"}}}}]},DeliveryPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookDelivery"}}}}]},MessagePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Message"}}}}]}};var ce=new Set(["__proto__","constructor","prototype"]),me=64,ue=5e4;function B(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 f(r,h(o),0,a)||P(),r}function f(e,t,r,n){if(n.nodes+=1,r>me||n.nodes>ue)return false;if(typeof t.$ref=="string"){let o=_e(t.$ref);if(o===null||!f(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>f(e,h(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>f(e,h(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=>le(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?fe(e,t):typeof e=="number"?he(e,t):Array.isArray(e)?ge(e,t,r,n):E(e)?be(e,t,r,n):typeof e=="boolean"}function le(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 fe(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!ye(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 ye(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 he(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function ge(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=h(t.items);return e.every(o=>f(o,s,r+1,n))}function be(e,t,r,n){let s=Object.keys(e);if(s.some(a=>ce.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=>!f(a,h(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(!f(p,h(c),r+1,n))return false;continue}if(t.additionalProperties===false||E(t.additionalProperties)&&!f(p,t.additionalProperties,r+1,n))return false}return true}function _e(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(v,r)?h(v[r]):null}function h(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 Se=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,we=1024*1024,Ae=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 Ee(e){Oe();let t=Ie(e?.secretKey),r=Te(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=async(a,p)=>{let c=p??{},m=A[a],g$1=new URL(ke(m.path,c).replace(/^\/+/,""),r);Pe(g$1,c);let l=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});xe(l,c);let d="body"in c?JSON.stringify(c.body):void 0;d!==void 0&&l.set("content-type","application/json");let y;try{y=await g({fetchImpl:n,url:g$1,init:{method:m.method,headers:l,body:d,signal:p?.signal},timeoutMs:Ae,maxResponseBytes:we,allowHttpLoopback:r.protocol==="http:",decode:(u,G)=>B(a,G.status,u)});}catch(u){throw u instanceof O?u:u instanceof f$1?new _(u.kind,u.requestId):new _("network")}let{response:b,requestId:S,data:R}=y;if(!b.ok)throw je(b,R,S);if(!m.successStatuses.some(u=>u===b.status))throw new _("invalid_response",S);return R},o=Object.assign(Object.create(null),{request:s});for(let a of Object.keys(A))o[a]=p=>s(a,p);return Object.freeze(o)}function Oe(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function Ie(e){if(typeof e!="string"||!Se.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function Te(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 ke(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 Pe(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 xe(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 je(e,t,r){let n=r??H(e.headers.get("x-request-id"),256),s=H(e.headers.get("retry-after"),128),o=Le(e.status,n),a=ve(t)?t:o;return new O({status:e.status,code:a.code,requestId:n,problem:a,retryAfter:s})}function Le(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 ve(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 H(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var Ne=/^v1=([a-f0-9]{64})$/i,Re=/^whsec_[A-Za-z0-9_-]{1,256}$/,ze=/^(0|[1-9]\d{0,10})$/;async function Ke(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=Ue(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=Me(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!ze.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let a=$e(e.signatureHeader);if(a.length===0)return false;let p=new TextEncoder().encode(`${e.timestamp}.`),c=new Uint8Array(p.byteLength+s.byteLength);c.set(p),c.set(s,p.byteLength);let m=false;for(let g of t){let l=await crypto.subtle.importKey("raw",new TextEncoder().encode(g),{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=new Uint8Array(await crypto.subtle.sign("HMAC",l,c));for(let y of a)m=De(d,y)||m;}return m}function Ue(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!Re.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function $e(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=Ne.exec(n.trim());s&&r.push(Ce(s[1]));}return r}function Me(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 Ce(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 De(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 F=["publishableKey","apiUrl","issuer","jwksUri","audience"],We=new Set([...F,"clockToleranceSeconds"]);function N(e$1){if(e$1!==void 0&&(!e$1||typeof e$1!="object"))throw new Error("AuthOwl token verification config must be an object.");if(e$1&&Object.keys(e$1).some(p=>!We.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(F.filter(p=>Object.prototype.hasOwnProperty.call(e$1??{},p))),r=t.has("publishableKey")||t.has("apiUrl"),n=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n){if(typeof e$1?.issuer!="string"||typeof e$1.jwksUri!="string"||typeof e$1.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return k({issuer:e$1.issuer,jwksUri:e$1.jwksUri,audience:e$1.audience,clockToleranceSeconds:e$1.clockToleranceSeconds})}let s,o;if(r){if(typeof e$1?.publishableKey!="string"||typeof e$1.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e$1.publishableKey,o=e$1.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=e({publishableKey:s,apiUrl:o});return k({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e$1?.clockToleranceSeconds},a.decoded.env==="test")}async function ot(e,t){return w(e,N(t))}async function it(e,t,r){let n=N(r);try{let s=await w(e,n);return u(s.membership,t)}catch{return false}}async function at(e,t,r){let n=N(r);try{let s$1=await w(e,n);return s(s$1.membership,t.permission)}catch{return false}}export{de as ADMIN_API_SPEC_SHA256,O as AuthOwlAdminApiError,_ as AuthOwlAdminNetworkError,i as TokenVerificationError,Ee as createAdminClient,it as has,at as hasPermission,pe as verifyProjectToken,ot as verifyToken,Ke as verifyWebhook};
1
+ import {d,c,v as v$1,t,h,g as g$1,f,r}from'./chunk-RRP2XNYV.js';export{f as resolveConfig,b as sessionCookieName}from'./chunk-RRP2XNYV.js';var i=class extends Error{code;constructor(t,r="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=r;}},Q=300*1e3,ee=5e3,te=64*1024,re=64,ne=60*1e3,D=new Map,W=new Map;function L(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4===0?t:t+"=".repeat(4-t.length%4),n=typeof atob=="function"?atob(r):globalThis.Buffer.from(r,"base64").toString("binary"),s=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)s[o]=n.charCodeAt(o);return s}function q(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(L(e)),r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");return r}catch(t){throw t instanceof i?t:new i("Malformed JWT segment.","TOKEN_MALFORMED")}}function B(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function J(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&L(e).byteLength===32}function se(e){if(!B(e))throw new i("JWKS contains a non-object key.","JWKS_KEY_INVALID");let t=new Set(["alg","crv","kid","kty","use","x","y"]),r=["d","p","q","dp","dq","qi","k","oth"];if("key_ops"in e||r.some(n=>n in e)||Object.keys(e).some(n=>!t.has(n)))throw new i("JWKS contains private, key_ops, or unexpected key members.","JWKS_KEY_INVALID");if(e.kty!=="EC"||e.crv!=="P-256"||e.alg!=="ES256"||e.use!=="sig"||typeof e.kid!="string"||e.kid.length===0||e.kid.length>128||!/^[A-Za-z0-9_-]+$/.test(e.kid)||!J(e.x)||!J(e.y))throw new i("JWKS contains a key outside the AuthOwl ES256 public-key schema.","JWKS_KEY_INVALID");return {alg:e.alg,crv:e.crv,kid:e.kid,kty:e.kty,use:e.use,x:e.x,y:e.y}}function oe(e){if(!B(e)||Object.keys(e).length!==1||!Array.isArray(e.keys))throw new i("JWKS response must be an object containing only a keys array.","JWKS_DOCUMENT_INVALID");if(e.keys.length>re)throw new i("JWKS response exceeds the 64-key limit.","JWKS_TOO_MANY_KEYS");let t=e.keys.map(se),r=new Set;for(let n of t){if(r.has(n.kid))throw new i("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");r.add(n.kid);}return t}async function V(e,t){let r$1=D.get(e);if(!t&&r$1&&Date.now()-r$1.fetchedAt<Q)return r$1.keys;try{let n=await h({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:ee,maxResponseBytes:te,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>r(o)});if(!n.response.ok)throw new i(`JWKS fetch returned ${n.response.status}.`,"JWKS_HTTP_ERROR");let s=oe(n.data);return D.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(n){if(n instanceof i)throw n;if(n instanceof g$1)switch(n.kind){case "timeout":throw new i("JWKS fetch timed out.","JWKS_FETCH_TIMEOUT");case "response_too_large":throw new i("JWKS response exceeds the 64 KiB limit.","JWKS_RESPONSE_TOO_LARGE");case "invalid_response":throw new i("JWKS response is invalid.","JWKS_DOCUMENT_INVALID");}throw new i("Failed to fetch JWKS.","JWKS_FETCH_FAILED")}}async function ie(e,t){let r=s=>t?s.find(o=>o.kid===t):s[0],n=r(await V(e,false));if(!n){let s=W.get(e)??0;Date.now()-s>=ne&&(W.set(e,Date.now()),n=r(await V(e,true)));}if(!n)throw new i("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return n}function ae(e){let t=globalThis.crypto?.subtle;if(!t)throw new i("WebCrypto is unavailable in this runtime.","WEBCRYPTO_UNAVAILABLE");return t.importKey("jwk",{kty:e.kty,crv:e.crv,x:e.x,y:e.y},{name:"ECDSA",namedCurve:"P-256"},false,["verify"])}function pe(e,t){return typeof e=="string"?e===t:Array.isArray(e)?e.includes(t):false}function de(e){let t=e.membership;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,n=typeof r.role=="string"?r.role:"",s=Array.isArray(r.permissions)?r.permissions.filter(a=>typeof a=="string"):[],o=Array.isArray(r.teams)?r.teams.filter(a=>typeof a=="string"):void 0;return n===""&&s.length===0&&!o?.length?null:{role:n,permissions:s,...o===void 0?{}:{teams:o}}}async function ce(e,t){return w(e,k(t))}function k(e,t=false){if(!e||typeof e!="object")throw new i("Token verification options are required.","TOKEN_CONFIG_INVALID");let r;try{r=d(e.issuer,e.jwksUri,{allowHttpLoopback:t});}catch{throw new i("Token verifier issuer or JWKS URL is invalid.","TOKEN_CONFIG_INVALID")}if(typeof e.audience!="string"||e.audience.length===0||e.audience.length>256)throw new i("Token verifier audience is invalid.","TOKEN_CONFIG_INVALID");if(e.clockToleranceSeconds!==void 0&&(!Number.isInteger(e.clockToleranceSeconds)||e.clockToleranceSeconds<0||e.clockToleranceSeconds>300))throw new i("clockToleranceSeconds must be an integer from 0 through 300.","TOKEN_CONFIG_INVALID");return {...e,...r}}async function w(e,t){if(typeof e!="string"||e.length===0)throw new i("A token string is required.","TOKEN_MALFORMED");let r=e.split(".");if(r.length!==3)throw new i("Malformed JWT.","TOKEN_MALFORMED");let[n,s,o]=r,a=q(n);if(a.alg!=="ES256")throw new i("Unsupported JWT algorithm.","TOKEN_ALGORITHM_UNSUPPORTED");let p=await ie(t.jwksUri,typeof a.kid=="string"?a.kid:void 0),c;try{c=await ae(p);}catch(b){throw b instanceof i?b:new i("JWKS key could not be imported.","JWKS_KEY_INVALID")}let m;try{if(!/^[A-Za-z0-9_-]{86}$/.test(o))throw new Error("invalid signature encoding");if(m=L(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new i("Malformed JWT signature.","TOKEN_MALFORMED")}let f=new TextEncoder().encode(`${n}.${s}`),y;try{y=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},c,m,f);}catch{throw new i("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!y)throw new i("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let d=q(s),h=t.clockToleranceSeconds??60,S=Math.floor(Date.now()/1e3);if(typeof d.exp!="number")throw new i("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(d.exp+h<S)throw new i("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof d.nbf=="number"&&d.nbf-h>S)throw new i("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof d.iss!="string"||d.iss!==t.issuer)throw new i("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!pe(d.aud,t.audience))throw new i("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof d.sub=="string"?d.sub:null,membership:de(d),claims:d}}var me="3e6f30e32508bbe3d398e6add18d0cf88776b1da5bbc1535570999fc994f8d4d",A={getOpenApiDocument:{method:"GET",path:"/openapi.json",successStatuses:[200],responseSchemas:{200:{type:"object"}}},listUsers:{method:"GET",path:"/users",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserPage"}}},createUser:{method:"POST",path:"/users",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/User"}}},startUserExport:{method:"POST",path:"/users/export",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getUserExport:{method:"GET",path:"/users/export/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadUserExport:{method:"GET",path:"/users/export/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},startPasswordHashUserExport:{method:"POST",path:"/users/export/hashes",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/ExportJob"}}},getPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ExportJob"}}},downloadPasswordHashUserExport:{method:"GET",path:"/users/export/hashes/{exportId}/download",successStatuses:[200],responseSchemas:{200:null}},dryRunUserImport:{method:"POST",path:"/imports/dry-run",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportDryRun"}}},createUserImport:{method:"POST",path:"/imports",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/ImportBatch"}}},getUserImport:{method:"GET",path:"/imports/{importId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/ImportBatch"}}},downloadUserImportReport:{method:"GET",path:"/imports/{importId}/report",successStatuses:[200],responseSchemas:{200:null}},getUser:{method:"GET",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},updateUser:{method:"PATCH",path:"/users/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/User"}}},deleteUser:{method:"DELETE",path:"/users/{userId}",successStatuses:[204],responseSchemas:{204:null}},listUserSessions:{method:"GET",path:"/users/{userId}/sessions",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionPage"}}},revokeUserSessions:{method:"DELETE",path:"/users/{userId}/sessions",successStatuses:[204],responseSchemas:{204:null}},updateUserMetadata:{method:"PATCH",path:"/users/{userId}/metadata",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/UserMetadata"}}},verifySession:{method:"POST",path:"/sessions/verify",successStatuses:[200],responseSchemas:{200:{type:"object",required:["user","session"],properties:{user:{$ref:"#/components/schemas/User"},session:{$ref:"#/components/schemas/Session"}}}}},getSession:{method:"GET",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Session"}}},updateSessionMetadata:{method:"PATCH",path:"/sessions/{sessionId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/SessionMetadata"}}},revokeSession:{method:"DELETE",path:"/sessions/{sessionId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizations:{method:"GET",path:"/organizations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationPage"}}},createOrganization:{method:"POST",path:"/organizations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Organization"}}},getOrganization:{method:"GET",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},updateOrganization:{method:"PATCH",path:"/organizations/{organizationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Organization"}}},deleteOrganization:{method:"DELETE",path:"/organizations/{organizationId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationMembers:{method:"GET",path:"/organizations/{organizationId}/members",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MemberPage"}}},addOrganizationMember:{method:"POST",path:"/organizations/{organizationId}/members",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationMember"}}},updateOrganizationMember:{method:"PATCH",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationMember"}}},removeOrganizationMember:{method:"DELETE",path:"/organizations/{organizationId}/members/{userId}",successStatuses:[204],responseSchemas:{204:null}},listOrganizationRoles:{method:"GET",path:"/organizations/{organizationId}/roles",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/RolePage"}}},createOrganizationRole:{method:"POST",path:"/organizations/{organizationId}/roles",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/OrganizationRole"}}},updateOrganizationRole:{method:"PATCH",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/OrganizationRole"}}},deleteOrganizationRole:{method:"DELETE",path:"/organizations/{organizationId}/roles/{roleId}",successStatuses:[204],responseSchemas:{204:null}},listInvitations:{method:"GET",path:"/invitations",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/InvitationPage"}}},createInvitation:{method:"POST",path:"/invitations",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/Invitation"}}},getInvitation:{method:"GET",path:"/invitations/{invitationId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Invitation"}}},revokeInvitation:{method:"DELETE",path:"/invitations/{invitationId}",successStatuses:[204],responseSchemas:{204:null}},listMessages:{method:"GET",path:"/messages",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/MessagePage"}}},sendMessage:{method:"POST",path:"/messages",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/Message"}}},getMessage:{method:"GET",path:"/messages/{messageId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/Message"}}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},v={Problem:{type:"object",required:["type","title","status","detail","instance","code"],properties:{type:{type:"string",format:"uri"},title:{type:"string"},status:{type:"integer"},detail:{type:"string"},instance:{type:"string",format:"uri"},code:{type:"string"}},additionalProperties:true},User:{type:"object",required:["id","email","phone","name","image","email_verified","banned","public_metadata","private_metadata","unsafe_metadata","metadata_version","created_at","updated_at"],properties:{id:{type:"string"},email:{type:"string",format:"email"},phone:{type:["string","null"]},name:{type:["string","null"]},image:{type:["string","null"],format:"uri"},email_verified:{type:"boolean"},banned:{type:"boolean"},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateUser:{type:"object",required:["email"],properties:{email:{type:"string",format:"email",maxLength:320},password:{type:"string",minLength:8,maxLength:128},name:{type:"string",minLength:1,maxLength:200},phone:{type:"string",minLength:1,maxLength:32}},additionalProperties:false},UpdateUser:{type:"object",minProperties:1,properties:{email:{type:"string",format:"email",maxLength:320},name:{type:["string","null"],minLength:1,maxLength:200},phone:{type:["string","null"],minLength:1,maxLength:32},banned:{type:"boolean"}},additionalProperties:false},ImportDryRun:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","errors","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"dry_run"},status:{type:"string",const:"validated"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},errors:{type:"array",maxItems:100,items:{type:"object",required:["line","code","path","message"],properties:{line:{type:"integer",minimum:2},code:{type:"string",enum:["INVALID_JSON","UNEXPECTED_RECORD","INVALID_USER","DUPLICATE_EXTERNAL_ID"]},path:{type:["string","null"]},message:{type:"string"}},additionalProperties:false}},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},ImportBatch:{type:"object",required:["id","mode","status","schema_version","source","counts","bytes_received","errors_truncated","report_expires_at","created_at","completed_at"],properties:{id:{type:"string",format:"uuid"},mode:{type:"string",const:"commit"},status:{type:"string",const:"completed"},schema_version:{type:"string",const:"authowl.user-import.v1"},source:{type:"object",required:["provider","namespace","version"],properties:{provider:{type:"string",enum:["clerk","auth0","firebase","supabase","authowl","custom"]},namespace:{type:"string",minLength:1,maxLength:512,pattern:"^[A-Za-z0-9][A-Za-z0-9._:/-]*$"},version:{type:["string","null"],maxLength:100}},additionalProperties:false},counts:{type:"object",required:["total","valid","invalid","created","updated","unchanged","failed"],properties:{total:{type:"integer",minimum:1,maximum:1e4},valid:{type:"integer",minimum:0,maximum:1e4},invalid:{type:"integer",minimum:0,maximum:1e4},created:{type:"integer",minimum:0,maximum:1e4},updated:{type:"integer",minimum:0,maximum:1e4},unchanged:{type:"integer",minimum:0,maximum:1e4},failed:{type:"integer",minimum:0,maximum:1e4}},additionalProperties:false},bytes_received:{type:"integer",minimum:1,maximum:67108864},errors_truncated:{type:"boolean"},report_expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},completed_at:{type:"string",format:"date-time"}},additionalProperties:false},MetadataObject:{type:"object",maxProperties:100,description:"JSON metadata object. Reserved prototype keys and the authowl_ prefix are rejected at every depth. Encoded object size is limited to 8192 bytes.",additionalProperties:true},UserMetadata:{type:"object",required:["public_metadata","private_metadata","unsafe_metadata","metadata_version"],properties:{public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateUserMetadata:{type:"object",required:["expected_version"],minProperties:2,properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Session:{type:"object",required:["id","user_id","expires_at","created_at","metadata","metadata_version"],properties:{id:{type:"string"},user_id:{type:"string"},expires_at:{type:"string",format:"date-time"},created_at:{type:"string",format:"date-time"},ip_address:{type:["string","null"]},user_agent:{type:["string","null"]},metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},SessionMetadata:{type:"object",required:["metadata","metadata_version"],properties:{metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0}},additionalProperties:false},UpdateSessionMetadata:{type:"object",required:["expected_version","metadata"],properties:{expected_version:{type:"integer",minimum:0,maximum:2147483647},metadata:{$ref:"#/components/schemas/MetadataObject"}},additionalProperties:false},Organization:{type:"object",required:["id","name","slug","created_at"],properties:{id:{type:"string"},name:{type:"string"},slug:{type:"string"},logo:{type:["string","null"],format:"uri"},metadata:{type:["object","null"]},created_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateOrganization:{type:"object",required:["name","slug"],properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:"string",format:"uri",maxLength:2048},metadata:{type:"object"}},additionalProperties:false},UpdateOrganization:{type:"object",minProperties:1,properties:{name:{type:"string",minLength:1,maxLength:200},slug:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:-[a-z0-9]+)*$"},logo:{type:["string","null"],format:"uri",maxLength:2048},metadata:{type:["object","null"]}},additionalProperties:false},OrganizationMember:{type:"object",required:["organization_id","user_id","role","created_at"],properties:{organization_id:{type:"string"},user_id:{type:"string"},role:{type:"string"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},AddMember:{type:"object",required:["user_id","role"],properties:{user_id:{type:"string"},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},OrganizationRole:{type:"object",required:["id","organization_id","name","permissions"],properties:{id:{type:"string"},organization_id:{type:"string"},name:{type:"string"},permissions:{type:"array",items:{$ref:"#/components/schemas/OrganizationPermissionId"}}},additionalProperties:false},OrganizationPermissionId:{type:"string",enum:["organization:update","organization:delete","member:create","member:update","member:delete","invitation:create","invitation:cancel","team:create","team:update","team:delete","ac:create","ac:read","ac:update","ac:delete"]},RoleInput:{type:"object",required:["name","permissions"],properties:{name:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9_-]*$"},permissions:{type:"array",maxItems:100,items:{$ref:"#/components/schemas/OrganizationPermissionId"},uniqueItems:true}},additionalProperties:false},Invitation:{type:"object",required:["id","organization_id","email","role","status","expires_at"],properties:{id:{type:"string"},organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100},status:{type:"string"},expires_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateInvitation:{type:"object",required:["organization_id","email","role"],properties:{organization_id:{type:"string"},email:{type:"string",format:"email",maxLength:320},role:{type:"string",minLength:1,maxLength:100}},additionalProperties:false},Event:{type:"object",required:["id","type","status","created_at"],properties:{id:{type:"string"},type:{type:"string"},status:{type:"string"},user_id:{type:["string","null"]},metadata:{type:"object"},created_at:{type:"string",format:"date-time"}},additionalProperties:false},StatsOverview:{type:"object",required:["users_total","monthly_active_users","recent_sign_ins"],properties:{users_total:{type:"integer",minimum:0},monthly_active_users:{type:"integer",minimum:0},recent_sign_ins:{type:"integer",minimum:0}},additionalProperties:false},WebhookInput:{type:"object",required:["url","events"],properties:{url:{type:"string",format:"uri",maxLength:2048},description:{type:"string",maxLength:500},events:{type:"array",minItems:1,maxItems:20,items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"},uniqueItems:true}},additionalProperties:false},SendMessage:{type:"object",required:["to","template","variables"],properties:{to:{type:"string",minLength:7,maxLength:32},channel:{type:"string",enum:["sms","whatsapp","auto"],description:"Defaults to auto."},purpose:{type:"string",enum:["transactional"],description:"Defaults to transactional."},template:{type:"string",pattern:"^[a-z][a-z0-9_]{0,63}$"},locale:{type:"string",enum:["en","ar"],description:"Defaults to en."},variables:{type:"object",maxProperties:50,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_]{0,63}$"},additionalProperties:{type:"string",maxLength:1024}},customerReference:{type:"string",minLength:1,maxLength:255}},additionalProperties:false},MessageState:{type:"string",enum:["preparing","queued","accepted","skipped","delivered","failed","unknown","canceled"]},Message:{type:"object",required:["id","state","purpose","requested_channel","actual_channel","customer_reference","masked_recipient","sms","billing","failure","created_at","updated_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},state:{$ref:"#/components/schemas/MessageState"},purpose:{type:"string",enum:["transactional","auth_otp"]},requested_channel:{type:"string",enum:["sms","whatsapp","auto"]},actual_channel:{type:["string","null"],enum:["sms","whatsapp",null]},customer_reference:{type:["string","null"]},masked_recipient:{type:"string"},sms:{oneOf:[{type:"null"},{type:"object",required:["encoding","segments"],properties:{encoding:{type:["string","null"],enum:["gsm7","ucs2",null]},segments:{type:["integer","null"],minimum:1}},additionalProperties:false}]},billing:{type:"object",required:["credential_mode","unit","units","charged_piasters","reserved_piasters"],properties:{credential_mode:{type:"string",enum:["managed","byok"]},unit:{type:["string","null"]},units:{type:["integer","null"]},charged_piasters:{type:"integer",minimum:0},reserved_piasters:{type:"integer",minimum:0}},additionalProperties:false},failure:{oneOf:[{type:"null"},{type:"object",required:["code","retryable"],properties:{code:{type:"string"},retryable:{type:"boolean"}},additionalProperties:false}]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},WebhookSubscriptionEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed"]},WebhookEventType:{type:"string",enum:["user.created","user.updated","user.deleted","user.banned","session.created","session.updated","session.revoked","organization.created","organization.updated","organization.deleted","organization_membership.created","organization_membership.deleted","mfa.enrolled","mfa.reset","message.accepted","message.skipped","message.delivered","message.failed","webhook.test"]},WebhookEndpoint:{type:"object",required:["id","url","events","status","created_at","updated_at"],properties:{id:{type:"string",format:"uuid"},url:{type:"string",format:"uri"},description:{type:["string","null"]},events:{type:"array",items:{$ref:"#/components/schemas/WebhookSubscriptionEventType"}},status:{type:"string",enum:["active","paused","auto_paused"]},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookSecret:{type:"object",required:["secret","overlap_expires_at"],properties:{secret:{type:"string"},overlap_expires_at:{type:"string",format:"date-time"}},additionalProperties:false},WebhookWithSecret:{type:"object",required:["endpoint","secret"],properties:{endpoint:{$ref:"#/components/schemas/WebhookEndpoint"},secret:{type:"string"}},additionalProperties:false},WebhookDelivery:{type:"object",required:["id","event_id","attempt_id","attempt_number","webhook_id","event_type","status","response_status","response_body","error_code","created_at","delivered_at"],properties:{id:{type:"string",format:"uuid"},event_id:{type:"string",format:"uuid"},attempt_id:{type:"string",format:"uuid"},attempt_number:{type:"integer",minimum:1},webhook_id:{type:"string",format:"uuid"},event_type:{$ref:"#/components/schemas/WebhookEventType"},status:{type:"string",enum:["queued","delivering","succeeded","failed"]},response_status:{type:["integer","null"]},response_body:{type:["string","null"]},error_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},delivered_at:{type:["string","null"],format:"date-time"}},additionalProperties:false},ExportJob:{type:"object",required:["id","format","status","includes_password_hashes","total_rows","artifact_bytes","failure_code","created_at","completed_at","expires_at","download_url"],properties:{id:{type:"string",format:"uuid"},format:{type:"string",enum:["ndjson","csv"]},status:{type:"string",enum:["pending","processing","completed","failed"]},includes_password_hashes:{type:"boolean"},total_rows:{type:"integer",minimum:0},artifact_bytes:{type:"integer",minimum:0},failure_code:{type:["string","null"]},created_at:{type:"string",format:"date-time"},completed_at:{type:["string","null"],format:"date-time"},expires_at:{type:["string","null"],format:"date-time"},download_url:{type:["string","null"]}},additionalProperties:false},ExportRequest:{type:"object",properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"}},additionalProperties:false},HashExportRequest:{type:"object",required:["approval_token"],properties:{format:{type:"string",enum:["ndjson","csv"],default:"ndjson"},approval_token:{type:"string",minLength:1,maxLength:256}},additionalProperties:false},Page:{type:"object",required:["data","next_cursor"],properties:{data:{type:"array"},next_cursor:{type:["string","null"]}},additionalProperties:false},UserPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/User"}}}}]},SessionPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}]},OrganizationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Organization"}}}}]},MemberPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationMember"}}}}]},RolePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/OrganizationRole"}}}}]},InvitationPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Invitation"}}}}]},EventPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Event"}}}}]},WebhookPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookEndpoint"}}}}]},DeliveryPage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/WebhookDelivery"}}}}]},MessagePage:{allOf:[{$ref:"#/components/schemas/Page"},{type:"object",properties:{data:{type:"array",items:{$ref:"#/components/schemas/Message"}}}}]}};var ue=new Set(["__proto__","constructor","prototype"]),le=64,fe=5e4;function H(e,t,r){let s=A[e].responseSchemas;Object.hasOwn(s,String(t))||P();let o=s[String(t)];if(o===null){r!==null&&P();return}let a={nodes:0};return l(r,g(o),0,a)||P(),r}function l(e,t,r,n){if(n.nodes+=1,r>le||n.nodes>fe)return false;if(typeof t.$ref=="string"){let o=we(t.$ref);if(o===null||!l(e,o,r+1,n))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>l(e,g(o),r+1,n))||Array.isArray(t.oneOf)&&t.oneOf.filter(o=>l(e,g(o),r+1,n)).length!==1||Array.isArray(t.enum)&&!t.enum.some(o=>Object.is(o,e))||t.const!==void 0&&!Object.is(t.const,e))return false;let s=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!s.some(o=>ye(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?he(e,t):typeof e=="number"?be(e,t):Array.isArray(e)?_e(e,t,r,n):E(e)?Se(e,t,r,n):typeof e=="boolean"}function ye(e,t){switch(t){case "null":return e===null;case "object":return E(e);case "array":return Array.isArray(e);case "string":return typeof e=="string";case "integer":return Number.isSafeInteger(e);case "number":return typeof e=="number"&&Number.isFinite(e);case "boolean":return typeof e=="boolean";default:return false}}function he(e,t){if(typeof t.minLength=="number"&&e.length<t.minLength||typeof t.maxLength=="number"&&e.length>t.maxLength||typeof t.pattern=="string"&&!ge(e,t.pattern))return false;switch(t.format){case void 0:return true;case "uuid":return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e);case "date-time":return /^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e));case "email":return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);case "uri":try{return new URL(e).protocol.length>1}catch{return false}default:return false}}function ge(e,t){switch(t){case "^[a-z0-9]+(?:-[a-z0-9]+)*$":return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e);case "^[a-z][a-z0-9_-]*$":return /^[a-z][a-z0-9_-]*$/.test(e);case "^[A-Za-z0-9][A-Za-z0-9._:/-]*$":return /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/.test(e);case "^[a-z][a-z0-9_]{0,63}$":return /^[a-z][a-z0-9_]{0,63}$/.test(e);case "^[A-Za-z][A-Za-z0-9_]{0,63}$":return /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(e);default:return false}}function be(e,t){return Number.isFinite(e)&&!(typeof t.minimum=="number"&&e<t.minimum)&&!(typeof t.maximum=="number"&&e>t.maximum)}function _e(e,t,r,n){if(typeof t.minItems=="number"&&e.length<t.minItems||typeof t.maxItems=="number"&&e.length>t.maxItems||t.uniqueItems===true&&new Set(e.map(o=>JSON.stringify(o))).size!==e.length)return false;if(t.items===void 0)return true;let s=g(t.items);return e.every(o=>l(o,s,r+1,n))}function Se(e,t,r,n){let s=Object.keys(e);if(s.some(a=>ue.has(a))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=E(t.properties)?t.properties:{};if(t.propertyNames!==void 0&&s.some(a=>!l(a,g(t.propertyNames),r+1,n))||Array.isArray(t.required)&&t.required.some(a=>typeof a!="string"||!Object.hasOwn(e,a)))return false;for(let[a,p]of Object.entries(e)){let c=o[a];if(c!==void 0){if(!l(p,g(c),r+1,n))return false;continue}if(t.additionalProperties===false||E(t.additionalProperties)&&!l(p,t.additionalProperties,r+1,n))return false}return true}function we(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let r=e.slice(t.length);return Object.hasOwn(v,r)?g(v[r]):null}function g(e){return E(e)||P(),e}function E(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function P(){throw new TypeError("Admin API response does not match its generated contract.")}var Ae=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Ee=1024*1024,Oe=1e4,O=class extends Error{status;code;requestId;problem;retryAfter;constructor(t){super(t.problem.detail),this.name="AuthOwlAdminApiError",this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.problem=t.problem,this.retryAfter=t.retryAfter;}},_=class extends Error{kind;requestId;constructor(t,r){super(t==="aborted"?"The AuthOwl Admin API request was aborted.":t==="timeout"?"The AuthOwl Admin API request timed out.":t==="response_too_large"?"The AuthOwl Admin API response exceeded the allowed size.":t==="invalid_response"?"The AuthOwl Admin API returned an invalid response.":"The AuthOwl Admin API request could not be completed."),this.name="AuthOwlAdminNetworkError",this.kind=t,this.requestId=r;}};function Te(e){Ie();let t=ke(e?.secretKey),r=Pe(e?.apiUrl),n=e?.fetch??globalThis.fetch;if(typeof n!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let s=n,o=async(p,c)=>{let m=c??{},f=A[p],y=new URL(xe(f.path,m).replace(/^\/+/,""),r);je(y,m);let d=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`});Le(d,m);let h$1="body"in m?JSON.stringify(m.body):void 0;h$1!==void 0&&d.set("content-type","application/json");let S;try{S=await h({fetchImpl:s,url:y,init:{method:f.method,headers:d,body:h$1,signal:c?.signal},timeoutMs:Oe,maxResponseBytes:Ee,allowHttpLoopback:r.protocol==="http:",decode:(u,Y)=>H(p,Y.status,u)});}catch(u){throw u instanceof O?u:u instanceof g$1?new _(u.kind,u.requestId):new _("network")}let{response:b,requestId:R,data:z}=S;if(!b.ok)throw ve(b,z,R);if(!f.successStatuses.some(u=>u===b.status))throw new _("invalid_response",R);return z},a=Object.assign(Object.create(null),{request:o});for(let p of Object.keys(A))a[p]=c=>o(p,c);return Object.freeze(a)}function Ie(){if(typeof window<"u"&&typeof window.document<"u")throw new Error("createAdminClient must not be called in a browser context.")}function ke(e){if(typeof e!="string"||!Ae.test(e))throw new TypeError("secretKey is malformed; expected sk_(live|test)_<uuid>_<random>.");return e}function Pe(e){if(typeof e!="string"||e.length===0)throw new TypeError("apiUrl is required.");let t=c(e,{allowHttpLoopback:true});if(t.username||t.password||t.search||t.hash)throw new TypeError("apiUrl must not contain credentials, a query, or a fragment.");let r=t.pathname.replace(/\/+$/,"");if(r!==""&&r!=="/api/v1")throw new TypeError("apiUrl path must be empty or /api/v1.");return t.pathname="/api/v1/",t}function xe(e,t){let r="path"in t&&x(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(n,s)=>{let o=r[s];if(typeof o!="string"&&typeof o!="number")throw new TypeError(`Missing Admin API path parameter: ${s}.`);return encodeURIComponent(String(o))})}function je(e,t){if(!(!("query"in t)||!x(t.query)))for(let[r,n]of Object.entries(t.query)){if(n==null)continue;let s=Array.isArray(n)?n:[n];for(let o of s)e.searchParams.append(r,String(o));}}function Le(e,t){if(!(!("header"in t)||!x(t.header)))for(let[r,n]of Object.entries(t.header)){if(n==null)continue;if(r.toLowerCase()!=="idempotency-key")throw new TypeError(`Unsupported Admin API header parameter: ${r}.`);if(typeof n!="string"||n.length<1||n.length>255)throw new TypeError("Idempotency-Key must contain between 1 and 255 characters.");if(!/^[\x21-\x7e ]+$/.test(n))throw new TypeError("Idempotency-Key contains unsupported characters.");e.set("Idempotency-Key",n);}}function ve(e,t,r){let n=r??F(e.headers.get("x-request-id"),256),s=F(e.headers.get("retry-after"),128),o=Ne(e.status,n),a=Re(t)?t:o;return new O({status:e.status,code:a.code,requestId:n,problem:a,retryAfter:s})}function Ne(e,t){return {type:"about:blank",title:"AuthOwl Admin API error",status:e,detail:"The AuthOwl Admin API rejected the request.",instance:`urn:authowl:request:${t??"unknown"}`,code:"UNKNOWN_ERROR"}}function Re(e){return x(e)?typeof e.type=="string"&&typeof e.title=="string"&&typeof e.status=="number"&&typeof e.detail=="string"&&typeof e.instance=="string"&&typeof e.code=="string":false}function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function F(e,t){let r=e?.trim();if(!(!r||r.length>t||!/^[\x21-\x7e]+$/.test(r)))return r}var ze=/^v1=([a-f0-9]{64})$/i,Ke=/^whsec_[A-Za-z0-9_-]{1,256}$/,Ue=/^(0|[1-9]\d{0,10})$/;async function $e(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=Me(e.secrets),r=e.toleranceSeconds??300;if(!Number.isSafeInteger(r)||r<0||r>3600)throw new TypeError("Webhook toleranceSeconds must be an integer from 0 to 3600.");let n=e.now??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(n)||n<0)throw new TypeError("Webhook now must be a non-negative Unix timestamp.");let s=De(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!Ue.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(n-o)>r)return false;let a=Ce(e.signatureHeader);if(a.length===0)return false;let p=new TextEncoder().encode(`${e.timestamp}.`),c=new Uint8Array(p.byteLength+s.byteLength);c.set(p),c.set(s,p.byteLength);let m=false;for(let f of t){let y=await crypto.subtle.importKey("raw",new TextEncoder().encode(f),{name:"HMAC",hash:"SHA-256"},false,["sign"]),d=new Uint8Array(await crypto.subtle.sign("HMAC",y,c));for(let h of a)m=qe(d,h)||m;}return m}function Me(e){if(!Array.isArray(e)||e.length<1||e.length>2||e.some(t=>typeof t!="string"||!Ke.test(t))||new Set(e).size!==e.length)throw new TypeError("Webhook secrets must contain one or two unique whsec_ values.");return e}function Ce(e){if(typeof e!="string"||e.length>1024)return [];let t=e.split(",");if(t.length>4)return [];let r=[];for(let n of t){let s=ze.exec(n.trim());s&&r.push(We(s[1]));}return r}function De(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("Webhook rawBody must be a string, ArrayBuffer, or ArrayBuffer view.")}function We(e){let t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(r*2,r*2+2),16);return t}function qe(e,t){if(e.byteLength!==t.byteLength)return false;let r=0;for(let n=0;n<e.byteLength;n+=1)r|=e[n]^t[n];return r===0}var G=["publishableKey","apiUrl","issuer","jwksUri","audience"],Je=new Set([...G,"clockToleranceSeconds"]);function N(e){if(e!==void 0&&(!e||typeof e!="object"))throw new Error("AuthOwl token verification config must be an object.");if(e&&Object.keys(e).some(p=>!Je.has(p)))throw new Error("AuthOwl token verification config contains an unsupported field.");let t=new Set(G.filter(p=>Object.prototype.hasOwnProperty.call(e??{},p))),r=t.has("publishableKey")||t.has("apiUrl"),n=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(r&&n)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(n){if(typeof e?.issuer!="string"||typeof e.jwksUri!="string"||typeof e.audience!="string")throw new Error("Explicit AuthOwl token verification requires issuer, jwksUri, and audience together.");return k({issuer:e.issuer,jwksUri:e.jwksUri,audience:e.audience,clockToleranceSeconds:e.clockToleranceSeconds})}let s,o;if(r){if(typeof e?.publishableKey!="string"||typeof e.apiUrl!="string")throw new Error("Derived AuthOwl token verification requires publishableKey and apiUrl together.");s=e.publishableKey,o=e.apiUrl;}else s=process.env.AUTHOWL_PUBLISHABLE_KEY,o=process.env.AUTHOWL_API_URL;if(!s||!o)throw new Error("AuthOwl token verification is not configured. Pass { publishableKey, apiUrl } (or issuer/jwksUri/audience), or set AUTHOWL_PUBLISHABLE_KEY and AUTHOWL_API_URL.");let a=f({publishableKey:s,apiUrl:o});return k({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e?.clockToleranceSeconds},a.decoded.env==="test")}async function at(e,t){return w(e,N(t))}async function pt(e,t,r){let n=N(r);try{let s=await w(e,n);return v$1(s.membership,t)}catch{return false}}async function dt(e,t$1,r){let n=N(r);try{let s=await w(e,n);return t(s.membership,t$1.permission)}catch{return false}}export{me as ADMIN_API_SPEC_SHA256,O as AuthOwlAdminApiError,_ as AuthOwlAdminNetworkError,i as TokenVerificationError,Te as createAdminClient,pt as has,dt as hasPermission,ce as verifyProjectToken,at as verifyToken,$e as verifyWebhook};
@@ -0,0 +1,2 @@
1
+ import {a as a$1}from'./chunk-T5SH3ZZP.js';var u="authowl_handoff_verifier",a="authowl_code",g=32,S=900,m=["email","providerId","domain","organizationSlug"];function f(n){let e="";for(let o of n)e+=String.fromCharCode(o);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function w(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return f(new Uint8Array(e))}function h(){return f(crypto.getRandomValues(new Uint8Array(g)))}function p(n,e){let o=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${u}=${n}; Path=/; Max-Age=${e}; SameSite=Lax${o}`;}function y(){for(let n of document.cookie.split(";")){let e=n.indexOf("=");if(!(e<0)&&n.slice(0,e).trim()===u)return n.slice(e+1).trim()||null}return null}function R(){p("",0);}function l(n){return new URL(n,window.location.href).toString()}async function U(n,e){let o=e.callbackURL?l(e.callbackURL):null;if(o&&new URL(o).origin!==window.location.origin)return null;let t=h(),i=new URL(`${n.projectBaseURL}/session/start`);if(i.searchParams.set("pk",n.publishableKey),i.searchParams.set("kind",e.kind),e.kind==="social")i.searchParams.set("provider",e.provider),e.scopes?.length&&i.searchParams.set("scopes",e.scopes.join(",")),e.loginHint&&i.searchParams.set("loginHint",e.loginHint),e.requestSignUp!==void 0&&i.searchParams.set("requestSignUp",e.requestSignUp?"1":"0");else for(let s of m){let r=e[s];r&&i.searchParams.set(s,r);}let d=`${window.location.origin}${window.location.pathname}${window.location.search}`;i.searchParams.set("cb",o??d);for(let[s,r]of [["err",e.errorCallbackURL],["new",e.newUserCallbackURL]])r&&i.searchParams.set(s,l(r));return i.searchParams.set("challenge",await w(t)),p(t,S),i.toString()}function k(){if(typeof window>"u")return null;let n=window.location.hash;if(!n.includes(a))return null;let e=new URLSearchParams(n.replace(/^#/,"")),o=e.get(a);if(!o)return null;e.delete(a);let t=e.toString();return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${t?`#${t}`:""}`),o}async function P(n,e){if(!a$1())return false;let o=k();if(!o)return false;let t=y();if(R(),!t)return false;e.beginSession({remember:true});let{error:i}=await n.request("/session/exchange",{method:"POST",body:{code:o,verifier:t}});return i===null}
2
+ export{U as beginCrossSiteSignIn,w as challengeFor,P as completeCrossSiteSignIn,k as takeHandoffCode};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authowl/core",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
4
4
  "description": "Framework-agnostic client for AuthOwl, the multi-tenant auth SaaS.",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -1,2 +0,0 @@
1
- var $=/^(pk_(live|test))_([0-9a-f-]{36})_([A-Za-z0-9]{20,})$/i,V=/^sk_/i;function j(e){if(typeof e!="string"||e.length===0)throw new Error("publishableKey is required");if(V.test(e))throw new Error("A secret key was passed where a publishable key was expected. Never embed secret keys in client code.");let t=$.exec(e);if(!t)throw new Error("publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>");return {prefix:t[1],env:t[2],projectId:t[3]}}function pe(e,t){let n=`p_${e.replace(/-/g,"")}`;return `${t?.secure?"__Secure-":""}${n}.session_token`}var U=/^http:\/\/(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i;function u(e,t){throw new Error(`${e}: ${t}`)}function v(e){return /^https?:\/\/[^/?#]*(\/[^?#]*)?$/i.exec(e)?.[1]??""}function S(e,{label:t,allowHttpLoopback:n}){(typeof e!="string"||e.length===0)&&u(t,"required"),e!==e.trim()&&u(t,"surrounding whitespace"),(e.includes("?")||e.includes("#"))&&u(t,"query or fragment forbidden"),(e.includes("\\")||/%[0-9a-f]{2}/i.test(e))&&u(t,"path must be unencoded");let r;try{r=new URL(e);}catch{u(t,"absolute URL required");}return (r.username||r.password)&&u(t,"credentials forbidden"),r.protocol!=="https:"&&r.protocol!=="http:"&&u(t,"HTTPS required"),r.protocol==="http:"&&(!n||!U.test(e))&&u(t,"HTTPS required except exact loopback"),r}function H(e,t){let n;try{n=new URL(String(e));}catch{throw new TypeError("Transport URL must be absolute.")}if(n.username||n.password||n.hash)throw new TypeError("Transport URL must not contain credentials or a fragment.");let r=n.toString();if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t.allowHttpLoopback&&U.test(r)))throw new TypeError("Transport URL must use HTTPS except on approved loopback.");return n}function K(e,t,n){let r=v(e);(r.includes("//")||r.split("/").some(o=>o==="."||o==="..")||r!==""&&r!==t.pathname)&&u(n,"path traversal or duplicate separator");}function J(e,t){(typeof e!="string"||!/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(e))&&u("apiUrl","origin required");let n;try{n=new URL(e);}catch{u("apiUrl","origin required");}return n.protocol==="http:"&&(!t.allowHttpLoopback||!U.test(e))&&u("apiUrl","HTTPS required except exact loopback"),n.origin}function fe(e,t,n={allowHttpLoopback:false}){let r=S(e,{label:"issuer",allowHttpLoopback:n.allowHttpLoopback}),o=S(t,{label:"jwksUri",allowHttpLoopback:n.allowHttpLoopback});return K(e,r,"issuer"),K(t,o,"jwksUri"),r.pathname!=="/"&&r.pathname.endsWith("/")&&u("issuer","trailing slash forbidden"),{issuer:r.toString().replace(/\/$/,""),jwksUri:o.toString()}}function ye(e){if(!e||typeof e!="object")throw new Error("AuthConfig is required");let t=j(e.publishableKey),n=J(e.apiUrl,{allowHttpLoopback:t.env==="test"}),r=`${n}/api/projects/${t.projectId}/auth`;return {...e,apiUrl:n,decoded:t,projectBaseURL:r}}var F=1e4,W=1024*1024,A=class extends Error{kind;requestId;constructor(t,n){super(ne(t)),this.name="TransportError",this.kind=t,this.requestId=n;}},q=new WeakSet;function i(e,t){let n=new A(e,t);return q.add(n),n}async function ke({fetchImpl:e,url:t,init:n={},timeoutMs:r=F,maxResponseBytes:o=W,allowHttpLoopback:y=false,decode:l}){z(r,"timeoutMs"),z(o,"maxResponseBytes");let f=H(t,{allowHttpLoopback:y}),b=n.signal,m=new AbortController,p=null,k,d=new Promise(a=>{k=a;}),T=a=>{p===null&&(p=a,k({type:"abort",kind:a}),m.abort());},g=()=>T("aborted");b?.addEventListener("abort",g,{once:true});let D=setTimeout(()=>T("timeout"),r);b?.aborted&&g();try{if(p!==null)throw i(p);let a;try{a=await Promise.race([e(f.toString(),{...n,redirect:"error",signal:m.signal}).then(I=>({type:"response",response:I})),d]);}catch{throw i(p??"network")}if(a.type==="abort")throw i(a.kind);if(!Y(a.response))throw i("invalid_response");let w=a.response,R=te(w.headers),M=await Z(w,o,d,()=>p,R),E=Q(w,M,R),P;try{P=w.ok&&l?l(E,Object.freeze({status:w.status})):E;}catch{throw i("invalid_response",R)}return {response:w,data:P,...R===void 0?{}:{requestId:R}}}catch(a){throw a instanceof A&&q.has(a)?a:i(p??"network")}finally{clearTimeout(D),b?.removeEventListener("abort",g);}}function Y(e){if(!e||typeof e!="object")return false;let t=e;return Number.isInteger(t.status)&&t.status>=0&&t.status<=599&&typeof t.statusText=="string"&&typeof t.ok=="boolean"&&typeof t.headers?.get=="function"&&(t.body===null||typeof t.body=="object"&&typeof t.body?.getReader=="function"&&typeof t.body.cancel=="function")}async function Z(e,t,n,r,o){let y=e.headers.get("content-length");if(y!==null){if(!/^\d+$/.test(y))throw N(e.body),i("invalid_response",o);if(Number(y)>t)throw N(e.body),i("response_too_large",o)}if(!e.body)return "";let l;try{l=e.body.getReader();}catch{throw i("network",o)}let f=[],b=0,m=null;try{for(;;){let d;try{d=await Promise.race([l.read(),n]);}catch{m=i(r()??"network",o);break}if(G(d)){m=i(d.kind,o);break}let{done:T,value:g}=d;if(T)break;if(g.byteLength!==0){if(b+=g.byteLength,b>t){m=i("response_too_large",o);break}f.push(g);}}}finally{m&&X(l);try{l.releaseLock();}catch{}}if(m)throw m;let p=new Uint8Array(b),k=0;for(let d of f)p.set(d,k),k+=d.byteLength;try{return new TextDecoder("utf-8",{fatal:!0}).decode(p)}catch{throw i("invalid_response",o)}}function G(e){return "type"in e&&e.type==="abort"}function N(e){if(e)try{e.cancel().catch(()=>{});}catch{}}function X(e){try{e.cancel().catch(()=>{});}catch{}}function Q(e,t,n){if(e.status===204||e.status===205)return null;let r=ee(e.headers.get("content-type"));if(!e.ok&&(!r||t.length===0))return null;if(!r||t.length===0)throw i("invalid_response",n);try{return JSON.parse(t)}catch{if(!e.ok)return null;throw i("invalid_response",n)}}function ee(e){if(e===null)return false;let t=e.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||t?.endsWith("+json")===true}function te(e){let t=e.get("x-request-id")?.trim();if(!(!t||t.length>256||!/^[A-Za-z0-9._:-]+$/.test(t)))return t}function z(e,t){if(!Number.isInteger(e)||e<=0)throw new TypeError(`${t} must be a positive integer.`)}function ne(e){switch(e){case "aborted":return "The request was cancelled.";case "timeout":return "The request timed out.";case "response_too_large":return "The response exceeded the allowed size.";case "invalid_response":return "The service returned an invalid response.";case "network":return "The network request could not be completed."}}function re(e,t){return !e||!t?false:e.permissions.includes(t)}function oe(e,t){return !e||!t?false:e.teams?.includes(t)??false}function ie(e,t){if(!e)return false;let{role:n,permission:r,teamId:o}=t;return !(n===void 0&&r===void 0&&o===void 0||n!==void 0&&e.role!==n||r!==void 0&&!e.permissions.includes(r)||o!==void 0&&!oe(e,o))}function Te(e){return {has:t=>ie(e,t),hasPermission:t=>re(e,t.permission)}}var se=new Set(["__proto__","constructor","prototype"]);function L(e){(!e||typeof e!="object"||Array.isArray(e))&&s();let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null&&s(),e}function x(e){return typeof e!="string"&&s(),e}function ae(e){return typeof e!="boolean"&&s(),e}function O(e){return (!(e instanceof Date)||Number.isNaN(e.getTime()))&&s(),e}function B(e){return (!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&s(),[...e]}function h(e,t){let n=e[t];return n==null||typeof n=="string"?n:s()}function C(e,t){let n=e[t];return n==null||typeof n=="boolean"?n:s()}function xe(e){let t=L(e),n=t.email;return n!==null&&typeof n!="string"&&s(),{id:x(t.id),email:n,emailVerified:ae(t.emailVerified),createdAt:O(t.createdAt),updatedAt:O(t.updatedAt),...c("phoneNumber",h(t,"phoneNumber")),...c("username",h(t,"username")),...c("displayUsername",h(t,"displayUsername")),...c("firstName",h(t,"firstName")),...c("lastName",h(t,"lastName")),...c("name",h(t,"name")),...c("image",h(t,"image")),...c("twoFactorEnabled",C(t,"twoFactorEnabled"))}}function Ue(e){let t=L(e),n=t.membership;return {id:x(t.id),userId:x(t.userId),expiresAt:O(t.expiresAt),...c("activeOrganizationId",h(t,"activeOrganizationId")),...c("activeTeamId",h(t,"activeTeamId")),...c("membership",n==null?n:ce(n)),...c("pendingMfaEnrollment",C(t,"pendingMfaEnrollment"))}}function s(){throw new TypeError("AuthOwl response does not match its runtime contract.")}function Oe(e,t=20,n=1e4){return (!e||typeof e!="object"||Array.isArray(e))&&s(),ue(e,t,n)}function ue(e,t=20,n=1e4){return _(e,0,{nodes:0},t,n)}function ce(e){let t=L(e);return {role:x(t.role),permissions:B(t.permissions),...t.teams===void 0?{}:{teams:B(t.teams)}}}function _(e,t,n,r,o){if(n.nodes+=1,(t>r||n.nodes>o)&&s(),e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||s(),e;if(Array.isArray(e))return e.map(f=>_(f,t+1,n,r,o));(!e||typeof e!="object")&&s();let y=Object.getPrototypeOf(e);y!==Object.prototype&&y!==null&&s();let l={};for(let[f,b]of Object.entries(e))se.has(f)&&s(),l[f]=_(b,t+1,n,r,o);return l}function c(e,t){return t===void 0?{}:{[e]:t}}
2
- export{j as a,pe as b,H as c,fe as d,ye as e,A as f,ke as g,L as h,x as i,ae as j,O as k,B as l,h as m,xe as n,Ue as o,s as p,Oe as q,ue as r,re as s,oe as t,ie as u,Te as v};
@@ -1 +0,0 @@
1
- import {f,g,q as q$1,j as j$1,h,p,i,n,s,u,o,k,r,m as m$1,l}from'./chunk-KPXCQZUX.js';import {a}from'./chunk-T5SH3ZZP.js';function yi(e){let t=e?.enabledMethods??["password"],n=t.includes("password"),i=t.includes("passkey"),o=e?.authentication,a=e?.mfa;return {emailSignUp:o?.email.signUp??t.some(r=>r==="password"||r==="magic_link"||r==="email_otp"),passwordSignUp:o?.password.signUp??n,phoneSignUp:o?.phone.signUp??t.includes("phone_otp"),passwordSignIn:o?.email.signIn.includes("password")??n,passwordMinLength:o?.password.minLength??8,passwordMaxLength:o?.password.maxLength??128,magicLinkSignIn:o?.email.signIn.includes("magic_link")??t.includes("magic_link"),emailOtpSignIn:o?.email.signIn.includes("email_otp")??t.includes("email_otp"),phoneSignIn:o?.phone.signIn??t.includes("phone_otp"),usernameSignIn:o?.username.signIn??false,collectUsername:o?.username.collectOnSignUp??false,passkeySignIn:o?.passkey.signIn??i,passkeyAdd:o?.passkey.add??i,firstLastName:e?.userModel?.firstLastName??false,emailChange:e===null?false:e.userModel?.emailChange??true,accountDeletion:e?.userModel?.accountDeletion??e?.accountDeletion??false,emailVerificationRequired:e?.emailVerification?.required??e?.requireEmailVerification??false,emailVerificationMethod:e?.emailVerification?.method??"link",totp:a?.totp??e?.twoFactor??false,mfaRequired:a?.required??e?.mfaRequired??false,backupCodes:a?.backupCodes??e?.twoFactor??false,legacyNameField:e?.authentication===void 0}}var Qt="x-authowl-turnstile-token",Zt=1e4,en=32,tn=2e4;function N(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 ke(e,t=e.projectBaseURL){return {async request(n,i={}){let o=rn(t,n,i.query),a=i.method??(i.body===void 0?"GET":"POST"),r=new Headers(i.fetchOptions?.headers);r.set("x-publishable-key",e.publishableKey),i.fetchOptions?.authChallengeToken&&r.set(Qt,i.fetchOptions.authChallengeToken),i.body!==void 0&&r.set("content-type","application/json");let d={method:a,headers:r,credentials:i.credentials??"include",...i.body===void 0?{}:{body:JSON.stringify(i.body)}},u=Object.freeze({method:a,path:n});await i.fetchOptions?.onRequest?.(u);let f$1=on(a,i.fetchOptions),h;try{h=await nn(e,o,{...d,signal:i.fetchOptions?.signal},f$1);}catch(w){let me=we(w);return await i.fetchOptions?.onError?.(ee(u,me,un(w))),{data:null,error:me}}let{response:S,requestId:s}=h,c=ln(n,h.data),g=c;if(S.ok)try{g=ne(c),i.decode&&(g=i.decode(g));}catch{let w=we(new f("invalid_response",s));return await i.fetchOptions?.onError?.(ee(u,w,"invalid_response")),{data:null,error:w}}let b=Object.freeze({...u,status:S.status,...s===void 0?{}:{requestId:s}});if(await i.fetchOptions?.onResponse?.(b),!S.ok){let w=an(S,c,s);return await i.fetchOptions?.onError?.(ee(u,w,"api")),{data:null,error:w}}return await i.fetchOptions?.onSuccess?.(b),{data:g,error:null}}}}async function nn(e,t,n,i){let o=Date.now()+Zt;for(let a=0;a<i;a+=1){let r=o-Date.now();if(r<=0)throw new f("timeout");try{let d=await g({fetchImpl:e.fetch??fetch,url:t,init:n,timeoutMs:Math.max(1,Math.ceil(r)),allowHttpLoopback:e.decoded.env==="test"});if(d.response.status<500||a===i-1)return d}catch(d){if(a===i-1||!(d instanceof f)||d.kind!=="network")throw d}await cn(50*2**a,n.signal,o);}throw new f("network")}function on(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 rn(e,t,n){let i=new URL(`${e}${t.startsWith("/")?t:`/${t}`}`);for(let[o,a]of Object.entries(n??{}))a!==void 0&&i.searchParams.set(o,String(a));return i.toString()}function an(e,t,n){let i=F(t)?t:{},o=sn(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 sn(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??be(t.get("retry-after"))??be(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function be(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 we(e){let t=e instanceof f?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 f&&e.requestId?{requestId:e.requestId}:{}}}function ee(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function un(e){return e instanceof f?e.kind:"network"}function cn(e,t,n){return new Promise((i,o)=>{if(t?.aborted){o(new f("aborted"));return}let a=n-Date.now();if(a<=0){o(new f("timeout"));return}let r=Math.min(e,a),d=()=>{clearTimeout(u),o(new f("aborted"));},u=setTimeout(()=>{t?.removeEventListener("abort",d),Date.now()>=n?o(new f("timeout")):i();},r);t?.addEventListener("abort",d,{once:true}),t?.aborted&&d();})}function ne(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>en||i.nodes>tn)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=>ne(o,"",n+1,i)):F(e)?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,dn(o)?a:ne(a,o,n+1,i)])):e}function dn(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function ln(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>F(o)?te(o):o);if(!F(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-")?te(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")&&F(i.session)&&(i={...i,session:te(i.session)}),i}function te(e){if(!Object.hasOwn(e,"token"))return e;let t={...e};return delete t.token,t}function F(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function Se(){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 Ie(e,t){let n=new Set,i=null,o=null,a=null,r,d=c=>{h(c);};r={data:null,isPending:true,isRefetching:false,error:null,refetch:d};function u(c){r=c;for(let g of n)g();}async function f(c){return e.request("/get-session",{query:c?.query,decode:Re})}async function h(c){a?.abort();let g=new AbortController;a=g,u({...r,isPending:r.data===null&&r.error===null,isRefetching:r.data!==null});let b=await e.request("/get-session",{query:c?.query,fetchOptions:{signal:g.signal},decode:Re});a===g&&(a=null,u({data:b.data,error:b.error,isPending:false,isRefetching:false,refetch:d}));}function S(){if(typeof window>"u"||o)return;let c=()=>{h();},g=()=>{document.visibilityState==="visible"&&h();};window.addEventListener("focus",c),document.addEventListener("visibilitychange",g),typeof BroadcastChannel<"u"&&(i=new BroadcastChannel(`authowl:${t}`),i.addEventListener("message",c)),o=()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",g),i?.close(),i=null,o=null;};}function s(c){return n.add(c),n.size===1&&(S(),h()),()=>{n.delete(c),n.size===0&&(a?.abort(),a=null,o?.());}}return {store:{subscribe:s,getSnapshot:()=>r},getSession:f,notifyMutation(){i?.postMessage({type:"session-changed"}),n.size>0&&h({query:{disableCookieCache:true}});}}}function Re(e){if(e===null)return null;let t=h(e);return (t.session===void 0||t.user===void 0)&&p(),{session:o(t.session),user:n(t.user)}}async function Pe(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:ve})}async function Te(e,t,n){return e.request("/user/metadata",{method:"PATCH",body:{expected_version:t.expectedVersion,unsafe_metadata:t.unsafeMetadata},fetchOptions:n,decode:ve})}function ve(e){let t=h(e),n=q$1(t.public_metadata),i=q$1(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 xe(e,t){let{post:n,mutation:i}=N(e,t);return {getMetadata:o=>Pe(e,o),updateUnsafeMetadata:(o,a)=>Te(e,o,a),updateProfile:(o,a)=>i(n("/update-user",o,a,q)),changeEmail:(o,a)=>i(n("/change-email",o,a,q)),changePassword:(o,a)=>i(n("/change-password",o,a,pn)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:gn}),revokeSession:({sessionId:o},a)=>i(n("/revoke-session",{sessionId:o},a,q)),revokeOtherSessions:o=>i(n("/revoke-other-sessions",{},o,q)),listSocialAccounts:async o=>{let a=await e.request("/list-accounts",{fetchOptions:o,decode:fn});if(!a.data)return {data:null,error:a.error};let r=a.data.length>1;return {...a,data:a.data.filter(d=>d.providerId!=="credential").map(d=>({...d,canUnlink:r}))}},linkSocial:(o,a)=>n("/link-social",o,a,mn),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,q)),delete:(o={},a)=>i(n("/delete-user",o,a,hn))}}function q(e){let t=h(e);return {status:j$1(t.status)}}function pn(e){let t=h(e);return {user:n(t.user)}}function gn(e){return Array.isArray(e)||p(),e.map(t=>{let n=h(t);return {id:i(n.id),userId:i(n.userId),createdAt:k(n.createdAt),updatedAt:k(n.updatedAt),expiresAt:k(n.expiresAt),...Ce("ipAddress",m$1(n,"ipAddress")),...Ce("userAgent",m$1(n,"userAgent"))}})}function fn(e){return Array.isArray(e)||p(),e.map(t=>{let n=h(t);return {id:i(n.id),userId:i(n.userId),providerId:i(n.providerId),accountId:i(n.accountId),scopes:l(n.scopes),createdAt:k(n.createdAt),updatedAt:k(n.updatedAt)}})}function mn(e){let t=h(e);return {url:i(t.url),redirect:j$1(t.redirect)}}function hn(e){let t=h(e);return {success:j$1(t.success),message:i(t.message)}}function Ce(e,t){return t===void 0?{}:{[e]:t}}var An=new Set(["pending","accepted","rejected","canceled"]),De=1e4;function U(e,t,n){let i=h(e),o={id:m(i.id),name:m(i.name),slug:m(i.slug),createdAt:k(i.createdAt),...K("logo",m$1(i,"logo")),...K("metadata",i.metadata===void 0?void 0:r(i.metadata))};return z(o.id,t),z(o.slug,n),o}function ze(e){return E(e,U)}function ie(e,t,n){return e===null?null:(t===null&&p(),U(e,t,n))}function Ee(e,t,n){if(e===null)return null;let i=h(e),o=U(i,t,n);return {...o,members:E(i.members,a=>Je(a,o.id)),invitations:E(i.invitations,a=>x(a,void 0,o.id))}}function Ne(e,t){let n=E(e,i=>je(i));return j(n.map(i=>i.organizationId),t),n}function Ue(e,t,n){return e===null?null:(t===null&&p(),je(e,t,n))}function Me(e,t){let n=h(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&p(),{members:yn(n.members,t),total:n.total}}function x(e,t,n){let i=h(e),o=m(i.status);An.has(o)||p();let a={id:m(i.id),organizationId:m(i.organizationId),email:m(i.email),role:m(i.role),status:o,inviterId:m(i.inviterId),expiresAt:k(i.expiresAt),createdAt:k(i.createdAt)};return z(a.id,t),z(a.organizationId,n),a}function _e(e,t){let n=E(e,i=>x(i));return j(n.map(i=>i.organizationId),t),n}function Le(e){return E(e,t=>{let n=h(t);return {...x(n),organizationName:m(n.organizationName)}})}function Fe(e,t){let n=h(e);return {...x(n,t),organizationName:m(n.organizationName),organizationSlug:m(n.organizationSlug),inviterEmail:m(n.inviterEmail)}}function qe(e,t){let n=h(e),i=x(n.invitation,t);return {invitation:i,member:M(n.member,void 0,i.organizationId)}}function Ve(e,t){let n=h(e);return n.member!==null&&p(),{invitation:n.invitation===null?null:x(n.invitation,t),member:null}}function He(e,t){return e===null?null:x(e,t)}function Be(e,t,n){let i=h(e);return {member:M(i.member,n,t)}}function M(e,t,n){let i=h(e),o={id:m(i.id),organizationId:m(i.organizationId),userId:m(i.userId),role:m(i.role),createdAt:k(i.createdAt),...i.user===void 0?{}:{user:Ge(i.user)}};return z(o.id,t),z(o.organizationId,n),o}function Ke(e,t){let n=E(e,i=>{let o=h(i);return {organizationId:m(o.organizationId),data:{role:m(o.role),...K("permission",o.permission===void 0?void 0:On(o.permission))}}});return j(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function je(e,t,n){let i=h(e),o=i.updatedAt,a={id:m(i.id),name:m(i.name),organizationId:m(i.organizationId),createdAt:k(i.createdAt),...o===void 0?{}:{updatedAt:k(o)}};return z(a.id,t),z(a.organizationId,n),a}function Je(e,t){let n=h(e);return {...M(n,void 0,t),user:Ge(n.user)}}function yn(e,t){let n=E(e,i=>Je(i));return j(n.map(i=>i.organizationId),t),n}function On(e){let t=h(e),n={};for(let[i,o]of Object.entries(t))(i==="__proto__"||i==="constructor"||i==="prototype"||i.length===0||i.length>De||!Array.isArray(o))&&p(),n[i]=o.map(a=>m(a));return n}function m(e){let t=i(e);return (t.length===0||t.length>De)&&p(),t}function z(e,t){t!==void 0&&e!==t&&p();}function j(e,t){let n=t??e[0];n!==void 0&&e.some(i=>i!==n)&&p();}function Ge(e){let t=h(e);return {id:m(t.id),name:m(t.name),email:m(t.email),...K("image",m$1(t,"image"))}}function E(e,t){return Array.isArray(e)||p(),e.map(n=>t(n))}function K(e,t){return t===void 0?{}:{[e]:t}}function We(e,t,n=()=>null){let{post:i,mutation:o}=N(e,t),a=(r,d,u,f)=>e.request(r,{query:d,fetchOptions:u,decode:f});return {create:(r,d)=>o(i("/organization/create",r,d,U)),list:r=>a("/organization/list",void 0,r,ze),get:(r={},d)=>a("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},d,u=>Ee(u,r.organizationId,r.organizationSlug)),setActive:(r,d)=>o(i("/organization/set-active",r,d,u=>ie(u,r.organizationId,r.organizationSlug))),listTeams:(r={},d)=>a("/organization/list-teams",{organizationId:r.organizationId},d,u=>Ne(u,r.organizationId)),setActiveTeam:(r,d)=>o(i("/organization/set-active-team",r,d,u=>Ue(u,r.teamId))),update:(r,d)=>o(i("/organization/update",r,d,u=>ie(u,r.organizationId))),delete:(r,d)=>o(i("/organization/delete",r,d,u=>U(u,r.organizationId))),listMembers:(r={},d)=>a("/organization/list-members",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,limit:r.limit,offset:r.offset,sortBy:r.sortBy,sortDirection:r.sortDirection,filterField:r.filterField,filterValue:r.filterValue,filterOperator:r.filterOperator},d,u=>Me(u,r.organizationId)),inviteMember:(r,d)=>o(i("/organization/invite-member",r,d,u=>x(u,void 0,r.organizationId))),listInvitations:(r={},d)=>a("/organization/list-invitations",{organizationId:r.organizationId},d,u=>_e(u,r.organizationId)),listUserInvitations:r=>a("/organization/list-user-invitations",void 0,r,Le),getInvitation:(r,d)=>a("/organization/get-invitation",{id:r.id},d,u=>Fe(u,r.id)),acceptInvitation:(r,d)=>o(i("/organization/accept-invitation",r,d,u=>qe(u,r.invitationId))),rejectInvitation:(r,d)=>o(i("/organization/reject-invitation",r,d,u=>Ve(u,r.invitationId))),cancelInvitation:(r,d)=>o(i("/organization/cancel-invitation",r,d,u=>He(u,r.invitationId))),removeMember:(r,d)=>o(i("/organization/remove-member",r,d,u=>Be(u,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,d)=>o(i("/organization/update-member-role",r,d,u=>M(u,r.memberId,r.organizationId))),leave:(r,d)=>o(i("/organization/leave",r,d,u=>M(u,void 0,r.organizationId))),listRoles:(r={},d)=>a("/organization/list-roles",{organizationId:r.organizationId},d,u=>Ke(u,r.organizationId)),has:r=>u(n(),r),hasPermission:r=>s(n(),r.permission)}}var Xe=4096,bn=4096,wn=100,kn=256,Sn=16,Rn=64,In=12;function re(e){let t=h(e);return t.twoFactorRedirect===true?((t.user!==void 0||t.redirect!==void 0||t.url!==void 0)&&p(),{twoFactorRedirect:true,...t.twoFactorMethods===void 0?{}:{twoFactorMethods:gt(t.twoFactorMethods,Sn,Rn)}}):(t.twoFactorRedirect!==void 0&&p(),{redirect:j$1(t.redirect),...xn(t,"url"),user:n(t.user)})}function $e(e){let t=h(e);return {user:n(t.user)}}function Ye(e){let t=h(e);return {sessionCreated:j$1(t.sessionCreated),user:n(t.user)}}function Qe(e,t){let n$1=h(e),i=j$1(n$1.redirect);n$1.user===null&&p();let o=n$1.user!==void 0&&n$1.user!==null,a=n$1.url!==void 0&&n$1.url!==null;return i?((o||!a)&&p(),{redirect:true,url:oe(n$1.url,t)}):(o===a&&p(),o?{redirect:false,user:n(n$1.user)}:{redirect:false,url:oe(n$1.url,t)})}function Ze(e,t){let n=h(e);return (n.redirect!==true||n.user!==void 0)&&p(),{redirect:true,url:oe(n.url,t)}}function et(e){return {status:j$1(h(e).status)}}function tt(e){return {success:j$1(h(e).success)}}function nt(e){return h(e).status!=="pending"&&p(),{status:"pending"}}function it(e){let t=h(e);if(t.kind==="authowl_turnstile")return {kind:"authowl_turnstile"};t.kind!=="akedly_shield_v1_2"&&p();let n=h(t.turnstile),i$1=n.siteKey===null?null:i(n.siteKey);return {kind:"akedly_shield_v1_2",connectionId:i(t.connectionId),challenge:i(t.challenge),difficulty:Pn(t.difficulty),challengeToken:i(t.challengeToken),challengeRequired:j$1(t.challengeRequired),turnstile:{required:j$1(n.required),siteKey:i$1}}}function Pn(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>In)&&p(),Number(e)}function ot(e){let t=h(e);return (t.status!==true||t.sessionCreated!==true)&&p(),{status:true,sessionCreated:true,user:Tn(t.user)}}function ae(e){return {status:j$1(h(e).status)}}function rt(e){return {status:j$1(h(e).status)}}function at(e){let t=h(e);return {status:j$1(t.status),user:n(t.user)}}function st(e){return {success:j$1(h(e).success)}}function ut(e){let t=h(e);return {totpURI:Cn(t.totpURI),backupCodes:pt(t.backupCodes)}}function ct(e){return {status:j$1(h(e).status)}}function J(e){return h(e).status!==true&&p(),{status:true}}function dt(e){return {status:j$1(h(e).status)}}function lt(e){let t=h(e);return t.status!==void 0&&t.status!==true&&p(),{backupCodes:pt(t.backupCodes)}}function Tn(e){let t=h(e);return {id:_(t.id,512),...Dn(t,"name",1024),phoneNumber:_(t.phoneNumber,64),phoneNumberVerified:j$1(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:k(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:k(t.updatedAt)}}}function oe(e,t){let n=_(e,Xe);/[\u0000-\u0020\u007f]/u.test(n)&&p();let i;try{i=new URL(n);}catch{return p()}return (i.username||i.password)&&p(),i.protocol==="https:"||t&&i.protocol==="http:"&&vn(i.hostname)?i.href:p()}function vn(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Cn(e){let t=_(e,bn),n;try{n=new URL(t);}catch{return p()}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))&&p(),t}function pt(e){return gt(e,wn,kn)}function gt(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&p();let i=e.map(o=>_(o,n));return i.some(o=>o.trim().length===0)&&p(),new Set(i).size!==i.length&&p(),i}function _(e,t){let n=i(e);return (n.length===0||n.length>t)&&p(),n}function xn(e,t){let n=e[t];return n==null?{}:{[t]:_(n,Xe)}}function Dn(e,t,n){let i=m$1(e,t);return i===void 0?{}:(i!==null&&i.length>n&&p(),{[t]:i})}var ft=new Set([1564,8206,8207,8234,8235,8236,8237,8238,8294,8295,8296,8297]),G=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 W(e){if(e===void 0)return {valid:true,value:void 0};for(let n of e){let i=n.codePointAt(0);if(i===void 0||ht(n,i)||mt(i)||ft.has(i))return {valid:false}}let t=zn(e);return se(t)?{valid:true,value:t}:{valid:false}}function se(e){let t=0,n,i;for(let o of e){if(t+=1,t>256)return false;let a=o.codePointAt(0);if(a===void 0||ht(o,a)||mt(a)||ft.has(a))return false;n??=a,i=a;}return t>0&&n!==void 0&&i!==void 0&&!G.has(n)&&!G.has(i)}function X(){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 zn(e){let t=0,n=e.length;for(;t<n;){let i=e.codePointAt(t);if(i===void 0||!G.has(i))break;t+=i>65535?2:1;}for(;n>t;){let i=e.codePointAt(n-1);if(i===void 0)break;let a=i>=56320&&i<=57343?n-2:n-1,r=e.codePointAt(a);if(r===void 0||!G.has(r))break;n=a;}return e.slice(t,n)}function mt(e){return e>=0&&e<=31||e>=127&&e<=159}function ht(e,t){return e.length===1&&t>=55296&&t<=57343}var Ot=12,bt=5e3,En=8,Nn=1e3,Un=16,At=512,wt=100,kt=8192,Mn=32768,ue=1024,yt=256,de=64,_n=6e5,Ln=/^[A-Za-z0-9_-]+$/u,Fn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,qn=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,Vn=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,Hn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,St=new Set(["discouraged","preferred","required"]),Bn=new Set(["singleDevice","multiDevice"]),Rt=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),It=new Set(["hybrid","security-key","client-device"]),Kn=new Set(["none","indirect","direct","enterprise"]),jn=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),Jn=new Set(["platform","cross-platform"]),Gn=new Set(["discouraged","preferred","required"]),Wn=new Set([-8,-7,-257]);function Pt(e){let t=q$1(e,Ot,bt);return {challenge:Mt(t.challenge),...O("timeout",Nt(t.timeout)),...O("rpId",_t(t.rpId)),...O("allowCredentials",Et(t.allowCredentials)),...O("userVerification",V(t.userVerification,St)),...O("hints",$(t.hints,It)),...O("extensions",Ut(t.extensions))}}function Tt(e){let t=q$1(e,Ot,bt);return {challenge:Mt(t.challenge),rp:Xn(t.rp),user:$n(t.user),pubKeyCredParams:Yn(t.pubKeyCredParams),...O("timeout",Nt(t.timeout)),...O("excludeCredentials",Et(t.excludeCredentials)),...O("authenticatorSelection",Qn(t.authenticatorSelection)),...O("attestation",V(t.attestation,Kn)),...O("attestationFormats",$(t.attestationFormats,jn)),...O("hints",$(t.hints,It)),...O("extensions",Ut(t.extensions))}}function vt(e){let t=h(e),n$1=o(t.session),i=n(t.user);return n$1.userId!==i.id&&p(),{session:n$1,user:i}}function le(e){let t=h(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&p();let i=pe(t.deviceType,Bn),o=j$1(t.backedUp);return o&&i!=="multiDevice"&&p(),{id:L(t.id,yt),...ti(t),publicKey:Zn(t.publicKey,Mn),userId:L(t.userId,yt),credentialID:Q(t.credentialID,kt),counter:n,deviceType:i,backedUp:o,...ni(t),createdAt:k(t.createdAt),...ii(t)}}function Ct(e,t,n){let i=le(e);return (i.credentialID!==t||(n===void 0?i.name!==void 0&&i.name!==null:i.name!==n))&&p(),i}function xt(e){(!Array.isArray(e)||e.length>wt)&&p();let t=e.map(le);return Y(t.map(n=>n.id)),Y(t.map(n=>n.credentialID)),t.length>1&&t.some(n=>n.userId!==t[0]?.userId)&&p(),t}function Dt(e,t,n){let i=h(e),o=le(i.passkey);return (o.id!==t||o.name!==n)&&p(),{passkey:o}}function zt(e){return h(e).status!==true&&p(),{status:true}}function Xn(e){let t=h(e);return {name:ce(t.name,ue),...O("id",_t(t.id))}}function $n(e){let t=h(e);return {id:Q(t.id,128,1,64),name:ce(t.name,ue),displayName:ce(t.displayName,ue)}}function Yn(e){(!Array.isArray(e)||e.length===0||e.length>de)&&p();let t=e.map(n=>{let i=h(n);return (i.type!=="public-key"||!Number.isSafeInteger(i.alg)||!Wn.has(i.alg))&&p(),{type:"public-key",alg:i.alg}});return oi(t.map(n=>n.alg)),t}function Et(e){if(e===void 0)return;(!Array.isArray(e)||e.length>wt)&&p();let t=e.map(n=>{let i=h(n);return i.type!=="public-key"&&p(),{type:"public-key",id:Q(i.id,kt),...O("transports",$(i.transports,Rt))}});return Y(t.map(n=>n.id)),t}function Qn(e){if(e===void 0)return;let t=h(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&p();let n=V(t.residentKey,Gn);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&p(),{...O("authenticatorAttachment",V(t.authenticatorAttachment,Jn)),...O("residentKey",n),...O("requireResidentKey",t.requireResidentKey),...O("userVerification",V(t.userVerification,St))}}function Nt(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>_n)&&p(),e}function Ut(e){return e===void 0?void 0:q$1(e,En,Nn)}function $(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>de)&&p();let n=e.map(i=>pe(i,t));return Y(n),n}function V(e,t){if(e!==void 0)return pe(e,t)}function Mt(e){return Q(e,Math.ceil(At*4/3),Un,At)}function Q(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=L(e,t),a=o.length%4,r=ei(o.at(-1)??""),d=Math.floor(o.length*3/4);return (!Ln.test(o)||a===1||a===2&&(r&15)!==0||a===3&&(r&3)!==0||d<n||d>i)&&p(),o}function L(e,t){let n=i(e);return (n.length===0||n.length>t)&&p(),n}function ce(e,t){let n=L(e,t);return qn.test(n)&&p(),n}function _t(e){if(e===void 0)return;let t=L(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!Vn.test(n)))&&p(),t}function Zn(e,t){let n=L(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",r=Lt(a);return (n.length%4!==0||!Fn.test(n)||i&&(r&15)!==0||o&&(r&3)!==0)&&p(),n}function ei(e){return Lt(e,true)}function Lt(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function ti(e){let t=m$1(e,"name");return t===void 0?{}:(t!==null&&!se(t)&&p(),{name:t})}function ni(e){let t=m$1(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>de||n.some(i=>!Rt.has(i))||new Set(n).size!==n.length)&&p(),{transports:t}}function ii(e){let t=m$1(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(Hn.test(t)||p(),{aaguid:t})}function pe(e,t){let n=i(e);return t.has(n)||p(),n}function O(e,t){return t===void 0?{}:{[e]:t}}function Y(e){new Set(e).size!==e.length&&p();}function oi(e){new Set(e).size!==e.length&&p();}function ri(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 Ft=new Map;function ai(e,t){let n=Ft.get(t);return n||(n=import('./session-handoff-6B5KZXQV.js').then(i=>i.completeCrossSiteSignIn(e)),Ft.set(t,n)),n}function qt(e){return !a()||e.idToken||e.disableRedirect?"legacy":"first-party"}function si(e,t=()=>{},n=di){let i=ke(e),o=a()?ai(i,e.decoded.projectId):void 0,a$1=ri(i,o),r=Ie(a$1,e.decoded.projectId),d=n(a$1,r.notifyMutation),u=()=>{r.notifyMutation(),t();},{post:f,mutation:h}=N(a$1,u),S=e.decoded.env==="test";return {sessionStore:r.store,getSession:r.getSession,account:xe(a$1,u),organization:We(a$1,u,()=>r.store.getSnapshot().data?.session.membership??null),signIn:{email:(s,c)=>h(f("/sign-in/email",s,c,re),g=>!("twoFactorRedirect"in g)),username:(s,c)=>h(f("/sign-in/username",s,c,re),g=>!("twoFactorRedirect"in g)),social:async(s,c)=>{if(qt(s)==="first-party"){let{beginCrossSiteSignIn:b}=await import('./session-handoff-6B5KZXQV.js'),w=await b(e,{kind:"social",provider:s.provider,callbackURL:s.callbackURL,errorCallbackURL:s.errorCallbackURL,newUserCallbackURL:s.newUserCallbackURL,scopes:s.scopes,loginHint:s.loginHint,requestSignUp:s.requestSignUp});if(w)return window.location.assign(w),{data:{redirect:true,url:w},error:null}}let g=await h(f("/sign-in/social",s,c,b=>Qe(b,S)),b=>"user"in b);return g.error!==null||g.data===null||"url"in g.data&&g.data.redirect&&!s.disableRedirect&&typeof window<"u"&&window.location.assign(g.data.url),g},sso:async(s,c)=>{if(qt(s)==="first-party"){let{beginCrossSiteSignIn:b}=await import('./session-handoff-6B5KZXQV.js'),w=await b(e,{kind:"sso",email:s.email,providerId:s.providerId,domain:s.domain,organizationSlug:s.organizationSlug,callbackURL:s.callbackURL,errorCallbackURL:s.errorCallbackURL,newUserCallbackURL:s.newUserCallbackURL});if(w)return window.location.assign(w),{data:{url:w,redirect:true},error:null}}let g=await f("/sign-in/sso",s,c,b=>Ze(b,S));return g.error!==null||g.data===null||typeof window<"u"&&window.location.assign(g.data.url),g},magicLink:(s,c)=>f("/sign-in/magic-link",s,c,et),emailOtp:(s,c)=>h(f("/sign-in/email-otp",s,c,$e)),passkey:(s,c)=>d.signIn(s,c)},signUp:{email:(s,c)=>h(f("/sign-up/email",s,c,Ye),g=>g.sessionCreated)},emailOtp:{sendVerificationOtp:(s,c)=>f("/email-otp/send-verification-otp",s,c,tt),verifyEmail:(s,c)=>h(f("/email-otp/verify-email",s,c,at))},phoneOtp:{prepare:s=>f("/phone-otp/challenge",{},s,it),start:(s,c)=>f("/phone-otp/start",{...s,idempotencyKey:s.idempotencyKey??Se()},c,nt),verify:(s,c)=>h(f("/phone-otp/verify",s,c,ot))},requestPasswordReset:(s,c)=>f("/request-password-reset",s,c,ae),resetPassword:(s,c)=>f("/reset-password",s,c,ae),sendVerificationEmail:(s,c)=>f("/send-verification-email",s,c,rt),passkey:{addPasskey:(s,c)=>d.add(s,c),listUserPasskeys:()=>a$1.request("/passkey/list-user-passkeys",{decode:xt}),updatePasskey:async(s,c)=>{let g=W(s.name);if(!g.valid||g.value===void 0)return X();let b=g.value;return f("/passkey/update-passkey",{...s,name:b},c,w=>Dt(w,s.id,b))},deletePasskey:(s,c)=>f("/passkey/delete-passkey",s,c,zt)},twoFactor:{enable:(s,c)=>f("/two-factor/enable",s,c,ut),disable:(s,c)=>h(f("/two-factor/disable",s,c,ct),g=>g.status),verifyTotp:(s,c)=>h(f("/two-factor/verify-totp",s,c,J)),verifyBackupCode:(s,c)=>h(f("/two-factor/verify-backup-code",s,c,J)),sendOtp:(s={},c)=>f("/two-factor/send-otp",s,c,dt),verifyOtp:(s,c)=>h(f("/two-factor/verify-otp",s,c,J)),generateBackupCodes:(s,c)=>f("/two-factor/generate-backup-codes",s,c,lt)},signOut:s=>h(a$1.request("/sign-out",{method:"POST",body:{},fetchOptions:s,decode:st}),c=>c.success)}}function Qi(e,t=()=>{},n){let i=si(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:Vt(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:Vt(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function Vt(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return ui();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?ci():i}}function ui(){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 ci(){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 di(){return {signIn:()=>Ht(),add:()=>Ht()}}function Ht(){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 no(e,t,n){let i=new Map;return {async signIn(o={},a){let r=await e.request("/passkey/generate-authenticate-options");if(!r.data)return jt(r.error);let d;try{d=Pt(r.data);}catch{return Bt()}let u;try{u=await n.authenticate({optionsJSON:d,useBrowserAutofill:o.autoFill});}catch(c){return Jt(n,c,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!li(u))return Kt();let{clientExtensionResults:f,...h}=u,S=i.get(u.id);if(S)return S;let s=(async()=>{let c=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:h},fetchOptions:a,decode:vt});return c.data&&t(),c})();i.set(u.id,s);try{return await s}finally{i.get(u.id)===s&&i.delete(u.id);}},async add(o={},a){let r=W(o.name);if(!r.valid)return X();let d=await e.request("/passkey/generate-register-options",{query:{name:r.value,authenticatorAttachment:o.authenticatorAttachment}});if(!d.data)return jt(d.error);let u;try{u=Tt(d.data);}catch{return Bt()}let f;try{f=await n.register({optionsJSON:u});}catch(c){return Jt(n,c,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!pi(f))return Kt();let{clientExtensionResults:h,...S}=f,s=await e.request("/passkey/verify-registration",{method:"POST",body:{response:S,name:r.value},fetchOptions:a,decode:c=>Ct(c,f.id,r.value)});return s.data&&t(),s}}}function Bt(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function Kt(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function Gt(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 li(e){if(!Gt(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 pi(e){if(!Gt(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function jt(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function Jt(e,t,n,i){let o=fi(t,"page does not have focus"),a=e.errorCode?.(t),r=a!==void 0?a==="ERROR_CEREMONY_ABORTED":gi(t)==="AbortError";return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:o?"PASSKEY_PAGE_NOT_FOCUSED":r?n:a??"PASSKEY_BROWSER_ERROR",message:o?"Keep this page focused while completing the passkey prompt.":r?i:n==="AUTH_CANCELLED"?"Passkey authentication could not be completed by this browser.":"Passkey registration could not be completed by this browser."}}}function gi(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function fi(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}var ge=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 Wt(e,t,n={}){let i=new Headers(n.init?.headers);return i.set("x-publishable-key",e.publishableKey),g({fetchImpl:e.fetch??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 Xt(e,t){if(!e.response.ok)throw new ge(t,e.response,e.requestId);return e.data}async function uo(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return Xt(await Wt(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>mi(i,e)}),"public-config")}function mi(e,t){let n=q$1(e),i=n.environmentId,o=n.environmentType,a=`${new URL(t.apiUrl).origin}/api/projects/${t.decoded.projectId}/auth`;if(typeof n.applicationId!="string"||!hi(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==a)throw v();let r=R(n.branding),d=R(n.legal);if(!fe(n.enabledMethods,64)||!fe(n.socialProviders,64)||!Yt(r,["appName","logoUrl","primaryColor"])||r.showAppName!==void 0&&typeof r.showAppName!="boolean"||r.alignment!==void 0&&r.alignment!=="left"&&r.alignment!=="center"&&r.alignment!=="right"||r.theme!==void 0&&r.theme!=="light"&&r.theme!=="dark"&&r.theme!=="system"||!Yt(d,["termsUrl","privacyUrl"])||!Number.isSafeInteger(d.version)||d.version<0||typeof d.required!="boolean")throw v();if(n.socialProviderClientIds!==void 0){let u=R(n.socialProviderClientIds);if(Object.keys(u).length>64||Object.values(u).some(f=>typeof f!="string"||f.length>2048))throw v()}if(!D(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!$t(n.turnstileSiteKey)||!$t(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 u=R(n.jwtIssuer);if(u.issuer!==a||u.jwksUrl!==`${a}/jwks`||u.aud!==t.decoded.projectId)throw v()}if(n.signUp!==void 0){let u=R(n.signUp).mode;if(typeof u!="string"||!["open","restricted","allowlist","waitlist"].includes(u))throw v()}if(n.authentication!==void 0&&Ai(n.authentication),n.emailVerification!==void 0){let u=R(n.emailVerification);if(!D(u,["required"])||u.method!=="link"&&u.method!=="code")throw v()}if(n.userModel!==void 0&&!D(R(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw v();if(n.mfa!==void 0){let u=R(n.mfa);if(!D(u,["totp","required","backupCodes"])||(u.required===true||u.backupCodes===true)&&u.totp!==true)throw v()}return n}function hi(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 R(e){if(!e||typeof e!="object"||Array.isArray(e))throw v();return e}function $t(e){return e===null||typeof e=="string"&&e.length<=4096}function Ai(e){let t=R(e),n=R(t.email),i=R(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!D(n,["signUp"])||!fe(n.signIn,3)||n.signIn.some(a=>a!=="password"&&a!=="magic_link"&&a!=="email_otp")||!D(R(t.phone),["signUp","signIn"])||!D(i,["signUp","add"])||o&&(!Number.isSafeInteger(i.minLength)||!Number.isSafeInteger(i.maxLength)||i.minLength<1||i.maxLength>4096||i.minLength>i.maxLength)||!D(R(t.passkey),["signIn","add"])||!D(R(t.username),["collectOnSignUp","signIn"]))throw v()}function D(e,t){return t.every(n=>typeof e[n]=="boolean")}function Yt(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function fe(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{yi as a,Qt as b,ke as c,Se as d,si as e,Qi as f,no as g,ge as h,Wt as i,Xt as j,uo as k};
@@ -1,117 +0,0 @@
1
- type DecodedPublishableKey = {
2
- prefix: 'pk_live' | 'pk_test';
3
- env: 'live' | 'test';
4
- projectId: string;
5
- };
6
- declare function decodePublishableKey(key: string): DecodedPublishableKey;
7
-
8
- /**
9
- * The exact session-cookie name the auth server sets for a given project.
10
- *
11
- * Single source of truth for the cookie name across the SDK. The server
12
- * (the AuthOwl server project factory) configures
13
- * `advanced.cookiePrefix = "p_" + <projectId without dashes>` and
14
- * `useSecureCookies` in production; the auth engine then names the session
15
- * cookie `${securePrefix}${cookiePrefix}.session_token`, where `securePrefix`
16
- * is `__Secure-` for secure cookies and empty otherwise:
17
- *
18
- * dev (http): p_<idNoDashes>.session_token
19
- * prod (https): __Secure-p_<idNoDashes>.session_token
20
- *
21
- * Verified 2026-07-06 against the auth engine's `getCookies()` with the server's
22
- * real config (see CONTRACTS section 5 and `cookie.test.ts`). Note the engine
23
- * joins the prefix and name with a dot (`.`), not an underscore, and uses the
24
- * `__Secure-` (not `__Host-`) prefix - both are easy to get wrong by hand, and
25
- * getting them wrong makes `auth()` forward a cookie the server never set. If an
26
- * auth-engine upgrade changes cookie naming, re-verify and update this function,
27
- * the `cookie.test.ts` fixtures, and CONTRACTS section 5 together.
28
- *
29
- * `secure` must reflect the SERVER's cookie mode: callers holding the auth API
30
- * URL derive it from the protocol (`https:` => secure). Callers that cannot
31
- * know it (the UX-only redirect middleware) should check both variants.
32
- */
33
- declare function sessionCookieName(projectId: string, opts?: {
34
- secure?: boolean;
35
- }): string;
36
-
37
- type AuthConfig = {
38
- publishableKey: string;
39
- apiUrl: string;
40
- /** Optional fetch override (e.g. for testing). */
41
- fetch?: typeof fetch;
42
- };
43
- type ResolvedAuthConfig = AuthConfig & {
44
- decoded: DecodedPublishableKey;
45
- /** Fully-resolved base URL pointing at the per-project auth endpoint. */
46
- projectBaseURL: string;
47
- };
48
- declare function resolveConfig(input: AuthConfig): ResolvedAuthConfig;
49
-
50
- /**
51
- * Pure, dependency-free evaluators for an organization membership's advisory
52
- * permission claim. Shared by the CLIENT `has()` (organization-client.ts, over
53
- * the browser session) and the SERVER `has()` (server.ts, over a verified JWT),
54
- * so the two paths can never disagree on what a membership grants.
55
- *
56
- * The membership carries the SAME `permissions` array AuthOwl emits into the
57
- * session and the JWT claim (plan §4/§5): the relabelled `org:sys_*` system ids
58
- * (plus their legacy bare forms during the dual-emit window) AND the operator's
59
- * custom `org:<feature>:<action>` ids. Evaluation is a pure array/string check
60
- * over that local claim - it NEVER calls a statement-only `/organization/has-
61
- * permission` route, which only knows the 14 static statements and would wrongly
62
- * report `false` for any custom permission.
63
- */
64
- /** The active-membership shape carried on the session / decoded from a token. */
65
- interface OrganizationMembership {
66
- /** The member's canonical role key (built-in `owner`/`admin`/`member` or a project role). */
67
- role: string;
68
- /**
69
- * The member's effective permission ids: `org:sys_*` system claims (with
70
- * their legacy bare forms during dual-emit) plus custom `org:<feature>:<action>`
71
- * ids. Advisory only - the real boundary is server-side over the verified token.
72
- */
73
- permissions: string[];
74
- /**
75
- * Team ids the member holds inside the ACTIVE organization, as emitted by
76
- * AuthOwl into both the session and the JWT claim. Teams are pure grouping:
77
- * belonging to one grants nothing on its own, so this is for the application's
78
- * own gating, never an authority check.
79
- *
80
- * Optional because a token minted before teams shipped carries no `teams` claim.
81
- * `has({ teamId })` then returns false rather than guessing - it can only ever
82
- * confirm a team the claim actually proves.
83
- */
84
- teams?: string[];
85
- }
86
- /** Clerk-style `has()` query: match the role, the permission, the team, or a combination (AND). */
87
- interface HasParams {
88
- role?: string;
89
- permission?: string;
90
- /** Require membership of this team within the active organization. */
91
- teamId?: string;
92
- }
93
- /** True when the membership's permission claim includes `permission`. Pure. */
94
- declare function membershipHasPermission(membership: OrganizationMembership | null | undefined, permission: string): boolean;
95
- /**
96
- * True when the membership's team claim includes `teamId`. Pure.
97
- *
98
- * False when the claim carries no `teams` at all, which is what a token minted
99
- * before teams shipped looks like - an absent claim is never read as "any team".
100
- */
101
- declare function membershipHasTeam(membership: OrganizationMembership | null | undefined, teamId: string): boolean;
102
- /**
103
- * Clerk-style `has()`: true when the membership satisfies EVERY provided
104
- * criterion - the role matches AND the permission is included AND the team is
105
- * held. Returns false when there is no membership, or when no criterion at all is
106
- * given. Pure: no I/O, evaluated entirely against the local claim.
107
- */
108
- declare function membershipHas(membership: OrganizationMembership | null | undefined, params: HasParams): boolean;
109
- /** Bind the pure evaluators to one membership (drives the client / hook `has`). */
110
- declare function createMembershipHas(membership: OrganizationMembership | null | undefined): {
111
- has: (params: HasParams) => boolean;
112
- hasPermission: (params: {
113
- permission: string;
114
- }) => boolean;
115
- };
116
-
117
- export { type AuthConfig as A, type DecodedPublishableKey as D, type HasParams as H, type OrganizationMembership as O, type ResolvedAuthConfig as R, membershipHasPermission as a, membershipHasTeam as b, createMembershipHas as c, decodePublishableKey as d, membershipHas as m, resolveConfig as r, sessionCookieName as s };