@authowl/core 0.12.0 → 0.14.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/README.md +3 -2
- package/dist/chunk-MX7KKUAW.js +1 -0
- package/dist/chunk-T5SH3ZZP.js +1 -0
- package/dist/{client-1cjryEHU.d.cts → client-DOOkDLWg.d.cts} +31 -3
- package/dist/{client-CzV2XWt6.d.ts → client-jpaYv3wu.d.ts} +31 -3
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +11 -2
- package/dist/index.d.ts +11 -2
- package/dist/index.js +3 -3
- package/dist/messages.cjs +1 -1
- package/dist/messages.d.cts +1 -0
- package/dist/messages.d.ts +1 -0
- package/dist/messages.js +1 -1
- package/dist/native.cjs +2 -1
- package/dist/native.d.cts +2 -2
- package/dist/native.d.ts +2 -2
- package/dist/native.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +894 -52
- package/dist/server.d.ts +894 -52
- package/dist/server.js +1 -1
- package/dist/session-handoff-6B5KZXQV.js +2 -0
- package/package.json +5 -1
- package/dist/chunk-SM5LS47O.js +0 -1
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,c,u,s,g as g$1,f,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,n="TOKEN_VERIFICATION_FAILED"){super(t),this.name="TokenVerificationError",this.code=n;}},X=300*1e3,Z=5e3,Q=64*1024,ee=64,te=60*1e3,W=new Map,$=new Map;function j(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?t:t+"=".repeat(4-t.length%4),r=typeof atob=="function"?atob(n):globalThis.Buffer.from(n,"base64").toString("binary"),s=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)s[o]=r.charCodeAt(o);return s}function D(e){try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");let t=new TextDecoder().decode(j(e)),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new i("Malformed JWT segment.","TOKEN_MALFORMED");return n}catch(t){throw t instanceof i?t:new i("Malformed JWT segment.","TOKEN_MALFORMED")}}function q(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function J(e){return typeof e=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e)&&j(e).byteLength===32}function ne(e){if(!q(e))throw new i("JWKS contains a non-object key.","JWKS_KEY_INVALID");let t=new Set(["alg","crv","kid","kty","use","x","y"]),n=["d","p","q","dp","dq","qi","k","oth"];if("key_ops"in e||n.some(r=>r in e)||Object.keys(e).some(r=>!t.has(r)))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 re(e){if(!q(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(ne),n=new Set;for(let r of t){if(n.has(r.kid))throw new i("JWKS response contains duplicate kid values.","JWKS_DUPLICATE_KID");n.add(r.kid);}return t}async function V(e,t){let n=W.get(e);if(!t&&n&&Date.now()-n.fetchedAt<X)return n.keys;try{let r=await g$1({fetchImpl:fetch,url:e,init:{headers:{accept:"application/json"}},timeoutMs:Z,maxResponseBytes:Q,allowHttpLoopback:new URL(e).protocol==="http:",decode:o=>q$1(o)});if(!r.response.ok)throw new i(`JWKS fetch returned ${r.response.status}.`,"JWKS_HTTP_ERROR");let s=re(r.data);return W.set(e,{keys:s,fetchedAt:Date.now()}),s}catch(r){if(r instanceof i)throw r;if(r instanceof f)switch(r.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 n=s=>t?s.find(o=>o.kid===t):s[0],r=n(await V(e,false));if(!r){let s=$.get(e)??0;Date.now()-s>=te&&($.set(e,Date.now()),r=n(await V(e,true)));}if(!r)throw new i("No matching JWKS key for the token kid.","JWKS_KEY_NOT_FOUND");return r}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 n=t,r=typeof n.role=="string"?n.role:"",s=Array.isArray(n.permissions)?n.permissions.filter(a=>typeof a=="string"):[],o=Array.isArray(n.teams)?n.teams.filter(a=>typeof a=="string"):void 0;return r===""&&s.length===0&&!o?.length?null:{role:r,permissions:s,...o===void 0?{}:{teams:o}}}async function pe(e,t){return _(e,I(t))}function I(e,t=false){if(!e||typeof e!="object")throw new i("Token verification options are required.","TOKEN_CONFIG_INVALID");let n;try{n=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,...n}}async function _(e,t){if(typeof e!="string"||e.length===0)throw new i("A token string is required.","TOKEN_MALFORMED");let n=e.split(".");if(n.length!==3)throw new i("Malformed JWT.","TOKEN_MALFORMED");let[r,s,o]=n,a=D(r);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),d;try{d=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=j(o),m.byteLength!==64)throw new Error("invalid signature length")}catch{throw new i("Malformed JWT signature.","TOKEN_MALFORMED")}let y=new TextEncoder().encode(`${r}.${s}`),f;try{f=await globalThis.crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,m,y);}catch{throw new i("Token signature verification failed.","TOKEN_SIGNATURE_INVALID")}if(!f)throw new i("Invalid token signature.","TOKEN_SIGNATURE_INVALID");let c=D(s),l=t.clockToleranceSeconds??60,h=Math.floor(Date.now()/1e3);if(typeof c.exp!="number")throw new i("Token is missing a valid exp claim.","TOKEN_CLAIM_INVALID");if(c.exp+l<h)throw new i("Token has expired.","TOKEN_CLAIM_INVALID");if(typeof c.nbf=="number"&&c.nbf-l>h)throw new i("Token is not yet valid.","TOKEN_CLAIM_INVALID");if(typeof c.iss!="string"||c.iss!==t.issuer)throw new i("Token issuer missing or mismatched.","TOKEN_CLAIM_INVALID");if(!ie(c.aud,t.audience))throw new i("Token audience mismatch.","TOKEN_CLAIM_INVALID");return {sub:typeof c.sub=="string"?c.sub:null,membership:ae(c),claims:c}}var ce="dc1953d9d9b9e1f7002fa045f12788280e5865bacfda94b1d133e9580aa87d62",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"}}},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}},listEvents:{method:"GET",path:"/events",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/EventPage"}}},getStatsOverview:{method:"GET",path:"/stats/overview",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/StatsOverview"}}},listWebhookEndpoints:{method:"GET",path:"/webhooks",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookPage"}}},createWebhookEndpoint:{method:"POST",path:"/webhooks",successStatuses:[201],responseSchemas:{201:{$ref:"#/components/schemas/WebhookWithSecret"}}},getWebhookEndpoint:{method:"GET",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},updateWebhookEndpoint:{method:"PATCH",path:"/webhooks/{webhookId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},deleteWebhookEndpoint:{method:"DELETE",path:"/webhooks/{webhookId}",successStatuses:[204],responseSchemas:{204:null}},rotateWebhookSecret:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookSecret"}}},pauseWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/pause",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},resumeWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/resume",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookEndpoint"}}},testWebhookEndpoint:{method:"POST",path:"/webhooks/{webhookId}/test",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}},listWebhookDeliveries:{method:"GET",path:"/webhook-deliveries",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/DeliveryPage"}}},getWebhookDelivery:{method:"GET",path:"/webhook-deliveries/{deliveryId}",successStatuses:[200],responseSchemas:{200:{$ref:"#/components/schemas/WebhookDelivery"}}},replayWebhookDelivery:{method:"POST",path:"/webhook-deliveries/{deliveryId}/replay",successStatuses:[202],responseSchemas:{202:{$ref:"#/components/schemas/WebhookDelivery"}}}},L={Problem:{type:"object",required:["type","title","status","detail","instance","code"],properties:{type:{type:"string",format:"uri"},title:{type:"string"},status:{type:"integer"},detail:{type:"string"},instance:{type:"string",format:"uri"},code:{type:"string"}},additionalProperties:true},User:{type:"object",required:["id","email","phone","name","image","email_verified","banned","public_metadata","private_metadata","unsafe_metadata","metadata_version","created_at","updated_at"],properties:{id:{type:"string"},email:{type:"string",format:"email"},phone:{type:["string","null"]},name:{type:["string","null"]},image:{type:["string","null"],format:"uri"},email_verified:{type:"boolean"},banned:{type:"boolean"},public_metadata:{$ref:"#/components/schemas/MetadataObject"},private_metadata:{$ref:"#/components/schemas/MetadataObject"},unsafe_metadata:{$ref:"#/components/schemas/MetadataObject"},metadata_version:{type:"integer",minimum:0},created_at:{type:"string",format:"date-time"},updated_at:{type:"string",format:"date-time"}},additionalProperties:false},CreateUser:{type:"object",required:["email"],properties:{email:{type:"string",format:"email",maxLength:320},password:{type:"string",minLength:8,maxLength:128},name:{type:"string",minLength:1,maxLength:200},phone:{type:"string",minLength:1,maxLength:32}},additionalProperties:false},UpdateUser:{type:"object",minProperties:1,properties:{email:{type:"string",format:"email",maxLength:320},name:{type:["string","null"],minLength:1,maxLength:200},phone:{type:["string","null"],minLength:1,maxLength:32},banned:{type:"boolean"}},additionalProperties:false},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},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"]},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","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","status","created_at"],properties:{id:{type:"string",format:"uuid"},status:{type:"string",enum:["pending","processing","completed","failed"]},created_at:{type:"string",format:"date-time"}},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"}}}}]}};var de=new Set(["__proto__","constructor","prototype"]),me=64,ue=5e4;function B(e,t,n){let s=A[e].responseSchemas;Object.hasOwn(s,String(t))||P();let o=s[String(t)];if(o===null){n!==null&&P();return}let a={nodes:0};return g(n,O(o),0,a)||P(),n}function g(e,t,n,r){if(r.nodes+=1,n>me||r.nodes>ue)return false;if(typeof t.$ref=="string"){let o=Se(t.$ref);if(o===null||!g(e,o,n+1,r))return false}if(Array.isArray(t.allOf)&&!t.allOf.every(o=>g(e,O(o),n+1,r))||Array.isArray(t.enum)&&!t.enum.some(o=>Object.is(o,e)))return false;let s=Array.isArray(t.type)?t.type:[t.type];return t.type!==void 0&&!s.some(o=>fe(e,o))?false:e===null?t.type===void 0||s.includes("null"):typeof e=="string"?le(e,t):typeof e=="number"?he(e,t):Array.isArray(e)?ge(e,t,n,r):w(e)?be(e,t,n,r):typeof e=="boolean"}function fe(e,t){switch(t){case "null":return e===null;case "object":return w(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 le(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);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,n,r){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=O(t.items);return e.every(o=>g(o,s,n+1,r))}function be(e,t,n,r){let s=Object.keys(e);if(s.some(a=>de.has(a))||typeof t.minProperties=="number"&&s.length<t.minProperties||typeof t.maxProperties=="number"&&s.length>t.maxProperties)return false;let o=w(t.properties)?t.properties:{};if(Array.isArray(t.required)&&t.required.some(a=>typeof a!="string"||!Object.hasOwn(e,a)))return false;for(let[a,p]of Object.entries(e)){let d=o[a];if(d!==void 0){if(!g(p,O(d),n+1,r))return false;continue}if(t.additionalProperties===false||w(t.additionalProperties)&&!g(p,t.additionalProperties,n+1,r))return false}return true}function Se(e){let t="#/components/schemas/";if(!e.startsWith(t))return null;let n=e.slice(t.length);return Object.hasOwn(L,n)?O(L[n]):null}function O(e){return w(e)||P(),e}function w(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function P(){throw new TypeError("Admin API response does not match its generated contract.")}var _e=/^sk_(?:live|test)_[0-9a-f-]{36}_[A-Za-z0-9]{20,}$/i,Ae=1024*1024,we=1e4,E=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;}},b=class extends Error{kind;requestId;constructor(t,n){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=n;}};function Oe(e){Ee();let t=ke(e?.secretKey),n=Te(e?.apiUrl),r=e?.fetch??globalThis.fetch;if(typeof r!="function")throw new TypeError("A fetch implementation is required in this server runtime.");let s=async(a,p)=>{let d=p??{},m=A[a],y=new URL(Ie(m.path,d).replace(/^\/+/,""),n);Pe(y,d);let f$1=new Headers({accept:"application/json, application/problem+json",authorization:`Bearer ${t}`}),c="body"in d?JSON.stringify(d.body):void 0;c!==void 0&&f$1.set("content-type","application/json");let l;try{l=await g$1({fetchImpl:r,url:y,init:{method:m.method,headers:f$1,body:c,signal:p?.signal},timeoutMs:we,maxResponseBytes:Ae,allowHttpLoopback:n.protocol==="http:",decode:(u,G)=>B(a,G.status,u)});}catch(u){throw u instanceof E?u:u instanceof f?new b(u.kind,u.requestId):new b("network")}let{response:h,requestId:S,data:R}=l;if(!h.ok)throw xe(h,R,S);if(!m.successStatuses.some(u=>u===h.status))throw new b("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 Ee(){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"||!_e.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 n=t.pathname.replace(/\/+$/,"");if(n!==""&&n!=="/api/v1")throw new TypeError("apiUrl path must be empty or /api/v1.");return t.pathname="/api/v1/",t}function Ie(e,t){let n="path"in t&&N(t.path)?t.path:{};return e.replace(/\{([^}]+)\}/g,(r,s)=>{let o=n[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)||!N(t.query)))for(let[n,r]of Object.entries(t.query)){if(r==null)continue;let s=Array.isArray(r)?r:[r];for(let o of s)e.searchParams.append(n,String(o));}}function xe(e,t,n){let r=n??H(e.headers.get("x-request-id"),256),s=H(e.headers.get("retry-after"),128),o=je(e.status,r),a=Le(t)?t:o;return new E({status:e.status,code:a.code,requestId:r,problem:a,retryAfter:s})}function je(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 Le(e){return N(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 N(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function H(e,t){let n=e?.trim();if(!(!n||n.length>t||!/^[\x21-\x7e]+$/.test(n)))return n}var Ne=/^v1=([a-f0-9]{64})$/i,Ke=/^whsec_[A-Za-z0-9_-]{1,256}$/,Re=/^(0|[1-9]\d{0,10})$/;async function ve(e){if(!e||typeof e!="object")throw new TypeError("Webhook verification input must be an object.");let t=Ce(e.secrets),n=e.toleranceSeconds??300;if(!Number.isSafeInteger(n)||n<0||n>3600)throw new TypeError("Webhook toleranceSeconds must be an integer from 0 to 3600.");let r=e.now??Math.floor(Date.now()/1e3);if(!Number.isSafeInteger(r)||r<0)throw new TypeError("Webhook now must be a non-negative Unix timestamp.");let s=ze(e.rawBody);if(s.byteLength>1048576||typeof e.timestamp!="string"||!Re.test(e.timestamp))return false;let o=Number(e.timestamp);if(!Number.isSafeInteger(o)||Math.abs(r-o)>n)return false;let a=Ue(e.signatureHeader);if(a.length===0)return false;let p=new TextEncoder().encode(`${e.timestamp}.`),d=new Uint8Array(p.byteLength+s.byteLength);d.set(p),d.set(s,p.byteLength);let m=false;for(let y of t){let f=await crypto.subtle.importKey("raw",new TextEncoder().encode(y),{name:"HMAC",hash:"SHA-256"},false,["sign"]),c=new Uint8Array(await crypto.subtle.sign("HMAC",f,d));for(let l of a)m=We(c,l)||m;}return m}function Ce(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 Ue(e){if(typeof e!="string"||e.length>1024)return [];let t=e.split(",");if(t.length>4)return [];let n=[];for(let r of t){let s=Ne.exec(r.trim());s&&n.push(Me(s[1]));}return n}function ze(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 Me(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}function We(e,t){if(e.byteLength!==t.byteLength)return false;let n=0;for(let r=0;r<e.byteLength;r+=1)n|=e[r]^t[r];return n===0}var F=["publishableKey","apiUrl","issuer","jwksUri","audience"],$e=new Set([...F,"clockToleranceSeconds"]);function K(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=>!$e.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))),n=t.has("publishableKey")||t.has("apiUrl"),r=t.has("issuer")||t.has("jwksUri")||t.has("audience");if(n&&r)throw new Error("AuthOwl token verification config cannot mix publishableKey/apiUrl with issuer/jwksUri/audience.");if(r){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 I({issuer:e$1.issuer,jwksUri:e$1.jwksUri,audience:e$1.audience,clockToleranceSeconds:e$1.clockToleranceSeconds})}let s,o;if(n){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 I({issuer:a.projectBaseURL,jwksUri:`${a.projectBaseURL}/jwks`,audience:a.decoded.projectId,clockToleranceSeconds:e$1?.clockToleranceSeconds},a.decoded.env==="test")}async function st(e,t){return _(e,K(t))}async function ot(e,t,n){let r=K(n);try{let s=await _(e,r);return u(s.membership,t)}catch{return false}}async function it(e,t,n){let r=K(n);try{let s$1=await _(e,r);return s(s$1.membership,t.permission)}catch{return false}}export{ce as ADMIN_API_SPEC_SHA256,E as AuthOwlAdminApiError,b as AuthOwlAdminNetworkError,i as TokenVerificationError,Oe as createAdminClient,ot as has,it as hasPermission,pe as verifyProjectToken,st as verifyToken,ve as verifyWebhook};
|
|
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};
|
|
@@ -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 i of n)e+=String.fromCharCode(i);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 i=window.location.protocol==="https:"?"; Secure":"";document.cookie=`${u}=${n}; Path=/; Max-Age=${e}; SameSite=Lax${i}`;}function R(){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 y(){p("",0);}function l(n){return new URL(n,window.location.href).toString()}async function b(n,e){let i=e.callbackURL?l(e.callbackURL):null;if(i&&new URL(i).origin!==window.location.origin)return null;let t=h(),o=new URL(`${n.projectBaseURL}/session/start`);if(o.searchParams.set("pk",n.publishableKey),o.searchParams.set("kind",e.kind),e.kind==="social")o.searchParams.set("provider",e.provider),e.scopes?.length&&o.searchParams.set("scopes",e.scopes.join(",")),e.loginHint&&o.searchParams.set("loginHint",e.loginHint),e.requestSignUp!==void 0&&o.searchParams.set("requestSignUp",e.requestSignUp?"1":"0");else for(let s of m){let r=e[s];r&&o.searchParams.set(s,r);}let d=`${window.location.origin}${window.location.pathname}${window.location.search}`;o.searchParams.set("cb",i??d);for(let[s,r]of [["err",e.errorCallbackURL],["new",e.newUserCallbackURL]])r&&o.searchParams.set(s,l(r));return o.searchParams.set("challenge",await w(t)),p(t,S),o.toString()}function U(){if(typeof window>"u")return null;let n=window.location.hash;if(!n.includes(a))return null;let e=new URLSearchParams(n.replace(/^#/,"")),i=e.get(a);if(!i)return null;e.delete(a);let t=e.toString();return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${t?`#${t}`:""}`),i}async function k(n){if(!a$1())return false;let e=U();if(!e)return false;let i=R();if(y(),!i)return false;let{error:t}=await n.request("/session/exchange",{method:"POST",body:{code:e,verifier:i}});return t===null}
|
|
2
|
+
export{b as beginCrossSiteSignIn,w as challengeFor,k as completeCrossSiteSignIn,U as takeHandoffCode};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@authowl/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "Framework-agnostic client for AuthOwl, the multi-tenant auth SaaS.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -72,7 +72,11 @@
|
|
|
72
72
|
"THIRD_PARTY_NOTICES.md",
|
|
73
73
|
"LICENSE"
|
|
74
74
|
],
|
|
75
|
+
"dependencies": {
|
|
76
|
+
"@akedly/shield": "1.0.2"
|
|
77
|
+
},
|
|
75
78
|
"devDependencies": {
|
|
79
|
+
"jsdom": "26.1.0",
|
|
76
80
|
"tsup": "^8.3.5",
|
|
77
81
|
"typescript": "^5.7.2",
|
|
78
82
|
"vitest": "^4.1.10"
|
package/dist/chunk-SM5LS47O.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {f,g,q as q$1,j as j$1,h,p,n,s,u,o,k as k$1,r,m as m$1,i,l}from'./chunk-KPXCQZUX.js';function di(e){let t=e?.enabledMethods??["password"],n=t.includes("password"),i=t.includes("passkey"),o=e?.authentication,a=e?.mfa;return {emailSignUp:o?.email.signUp??t.some(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 Wt="x-authowl-turnstile-token",Xt=1e4,$t=32,Yt=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=en(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(Wt,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 O=Zt(a,i.fetchOptions),c;try{c=await Qt(e,o,{...s,signal:i.fetchOptions?.signal},O);}catch(D){let fe=be(D);return await i.fetchOptions?.onError?.(Z(u,fe,on(D))),{data:null,error:fe}}let{response:l,requestId:g}=c,f$1=sn(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=tn(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 Qt(e,t,n,i){let o=Date.now()+Xt;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 rn(50*2**a,n.signal,o);}throw new f("network")}function Zt(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 en(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 tn(e,t,n){let i=F(t)?t:{},o=nn(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 nn(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 on(e){return e instanceof f?e.kind:"network"}function rn(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>$t||i.nodes>Yt)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,an(o)?a:te(a,o,n+1,i)])):e}function an(e){return e==="metadata"||e==="public_metadata"||e==="unsafe_metadata"||e==="private_metadata"||e==="publicMetadata"||e==="unsafeMetadata"||e==="privateMetadata"}function sn(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 O(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:O,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,un)),listSessions:o=>e.request("/list-sessions",{fetchOptions:o,decode:cn}),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:dn});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,ln),unlinkSocial:(o,a)=>i(n("/unlink-account",o,a,q)),delete:(o={},a)=>i(n("/delete-user",o,a,pn))}}function q(e){let t=h(e);return {status:j$1(t.status)}}function un(e){let t=h(e);return {user:n(t.user)}}function cn(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 dn(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 ln(e){let t=h(e);return {url:i(t.url),redirect:j$1(t.redirect)}}function pn(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 gn=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),...K("logo",m$1(i,"logo")),...K("metadata",i.metadata===void 0?void 0:r(i.metadata))};return z(o.id,t),z(o.slug,n),o}function ze(e){return 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=>Ke(i));return j(n.map(i=>i.organizationId),t),n}function Ne(e,t,n){return e===null?null:(t===null&&p(),Ke(e,t,n))}function Ue(e,t){let n=h(e);return (!Number.isSafeInteger(n.total)||n.total<0)&&p(),{members:fn(n.members,t),total:n.total}}function v(e,t,n){let i=h(e),o=m(i.status);gn.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 Be(e,t){let n=C(e,i=>{let o=h(i);return {organizationId:m(o.organizationId),data:{role:m(o.role),...K("permission",o.permission===void 0?void 0:mn(o.permission))}}});return j(n.map(i=>i.organizationId),t),n.map(i=>i.data)}function Ke(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 fn(e,t){let n=C(e,i=>je(i));return j(n.map(i=>i.organizationId),t),n}function mn(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),...K("image",m$1(t,"image"))}}function C(e,t){return Array.isArray(e)||p(),e.map(n=>t(n))}function K(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,O)=>e.request(r,{query:s,fetchOptions:u,decode:O});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=>Be(u,r.organizationId)),has:r=>u(n(),r),hasPermission:r=>s(n(),r.permission)}}var We=4096,hn=4096,An=100,yn=256,On=16,bn=64;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:lt(t.twoFactorMethods,On,bn)}}):(t.twoFactorRedirect!==void 0&&p(),{redirect:j$1(t.redirect),...In(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);return (t.status!==true||t.sessionCreated!==true)&&p(),{status:true,sessionCreated:true,user:wn(t.user)}}function re(e){return {status:j$1(h(e).status)}}function it(e){return {status:j$1(h(e).status)}}function ot(e){let t=h(e);return {status:j$1(t.status),user:n(t.user)}}function rt(e){return {success:j$1(h(e).success)}}function at(e){let t=h(e);return {totpURI:Sn(t.totpURI),backupCodes:dt(t.backupCodes)}}function st(e){return {status:j$1(h(e).status)}}function J(e){return h(e).status!==true&&p(),{status:true}}function ut(e){return {status:j$1(h(e).status)}}function ct(e){let t=h(e);return t.status!==void 0&&t.status!==true&&p(),{backupCodes:dt(t.backupCodes)}}function wn(e){let t=h(e);return {id:M(t.id,512),...Rn(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:"&&kn(i.hostname)?i.href:p()}function kn(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}function Sn(e){let t=M(e,hn),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 dt(e){return lt(e,An,yn)}function lt(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 In(e,t){let n=e[t];return n==null?{}:{[t]:M(n,We)}}function Rn(e,t,n){let i=m$1(e,t);return i===void 0?{}:(i!==null&&i.length>n&&p(),{[t]:i})}var pt=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||ft(n,i)||gt(i)||pt.has(i))return {valid:false}}let t=Tn(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||ft(o,a)||gt(a)||pt.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 Tn(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 gt(e){return e>=0&&e<=31||e>=127&&e<=159}function ft(e,t){return e.length===1&&t>=55296&&t<=57343}var At=12,yt=5e3,Pn=8,vn=1e3,xn=16,mt=512,Ot=100,bt=8192,Dn=32768,se=1024,ht=256,ce=64,zn=6e5,Cn=/^[A-Za-z0-9_-]+$/u,En=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u,Nn=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u,Un=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/u,Mn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,wt=new Set(["discouraged","preferred","required"]),_n=new Set(["singleDevice","multiDevice"]),kt=new Set(["ble","cable","hybrid","internal","nfc","smart-card","usb"]),St=new Set(["hybrid","security-key","client-device"]),Ln=new Set(["none","indirect","direct","enterprise"]),Fn=new Set(["fido-u2f","packed","android-safetynet","android-key","tpm","apple","none"]),qn=new Set(["platform","cross-platform"]),Vn=new Set(["discouraged","preferred","required"]),Hn=new Set([-8,-7,-257]);function It(e){let t=q$1(e,At,yt);return {challenge:Nt(t.challenge),...A("timeout",Ct(t.timeout)),...A("rpId",Ut(t.rpId)),...A("allowCredentials",zt(t.allowCredentials)),...A("userVerification",V(t.userVerification,wt)),...A("hints",$(t.hints,St)),...A("extensions",Et(t.extensions))}}function Rt(e){let t=q$1(e,At,yt);return {challenge:Nt(t.challenge),rp:Bn(t.rp),user:Kn(t.user),pubKeyCredParams:jn(t.pubKeyCredParams),...A("timeout",Ct(t.timeout)),...A("excludeCredentials",zt(t.excludeCredentials)),...A("authenticatorSelection",Jn(t.authenticatorSelection)),...A("attestation",V(t.attestation,Ln)),...A("attestationFormats",$(t.attestationFormats,Fn)),...A("hints",$(t.hints,St)),...A("extensions",Et(t.extensions))}}function Tt(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,_n),o=j$1(t.backedUp);return o&&i!=="multiDevice"&&p(),{id:_(t.id,ht),...Xn(t),publicKey:Gn(t.publicKey,Dn),userId:_(t.userId,ht),credentialID:Q(t.credentialID,bt),counter:n,deviceType:i,backedUp:o,...$n(t),createdAt:k$1(t.createdAt),...Yn(t)}}function Pt(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 vt(e){(!Array.isArray(e)||e.length>Ot)&&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 xt(e,t,n){let i=h(e),o=de(i.passkey);return (o.id!==t||o.name!==n)&&p(),{passkey:o}}function Dt(e){return h(e).status!==true&&p(),{status:true}}function Bn(e){let t=h(e);return {name:ue(t.name,se),...A("id",Ut(t.id))}}function Kn(e){let t=h(e);return {id:Q(t.id,128,1,64),name:ue(t.name,se),displayName:ue(t.displayName,se)}}function jn(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)||!Hn.has(i.alg))&&p(),{type:"public-key",alg:i.alg}});return Qn(t.map(n=>n.alg)),t}function zt(e){if(e===void 0)return;(!Array.isArray(e)||e.length>Ot)&&p();let t=e.map(n=>{let i=h(n);return i.type!=="public-key"&&p(),{type:"public-key",id:Q(i.id,bt),...A("transports",$(i.transports,kt))}});return Y(t.map(n=>n.id)),t}function Jn(e){if(e===void 0)return;let t=h(e);t.requireResidentKey!==void 0&&typeof t.requireResidentKey!="boolean"&&p();let n=V(t.residentKey,Vn);return t.requireResidentKey!==void 0&&n!==void 0&&t.requireResidentKey!==(n==="required")&&p(),{...A("authenticatorAttachment",V(t.authenticatorAttachment,qn)),...A("residentKey",n),...A("requireResidentKey",t.requireResidentKey),...A("userVerification",V(t.userVerification,wt))}}function Ct(e){return e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0||e>zn)&&p(),e}function Et(e){return e===void 0?void 0:q$1(e,Pn,vn)}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 Nt(e){return Q(e,Math.ceil(mt*4/3),xn,mt)}function Q(e,t,n=1,i=Number.POSITIVE_INFINITY){let o=_(e,t),a=o.length%4,r=Wn(o.at(-1)??""),s=Math.floor(o.length*3/4);return (!Cn.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 Nn.test(n)&&p(),n}function Ut(e){if(e===void 0)return;let t=_(e,253);return t!=="localhost"&&(t.endsWith(".")||!t.includes(".")||t.split(".").some(n=>!Un.test(n)))&&p(),t}function Gn(e,t){let n=_(e,t),i=n.endsWith("=="),o=!i&&n.endsWith("="),a=n.at(i?-3:o?-2:-1)??"",r=Mt(a);return (n.length%4!==0||!En.test(n)||i&&(r&15)!==0||o&&(r&3)!==0)&&p(),n}function Wn(e){return Mt(e,true)}function Mt(e,t=false){return (t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").indexOf(e)}function Xn(e){let t=m$1(e,"name");return t===void 0?{}:(t!==null&&!ae(t)&&p(),{name:t})}function $n(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=>!kt.has(i))||new Set(n).size!==n.length)&&p(),{transports:t}}function Yn(e){let t=m$1(e,"aaguid");return t==null?t===void 0?{}:{aaguid:null}:(Mn.test(t)||p(),{aaguid:t})}function le(e,t){let n=i(e);return t.has(n)||p(),n}function A(e,t){return t===void 0?{}:{[e]:t}}function Y(e){new Set(e).size!==e.length&&p();}function Qn(e){new Set(e).size!==e.length&&p();}function Zn(e,t=()=>{},n=ni){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),O=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,O)),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,O));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,ot))},phoneOtp:{start:(c,l)=>s("/phone-otp/start",{...c,idempotencyKey:c.idempotencyKey??ke()},l,tt),verify:(c,l)=>u(s("/phone-otp/verify",c,l,nt))},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,it),passkey:{addPasskey:(c,l)=>a.add(c,l),listUserPasskeys:()=>i.request("/passkey/list-user-passkeys",{decode:vt}),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=>xt(w,c.id,f))},deletePasskey:(c,l)=>s("/passkey/delete-passkey",c,l,Dt)},twoFactor:{enable:(c,l)=>s("/two-factor/enable",c,l,at),disable:(c,l)=>u(s("/two-factor/disable",c,l,st),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,ut),verifyOtp:(c,l)=>u(s("/two-factor/verify-otp",c,l,J)),generateBackupCodes:(c,l)=>s("/two-factor/generate-backup-codes",c,l,ct)},signOut:c=>u(i.request("/sign-out",{method:"POST",body:{},fetchOptions:c,decode:rt}),l=>l.success)}}function Bi(e,t=()=>{},n){let i=Zn(e,t,n);return n?{...i,signIn:{email:i.signIn.email,username:i.signIn.username,social:_t(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:_t(i),magicLink:i.signIn.magicLink,emailOtp:i.signIn.emailOtp},passkey:{listUserPasskeys:i.passkey.listUserPasskeys,updatePasskey:i.passkey.updatePasskey,deletePasskey:i.passkey.deletePasskey}}}function _t(e){return async(t,n)=>{if(!t?.idToken||typeof t.idToken.token!="string"||t.idToken.token==="")return ei();let i=await e.signIn.social({...t,disableRedirect:true},n);return i.data!==null&&"url"in i.data?ti():i}}function ei(){return Promise.resolve({data:null,error:{status:400,statusText:"BAD_REQUEST",code:"NATIVE_SOCIAL_ID_TOKEN_REQUIRED",message:"Native social sign-in requires a provider ID token."}})}function ti(){return Promise.resolve({data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_NATIVE_SOCIAL_RESPONSE",message:"The server returned a redirect for native ID-token sign-in."}})}function ni(){return {signIn:()=>Lt(),add:()=>Lt()}}function Lt(){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 Gi(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 Vt(r.error);let s;try{s=It(r.data);}catch{return Ft()}let u;try{u=await n.authenticate({optionsJSON:s,useBrowserAutofill:o.autoFill});}catch(f){return Ht(n,f,"AUTH_CANCELLED","Passkey authentication was cancelled.")}if(!ii(u))return qt();let{clientExtensionResults:O,...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:Tt});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 Vt(s.error);let u;try{u=Rt(s.data);}catch{return Ft()}let O;try{O=await n.register({optionsJSON:u});}catch(f){return Ht(n,f,"REGISTRATION_CANCELLED","Passkey registration was cancelled.")}if(!oi(O))return qt();let{clientExtensionResults:c,...l}=O,g=await e.request("/passkey/verify-registration",{method:"POST",body:{response:l,name:r.value},fetchOptions:a,decode:f=>Pt(f,O.id,r.value)});return g.data&&t(),g}}}function Ft(){return {data:null,error:{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned invalid WebAuthn options."}}}function qt(){return {data:null,error:{status:400,statusText:"BAD_REQUEST",code:"INVALID_WEBAUTHN_RESPONSE",message:"The platform returned an invalid passkey response."}}}function 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 ii(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 oi(e){if(!Bt(e))return false;let t=e.response;return typeof t.clientDataJSON=="string"&&typeof t.attestationObject=="string"}function Vt(e){return {data:null,error:e??{status:502,statusText:"BAD_GATEWAY",code:"INVALID_WEBAUTHN_OPTIONS",message:"The server returned no WebAuthn options."}}}function Ht(e,t,n,i){let o=ai(t,"page does not have focus"),a=e.errorCode?.(t),r=a!==void 0?a==="ERROR_CEREMONY_ABORTED":ri(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 ri(e){return e&&typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:void 0}function ai(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 Kt(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 Zi(e){let n=`${new URL(e.apiUrl).origin}/api/projects/${e.decoded.projectId}/public-config`;return jt(await Kt(e,n,{init:{method:"GET",credentials:"omit"},maxResponseBytes:256*1024,decode:i=>si(i,e)}),"public-config")}function si(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"||!ui(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)||!Gt(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"||!Gt(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(O=>typeof O!="string"||O.length>2048))throw T()}if(!x(n,["requireEmailVerification","twoFactor","mfaRequired","accountDeletion","organizations","sso","badge"])||!Jt(n.turnstileSiteKey)||!Jt(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&&ci(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 ui(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 Jt(e){return e===null||typeof e=="string"&&e.length<=4096}function ci(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 Gt(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{di as a,Wt as b,we as c,ke as d,Zn as e,Bi as f,Gi as g,pe as h,Kt as i,jt as j,Zi as k};
|