@authowl/core 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4VJL4WGF.js +1 -0
- package/dist/chunk-RRP2XNYV.js +2 -0
- package/dist/chunk-T5SH3ZZP.js +1 -0
- package/dist/{client-jpaYv3wu.d.ts → client--0Q9VjLt.d.cts} +10 -1
- package/dist/{client-DOOkDLWg.d.cts → client-DwK6spWA.d.ts} +10 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +3 -4
- package/dist/index.d.ts +3 -4
- package/dist/index.js +2 -2
- package/dist/native.cjs +2 -1
- package/dist/native.d.cts +4 -4
- package/dist/native.d.ts +4 -4
- package/dist/native.js +1 -1
- package/dist/organization-membership--eTrgk_L.d.cts +442 -0
- package/dist/organization-membership--eTrgk_L.d.ts +442 -0
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +2 -3
- package/dist/server.d.ts +2 -3
- package/dist/server.js +1 -1
- package/dist/session-handoff-VJI4IXLT.js +2 -0
- package/package.json +2 -1
- package/dist/chunk-KPXCQZUX.js +0 -2
- package/dist/chunk-VZTAYWAD.js +0 -1
- package/dist/organization-membership-B3m6PbmO.d.cts +0 -117
- package/dist/organization-membership-B3m6PbmO.d.ts +0 -117
- package/dist/transport-DcWDTRd4.d.cts +0 -15
- package/dist/transport-DcWDTRd4.d.ts +0 -15
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.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Framework-agnostic client for AuthOwl, the multi-tenant auth SaaS.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -76,6 +76,7 @@
|
|
|
76
76
|
"@akedly/shield": "1.0.2"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
|
+
"jsdom": "26.1.0",
|
|
79
80
|
"tsup": "^8.3.5",
|
|
80
81
|
"typescript": "^5.7.2",
|
|
81
82
|
"vitest": "^4.1.10"
|
package/dist/chunk-KPXCQZUX.js
DELETED
|
@@ -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};
|
package/dist/chunk-VZTAYWAD.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {f,g,q as q$1,j as j$1,h,p,i,n,s,u,o,k as k$1,r,m as m$1,l}from'./chunk-KPXCQZUX.js';function gi(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 Xt="x-authowl-turnstile-token",$t=1e4,Yt=32,Qt=2e4;function E(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 we(e,t=e.projectBaseURL){return {async request(n,i={}){let o=tn(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(Xt,i.fetchOptions.authChallengeToken),i.body!==void 0&&r.set("content-type","application/json");let s={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 b=en(a,i.fetchOptions),c;try{c=await Zt(e,o,{...s,signal:i.fetchOptions?.signal},b);}catch(D){let fe=be(D);return await i.fetchOptions?.onError?.(Z(u,fe,rn(D))),{data:null,error:fe}}let{response:l,requestId:g}=c,f$1=un(n,c.data),w=f$1;if(l.ok)try{w=te(f$1),i.decode&&(w=i.decode(w));}catch{let D=be(new f("invalid_response",g));return await i.fetchOptions?.onError?.(Z(u,D,"invalid_response")),{data:null,error:D}}let L=Object.freeze({...u,status:l.status,...g===void 0?{}:{requestId:g}});if(await i.fetchOptions?.onResponse?.(L),!l.ok){let D=nn(l,f$1,g);return await i.fetchOptions?.onError?.(Z(u,D,"api")),{data:null,error:D}}return await i.fetchOptions?.onSuccess?.(L),{data:w,error:null}}}}async function Zt(e,t,n,i){let o=Date.now()+$t;for(let a=0;a<i;a+=1){let r=o-Date.now();if(r<=0)throw new f("timeout");try{let s=await g({fetchImpl:e.fetch??fetch,url:t,init:n,timeoutMs:Math.max(1,Math.ceil(r)),allowHttpLoopback:e.decoded.env==="test"});if(s.response.status<500||a===i-1)return s}catch(s){if(a===i-1||!(s instanceof f)||s.kind!=="network")throw s}await an(50*2**a,n.signal,o);}throw new f("network")}function en(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 tn(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 nn(e,t,n){let i=F(t)?t:{},o=on(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 on(e,t){let n=(typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?e.retryAfterSeconds:void 0)??Oe(t.get("retry-after"))??Oe(t.get("x-retry-after"));if(n!==void 0)return Math.min(Math.max(Math.trunc(n),1),86400)}function Oe(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 be(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 Z(e,t,n){return Object.freeze({...e,status:t.status??0,...t.requestId===void 0?{}:{requestId:t.requestId},failure:n})}function rn(e){return e instanceof f?e.kind:"network"}function an(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),s=()=>{clearTimeout(u),o(new f("aborted"));},u=setTimeout(()=>{t?.removeEventListener("abort",s),Date.now()>=n?o(new f("timeout")):i();},r);t?.addEventListener("abort",s,{once:true}),t?.aborted&&s();})}function te(e,t="",n=0,i={nodes:0}){if(i.nodes+=1,n>Yt||i.nodes>Qt)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=>te(o,"",n+1,i)):F(e)?Object.fromEntries(Object.entries(e).map(([o,a])=>[o,sn(o)?a:te(a,o,n+1,i)])):e}function sn(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function un(e,t){if(e==="/list-sessions"&&Array.isArray(t))return t.map(o=>F(o)?ee(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-")?ee(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:ee(i.session)}),i}function ee(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 ke(){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,s=f=>{c(f);};r={data:null,isPending:true,isRefetching:false,error:null,refetch:s};function u(f){r=f;for(let w of n)w();}async function b(f){return e.request("/get-session",{query:f?.query,decode:Se})}async function c(f){a?.abort();let w=new AbortController;a=w,u({...r,isPending:r.data===null&&r.error===null,isRefetching:r.data!==null});let L=await e.request("/get-session",{query:f?.query,fetchOptions:{signal:w.signal},decode:Se});a===w&&(a=null,u({data:L.data,error:L.error,isPending:false,isRefetching:false,refetch:s}));}function l(){if(typeof window>"u"||o)return;let f=()=>{c();},w=()=>{document.visibilityState==="visible"&&c();};window.addEventListener("focus",f),document.addEventListener("visibilitychange",w),typeof BroadcastChannel<"u"&&(i=new BroadcastChannel(`authowl:${t}`),i.addEventListener("message",f)),o=()=>{window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",w),i?.close(),i=null,o=null;};}function g(f){return n.add(f),n.size===1&&(l(),c()),()=>{n.delete(f),n.size===0&&(a?.abort(),a=null,o?.());}}return {store:{subscribe:g,getSnapshot:()=>r},getSession:b,notifyMutation(){i?.postMessage({type:"session-changed"}),n.size>0&&c({query:{disableCookieCache:true}});}}}function Se(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 Re(e,t){return e.request("/user/metadata",{fetchOptions:t,decode:Pe})}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:Pe})}function Pe(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}=E(e,t);return {getMetadata:o=>Re(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,cn)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:dn}),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:ln});if(!a.data)return {data:null,error:a.error};let r=a.data.length>1;return {...a,data:a.data.filter(s=>s.providerId!=="credential").map(s=>({...s,canUnlink:r}))}},linkSocial:(o,a)=>n("/link-social",o,a,pn),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,q)),delete:(o={},a)=>i(n("/delete-user",o,a,gn))}}function q(e){let t=h(e);return {status:j$1(t.status)}}function cn(e){let t=h(e);return {user:n(t.user)}}function dn(e){return Array.isArray(e)||p(),e.map(t=>{let n=h(t);return {id:i(n.id),userId:i(n.userId),createdAt:k$1(n.createdAt),updatedAt:k$1(n.updatedAt),expiresAt:k$1(n.expiresAt),...ve("ipAddress",m$1(n,"ipAddress")),...ve("userAgent",m$1(n,"userAgent"))}})}function ln(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$1(n.createdAt),updatedAt:k$1(n.updatedAt)}})}function pn(e){let t=h(e);return {url:i(t.url),redirect:j$1(t.redirect)}}function gn(e){let t=h(e);return {success:j$1(t.success),message:i(t.message)}}function ve(e,t){return t===void 0?{}:{[e]:t}}var fn=new Set(["pending","accepted","rejected","canceled"]),De=1e4;function N(e,t,n){let i=h(e),o={id:m(i.id),name:m(i.name),slug:m(i.slug),createdAt:k$1(i.createdAt),...B("logo",m$1(i,"logo")),...B("metadata",i.metadata===void 0?void 0:r(i.metadata))};return z(o.id,t),z(o.slug,n),o}function ze(e){return C(e,N)}function ne(e,t,n){return e===null?null:(t===null&&p(),N(e,t,n))}function Ce(e,t,n){if(e===null)return null;let i=h(e),o=N(i,t,n);return {...o,members:C(i.members,a=>je(a,o.id)),invitations:C(i.invitations,a=>v(a,void 0,o.id))}}function Ee(e,t){let n=C(e,i=>Be(i));return j(n.map(i=>i.organizationId),t),n}function Ne(e,t,n){return e===null?null:(t===null&&p(),Be(e,t,n))}function Ue(e,t){let n=h(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&p(),{members:mn(n.members,t),total:n.total}}function v(e,t,n){let i=h(e),o=m(i.status);fn.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$1(i.expiresAt),createdAt:k$1(i.createdAt)};return z(a.id,t),z(a.organizationId,n),a}function Me(e,t){let n=C(e,i=>v(i));return j(n.map(i=>i.organizationId),t),n}function _e(e){return C(e,t=>{let n=h(t);return {...v(n),organizationName:m(n.organizationName)}})}function Le(e,t){let n=h(e);return {...v(n,t),organizationName:m(n.organizationName),organizationSlug:m(n.organizationSlug),inviterEmail:m(n.inviterEmail)}}function Fe(e,t){let n=h(e),i=v(n.invitation,t);return {invitation:i,member:U(n.member,void 0,i.organizationId)}}function qe(e,t){let n=h(e);return n.member!==null&&p(),{invitation:n.invitation===null?null:v(n.invitation,t),member:null}}function Ve(e,t){return e===null?null:v(e,t)}function He(e,t,n){let i=h(e);return {member:U(i.member,n,t)}}function U(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$1(i.createdAt),...i.user===void 0?{}:{user:Je(i.user)}};return z(o.id,t),z(o.organizationId,n),o}function Ke(e,t){let n=C(e,i=>{let o=h(i);return {organizationId:m(o.organizationId),data:{role:m(o.role),...B("permission",o.permission===void 0?void 0:hn(o.permission))}}});return j(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function Be(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$1(i.createdAt),...o===void 0?{}:{updatedAt:k$1(o)}};return z(a.id,t),z(a.organizationId,n),a}function je(e,t){let n=h(e);return {...U(n,void 0,t),user:Je(n.user)}}function mn(e,t){let n=C(e,i=>je(i));return j(n.map(i=>i.organizationId),t),n}function hn(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 Je(e){let t=h(e);return {id:m(t.id),name:m(t.name),email:m(t.email),...B("image",m$1(t,"image"))}}function C(e,t){return Array.isArray(e)||p(),e.map(n=>t(n))}function B(e,t){return t===void 0?{}:{[e]:t}}function Ge(e,t,n=()=>null){let{post:i,mutation:o}=E(e,t),a=(r,s,u,b)=>e.request(r,{query:s,fetchOptions:u,decode:b});return {create:(r,s)=>o(i("/organization/create",r,s,N)),list:r=>a("/organization/list",void 0,r,ze),get:(r={},s)=>a("/organization/get-full-organization",{organizationId:r.organizationId,organizationSlug:r.organizationSlug,membersLimit:r.membersLimit},s,u=>Ce(u,r.organizationId,r.organizationSlug)),setActive:(r,s)=>o(i("/organization/set-active",r,s,u=>ne(u,r.organizationId,r.organizationSlug))),listTeams:(r={},s)=>a("/organization/list-teams",{organizationId:r.organizationId},s,u=>Ee(u,r.organizationId)),setActiveTeam:(r,s)=>o(i("/organization/set-active-team",r,s,u=>Ne(u,r.teamId))),update:(r,s)=>o(i("/organization/update",r,s,u=>ne(u,r.organizationId))),delete:(r,s)=>o(i("/organization/delete",r,s,u=>N(u,r.organizationId))),listMembers:(r={},s)=>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},s,u=>Ue(u,r.organizationId)),inviteMember:(r,s)=>o(i("/organization/invite-member",r,s,u=>v(u,void 0,r.organizationId))),listInvitations:(r={},s)=>a("/organization/list-invitations",{organizationId:r.organizationId},s,u=>Me(u,r.organizationId)),listUserInvitations:r=>a("/organization/list-user-invitations",void 0,r,_e),getInvitation:(r,s)=>a("/organization/get-invitation",{id:r.id},s,u=>Le(u,r.id)),acceptInvitation:(r,s)=>o(i("/organization/accept-invitation",r,s,u=>Fe(u,r.invitationId))),rejectInvitation:(r,s)=>o(i("/organization/reject-invitation",r,s,u=>qe(u,r.invitationId))),cancelInvitation:(r,s)=>o(i("/organization/cancel-invitation",r,s,u=>Ve(u,r.invitationId))),removeMember:(r,s)=>o(i("/organization/remove-member",r,s,u=>He(u,r.organizationId,r.memberIdOrEmail.includes("@")?void 0:r.memberIdOrEmail))),updateMemberRole:(r,s)=>o(i("/organization/update-member-role",r,s,u=>U(u,r.memberId,r.organizationId))),leave:(r,s)=>o(i("/organization/leave",r,s,u=>U(u,void 0,r.organizationId))),listRoles:(r={},s)=>a("/organization/list-roles",{organizationId:r.organizationId},s,u=>Ke(u,r.organizationId)),has:r=>u(n(),r),hasPermission:r=>s(n(),r.permission)}}var We=4096,An=4096,yn=100,On=256,bn=16,wn=64,kn=12;function oe(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:pt(t.twoFactorMethods,bn,wn)}}):(t.twoFactorRedirect!==void 0&&p(),{redirect:j$1(t.redirect),...Pn(t,"url"),user:n(t.user)})}function Xe(e){let t=h(e);return {user:n(t.user)}}function $e(e){let t=h(e);return {sessionCreated:j$1(t.sessionCreated),user:n(t.user)}}function Ye(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:ie(n$1.url,t)}):(o===a&&p(),o?{redirect:false,user:n(n$1.user)}:{redirect:false,url:ie(n$1.url,t)})}function Qe(e,t){let n=h(e);return (n.redirect!==true||n.user!==void 0)&&p(),{redirect:true,url:ie(n.url,t)}}function Ze(e){return {status:j$1(h(e).status)}}function et(e){return {success:j$1(h(e).success)}}function tt(e){return h(e).status!=="pending"&&p(),{status:"pending"}}function nt(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:Sn(t.difficulty),challengeToken:i(t.challengeToken),challengeRequired:j$1(t.challengeRequired),turnstile:{required:j$1(n.required),siteKey:i$1}}}function Sn(e){return (!Number.isSafeInteger(e)||Number(e)<0||Number(e)>kn)&&p(),Number(e)}function it(e){let t=h(e);return (t.status!==true||t.sessionCreated!==true)&&p(),{status:true,sessionCreated:true,user:In(t.user)}}function re(e){return {status:j$1(h(e).status)}}function ot(e){return {status:j$1(h(e).status)}}function rt(e){let t=h(e);return {status:j$1(t.status),user:n(t.user)}}function at(e){return {success:j$1(h(e).success)}}function st(e){let t=h(e);return {totpURI:Tn(t.totpURI),backupCodes:lt(t.backupCodes)}}function ut(e){return {status:j$1(h(e).status)}}function J(e){return h(e).status!==true&&p(),{status:true}}function ct(e){return {status:j$1(h(e).status)}}function dt(e){let t=h(e);return t.status!==void 0&&t.status!==true&&p(),{backupCodes:lt(t.backupCodes)}}function In(e){let t=h(e);return {id:M(t.id,512),...vn(t,"name",1024),phoneNumber:M(t.phoneNumber,64),phoneNumberVerified:j$1(t.phoneNumberVerified),...t.createdAt===void 0?{}:{createdAt:k$1(t.createdAt)},...t.updatedAt===void 0?{}:{updatedAt:k$1(t.updatedAt)}}}function ie(e,t){let n=M(e,We);/[\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:"&&Rn(i.hostname)?i.href:p()}function Rn(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Tn(e){let t=M(e,An),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 lt(e){return pt(e,yn,On)}function pt(e,t,n){(!Array.isArray(e)||e.length===0||e.length>t)&&p();let i=e.map(o=>M(o,n));return i.some(o=>o.trim().length===0)&&p(),new Set(i).size!==i.length&&p(),i}function M(e,t){let n=i(e);return (n.length===0||n.length>t)&&p(),n}function Pn(e,t){let n=e[t];return n==null?{}:{[t]:M(n,We)}}function vn(e,t,n){let i=m$1(e,t);return i===void 0?{}:(i!==null&&i.length>n&&p(),{[t]:i})}var gt=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||mt(n,i)||ft(i)||gt.has(i))return {valid:false}}let t=xn(e);return ae(t)?{valid:true,value:t}:{valid:false}}function ae(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||mt(o,a)||ft(a)||gt.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 xn(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 ft(e){return e>=0&&e<=31||e>=127&&e<=159}function mt(e,t){return e.length===1&&t>=55296&&t<=57343}var yt=12,Ot=5e3,Dn=8,zn=1e3,Cn=16,ht=512,bt=100,wt=8192,En=32768,se=1024,At=256,ce=64,Nn=6e5,Un=/^[A-Za-z0-9_-]+$/u,Mn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,_n=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,Ln=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,Fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,kt=new Set(["discouraged","preferred","required"]),qn=new Set(["singleDevice","multiDevice"]),St=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),It=new Set(["hybrid","security-key","client-device"]),Vn=new Set(["none","indirect","direct","enterprise"]),Hn=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),Kn=new Set(["platform","cross-platform"]),Bn=new Set(["discouraged","preferred","required"]),jn=new Set([-8,-7,-257]);function Rt(e){let t=q$1(e,yt,Ot);return {challenge:Ut(t.challenge),...y("timeout",Et(t.timeout)),...y("rpId",Mt(t.rpId)),...y("allowCredentials",Ct(t.allowCredentials)),...y("userVerification",V(t.userVerification,kt)),...y("hints",$(t.hints,It)),...y("extensions",Nt(t.extensions))}}function Tt(e){let t=q$1(e,yt,Ot);return {challenge:Ut(t.challenge),rp:Jn(t.rp),user:Gn(t.user),pubKeyCredParams:Wn(t.pubKeyCredParams),...y("timeout",Et(t.timeout)),...y("excludeCredentials",Ct(t.excludeCredentials)),...y("authenticatorSelection",Xn(t.authenticatorSelection)),...y("attestation",V(t.attestation,Vn)),...y("attestationFormats",$(t.attestationFormats,Hn)),...y("hints",$(t.hints,It)),...y("extensions",Nt(t.extensions))}}function Pt(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 de(e){let t=h(e),n=t.counter;(!Number.isSafeInteger(n)||n<0)&&p();let i=le(t.deviceType,qn),o=j$1(t.backedUp);return o&&i!=="multiDevice"&&p(),{id:_(t.id,At),...Qn(t),publicKey:$n(t.publicKey,En),userId:_(t.userId,At),credentialID:Q(t.credentialID,wt),counter:n,deviceType:i,backedUp:o,...Zn(t),createdAt:k$1(t.createdAt),...ei(t)}}function vt(e,t,n){let i=de(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>bt)&&p();let t=e.map(de);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=de(i.passkey);return (o.id!==t||o.name!==n)&&p(),{passkey:o}}function zt(e){return h(e).status!==true&&p(),{status:true}}function Jn(e){let t=h(e);return {name:ue(t.name,se),...y("id",Mt(t.id))}}function Gn(e){let t=h(e);return {id:Q(t.id,128,1,64),name:ue(t.name,se),displayName:ue(t.displayName,se)}}function Wn(e){(!Array.isArray(e)||e.length===0||e.length>ce)&&p();let t=e.map(n=>{let i=h(n);return (i.type!=="public-key"||!Number.isSafeInteger(i.alg)||!jn.has(i.alg))&&p(),{type:"public-key",alg:i.alg}});return ti(t.map(n=>n.alg)),t}function Ct(e){if(e===void 0)return;(!Array.isArray(e)||e.length>bt)&&p();let t=e.map(n=>{let i=h(n);return i.type!=="public-key"&&p(),{type:"public-key",id:Q(i.id,wt),...y("transports",$(i.transports,St))}});return Y(t.map(n=>n.id)),t}function Xn(e){if(e===void 0)return;let t=h(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&p();let n=V(t.residentKey,Bn);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&p(),{...y("authenticatorAttachment",V(t.authenticatorAttachment,Kn)),...y("residentKey",n),...y("requireResidentKey",t.requireResidentKey),...y("userVerification",V(t.userVerification,kt))}}function Et(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>Nn)&&p(),e}function Nt(e){return e===void 0?void 0:q$1(e,Dn,zn)}function $(e,t){if(e===void 0)return;(!Array.isArray(e)||e.length>ce)&&p();let n=e.map(i=>le(i,t));return Y(n),n}function V(e,t){if(e!==void 0)return le(e,t)}function Ut(e){return Q(e,Math.ceil(ht*4/3),Cn,ht)}function Q(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=_(e,t),a=o.length%4,r=Yn(o.at(-1)??""),s=Math.floor(o.length*3/4);return (!Un.test(o)||a===1||a===2&&(r&15)!==0||a===3&&(r&3)!==0||s<n||s>i)&&p(),o}function _(e,t){let n=i(e);return (n.length===0||n.length>t)&&p(),n}function ue(e,t){let n=_(e,t);return _n.test(n)&&p(),n}function Mt(e){if(e===void 0)return;let t=_(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!Ln.test(n)))&&p(),t}function $n(e,t){let n=_(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",r=_t(a);return (n.length%4!==0||!Mn.test(n)||i&&(r&15)!==0||o&&(r&3)!==0)&&p(),n}function Yn(e){return _t(e,true)}function _t(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function Qn(e){let t=m$1(e,"name");return t===void 0?{}:(t!==null&&!ae(t)&&p(),{name:t})}function Zn(e){let t=m$1(e,"transports");if(t==null||t==="")return t===void 0?{}:{transports:t};let n=t.split(",");return (n.length>ce||n.some(i=>!St.has(i))||new Set(n).size!==n.length)&&p(),{transports:t}}function ei(e){let t=m$1(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(Fn.test(t)||p(),{aaguid:t})}function le(e,t){let n=i(e);return t.has(n)||p(),n}function y(e,t){return t===void 0?{}:{[e]:t}}function Y(e){new Set(e).size!==e.length&&p();}function ti(e){new Set(e).size!==e.length&&p();}function ni(e,t=()=>{},n=ri){let i=we(e),o=Ie(i,e.decoded.projectId),a=n(i,o.notifyMutation),r=()=>{o.notifyMutation(),t();},{post:s,mutation:u}=E(i,r),b=e.decoded.env==="test";return {sessionStore:o.store,getSession:o.getSession,account:xe(i,r),organization:Ge(i,r,()=>o.store.getSnapshot().data?.session.membership??null),signIn:{email:(c,l)=>u(s("/sign-in/email",c,l,oe),g=>!("twoFactorRedirect"in g)),username:(c,l)=>u(s("/sign-in/username",c,l,oe),g=>!("twoFactorRedirect"in g)),social:async(c,l)=>{let g=await u(s("/sign-in/social",c,l,f=>Ye(f,b)),f=>"user"in f);return g.error!==null||g.data===null||"url"in g.data&&g.data.redirect&&!c.disableRedirect&&typeof window<"u"&&window.location.assign(g.data.url),g},sso:async(c,l)=>{let g=await s("/sign-in/sso",c,l,f=>Qe(f,b));return g.error!==null||g.data===null||typeof window<"u"&&window.location.assign(g.data.url),g},magicLink:(c,l)=>s("/sign-in/magic-link",c,l,Ze),emailOtp:(c,l)=>u(s("/sign-in/email-otp",c,l,Xe)),passkey:(c,l)=>a.signIn(c,l)},signUp:{email:(c,l)=>u(s("/sign-up/email",c,l,$e),g=>g.sessionCreated)},emailOtp:{sendVerificationOtp:(c,l)=>s("/email-otp/send-verification-otp",c,l,et),verifyEmail:(c,l)=>u(s("/email-otp/verify-email",c,l,rt))},phoneOtp:{prepare:c=>s("/phone-otp/challenge",{},c,nt),start:(c,l)=>s("/phone-otp/start",{...c,idempotencyKey:c.idempotencyKey??ke()},l,tt),verify:(c,l)=>u(s("/phone-otp/verify",c,l,it))},requestPasswordReset:(c,l)=>s("/request-password-reset",c,l,re),resetPassword:(c,l)=>s("/reset-password",c,l,re),sendVerificationEmail:(c,l)=>s("/send-verification-email",c,l,ot),passkey:{addPasskey:(c,l)=>a.add(c,l),listUserPasskeys:()=>i.request("/passkey/list-user-passkeys",{decode:xt}),updatePasskey:async(c,l)=>{let g=W(c.name);if(!g.valid||g.value===void 0)return X();let f=g.value;return s("/passkey/update-passkey",{...c,name:f},l,w=>Dt(w,c.id,f))},deletePasskey:(c,l)=>s("/passkey/delete-passkey",c,l,zt)},twoFactor:{enable:(c,l)=>s("/two-factor/enable",c,l,st),disable:(c,l)=>u(s("/two-factor/disable",c,l,ut),g=>g.status),verifyTotp:(c,l)=>u(s("/two-factor/verify-totp",c,l,J)),verifyBackupCode:(c,l)=>u(s("/two-factor/verify-backup-code",c,l,J)),sendOtp:(c={},l)=>s("/two-factor/send-otp",c,l,ct),verifyOtp:(c,l)=>u(s("/two-factor/verify-otp",c,l,J)),generateBackupCodes:(c,l)=>s("/two-factor/generate-backup-codes",c,l,dt)},signOut:c=>u(i.request("/sign-out",{method:"POST",body:{},fetchOptions:c,decode:at}),l=>l.success)}}function Ji(e,t=()=>{},n){let i=ni(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:Lt(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:Lt(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function Lt(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return ii();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?oi():i}}function ii(){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 oi(){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 ri(){return {signIn:()=>Ft(),add:()=>Ft()}}function Ft(){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 $i(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 Ht(r.error);let s;try{s=Rt(r.data);}catch{return qt()}let u;try{u=await n.authenticate({optionsJSON:s,useBrowserAutofill:o.autoFill});}catch(f){return Kt(n,f,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!ai(u))return Vt();let{clientExtensionResults:b,...c}=u,l=i.get(u.id);if(l)return l;let g=(async()=>{let f=await e.request("/passkey/verify-authentication",{method:"POST",body:{response:c},fetchOptions:a,decode:Pt});return f.data&&t(),f})();i.set(u.id,g);try{return await g}finally{i.get(u.id)===g&&i.delete(u.id);}},async add(o={},a){let r=W(o.name);if(!r.valid)return X();let s=await e.request("/passkey/generate-register-options",{query:{name:r.value,authenticatorAttachment:o.authenticatorAttachment}});if(!s.data)return Ht(s.error);let u;try{u=Tt(s.data);}catch{return qt()}let b;try{b=await n.register({optionsJSON:u});}catch(f){return Kt(n,f,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!si(b))return Vt();let{clientExtensionResults:c,...l}=b,g=await e.request("/passkey/verify-registration",{method:"POST",body:{response:l,name:r.value},fetchOptions:a,decode:f=>vt(f,b.id,r.value)});return g.data&&t(),g}}}function qt(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function Vt(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function Bt(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 ai(e){if(!Bt(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.authenticatorData=="string"&&typeof t.signature=="string"&&(t.userHandle===void 0||typeof t.userHandle=="string")}function si(e){if(!Bt(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function Ht(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function Kt(e,t,n,i){let o=ci(t,"page does not have focus"),a=e.errorCode?.(t),r=a!==void 0?a==="ERROR_CEREMONY_ABORTED":ui(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 ui(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function ci(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 pe=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 jt(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 Jt(e,t){if(!e.response.ok)throw new pe(t,e.response,e.requestId);return e.data}async function no(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return Jt(await jt(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>di(i,e)}),"public-config")}function di(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"||!li(n.applicationId)||i!==t.decoded.projectId||o!=="development"&&o!=="production"||n.authBaseUrl!==a)throw T();let r=k(n.branding),s=k(n.legal);if(!ge(n.enabledMethods,64)||!ge(n.socialProviders,64)||!Wt(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"||!Wt(s,["termsUrl","privacyUrl"])||!Number.isSafeInteger(s.version)||s.version<0||typeof s.required!="boolean")throw T();if(n.socialProviderClientIds!==void 0){let u=k(n.socialProviderClientIds);if(Object.keys(u).length>64||Object.values(u).some(b=>typeof b!="string"||b.length>2048))throw T()}if(!x(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!Gt(n.turnstileSiteKey)||!Gt(n.authTurnstileSiteKey)||typeof n.locale!="string"||n.locale.length===0||n.locale.length>64||!Number.isSafeInteger(n.configVersion)||n.configVersion<0)throw T();if(n.jwtIssuer!==null){let u=k(n.jwtIssuer);if(u.issuer!==a||u.jwksUrl!==`${a}/jwks`||u.aud!==t.decoded.projectId)throw T()}if(n.signUp!==void 0){let u=k(n.signUp).mode;if(typeof u!="string"||!["open","restricted","allowlist","waitlist"].includes(u))throw T()}if(n.authentication!==void 0&&pi(n.authentication),n.emailVerification!==void 0){let u=k(n.emailVerification);if(!x(u,["required"])||u.method!=="link"&&u.method!=="code")throw T()}if(n.userModel!==void 0&&!x(k(n.userModel),["requireEmail","firstLastName","emailChange","accountDeletion"]))throw T();if(n.mfa!==void 0){let u=k(n.mfa);if(!x(u,["totp","required","backupCodes"])||(u.required===true||u.backupCodes===true)&&u.totp!==true)throw T()}return n}function li(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 T(){return new TypeError("public-config returned an invalid response")}function k(e){if(!e||typeof e!="object"||Array.isArray(e))throw T();return e}function Gt(e){return e===null||typeof e=="string"&&e.length<=4096}function pi(e){let t=k(e),n=k(t.email),i=k(t.password),o=i.minLength!==void 0||i.maxLength!==void 0;if(!x(n,["signUp"])||!ge(n.signIn,3)||n.signIn.some(a=>a!=="password"&&a!=="magic_link"&&a!=="email_otp")||!x(k(t.phone),["signUp","signIn"])||!x(i,["signUp","add"])||o&&(!Number.isSafeInteger(i.minLength)||!Number.isSafeInteger(i.maxLength)||i.minLength<1||i.maxLength>4096||i.minLength>i.maxLength)||!x(k(t.passkey),["signIn","add"])||!x(k(t.username),["collectOnSignUp","signIn"]))throw T()}function x(e,t){return t.every(n=>typeof e[n]=="boolean")}function Wt(e,t){return t.every(n=>e[n]===void 0||typeof e[n]=="string"&&e[n].length<=4096)}function ge(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{gi as a,Xt as b,we as c,ke as d,ni as e,Ji as f,$i as g,pe as h,jt as i,Jt as j,no 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 };
|